codex-copilot-dx 0.9.33 → 0.9.34

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
@@ -2,8 +2,7 @@
2
2
 
3
3
  Use Codex App with GitHub Copilot through a local adapter.
4
4
 
5
- CCDX targets Codex App. It discovers Copilot models, adapts the client's model
6
- catalog, and preserves Responses streaming, tool calls and conversation history.
5
+ CCDX targets Codex App: Copilot discovery, adapted model catalogs, Responses streaming, tool calls and conversation history.
7
6
  Default Auto-review: **GPT-6.1 Sol / low**. Image generation is **off by default**. Native predictions are also **off by default**.
8
7
 
9
8
  ## Install and run
@@ -23,7 +22,7 @@ enabled. If PowerShell blocks scripts, use `npm.cmd` / `ccdx.cmd`; do not change
23
22
 
24
23
  Open [the local dashboard](http://127.0.0.1:2026/) for status, model discovery,
25
24
  usage, cache/limits, recent failures, request context and animation settings.
26
- Auto refresh runs every 30 minutes while visible and can be switched off. Hidden pages pause; opening sections and manual refresh still work.
25
+ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden pages pause; opening sections and manual refresh still work. Startup uses an atom icon and aligned checks; `Ready` refers to the core service. Narrow/non-color terminals use a plain title.
27
26
 
28
27
  ## Commands
29
28
 
@@ -75,6 +74,7 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
75
74
  Other domains and the CCDX model endpoint stay on their existing routes.
76
75
  No program files or OS trust are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are retained.
77
76
  Windows supports company PAC/WPAD; macOS dynamic routing remains unsupported. Windows setup needs the official MSIX App, Windows PowerShell and .NET Framework 4.7.2+—not Git/OpenSSL. See the reference for limits.
77
+ Bridge checks allow three same-port recovery attempts per process, without App restart/replay. Only closed, initialized Apps in direct environments receive an owned persistent route; user/company proxies are preserved. Missing routes in running Apps are not hot-attached.
78
78
  - CCDX adds experimental local history compression only when installed App
79
79
  runtimes support it and report it off. Existing choices are preserved; an
80
80
  already-enabled default, unavailable runtime or failed check is skipped.
package/bin/cli.mjs CHANGED
@@ -22,6 +22,7 @@ import { createProfileRuntime } from "../src/profile-runtime.mjs";
22
22
  import { createProfileModelRuntime } from "../src/profile-model-runtime.mjs";
23
23
  import { createCodexModelCatalog } from "../src/codex-model-catalog.mjs";
24
24
  import { setResponseHistoryMaxBytes } from "../src/response-history.mjs";
25
+ import { startupBanner, startupCheck, startupReady, startupLogger, predictionStartupCheck } from "../src/startup-ui.mjs";
25
26
 
26
27
  const LOCAL_VERSION = localPackageVersion();
27
28
  const CLI_NAME = cliCommandName();
@@ -271,7 +272,8 @@ async function clientIntegrations() {
271
272
  if (!clientIntegration) {
272
273
  const { createClientIntegration } = await import("../src/client-integration.mjs");
273
274
  clientIntegration = createClientIntegration({ port: ADAPTER_PORT, host: ADAPTER_HOST,
274
- info: (message) => console.log(status("info", message)), warning: (message) => console.warn(status("warn", message)) });
275
+ configLog: startupLogger("Config"),
276
+ info: (message) => console.log(startupCheck("info", "Client", message)), warning: (message) => console.warn(startupCheck("warn", "Client", message)) });
275
277
  }
276
278
  return clientIntegration;
277
279
  }
@@ -293,30 +295,36 @@ async function reuseRunningAdapterIfAvailable() {
293
295
  }
294
296
  if (!running.ok) return false;
295
297
 
296
- console.log(status("ok", `Using existing adapter at ${running.baseUrl}`));
297
- const { compressionSetup } = await configureCodexClient();
298
+ console.log(startupCheck("ok", "Adapter", `Using existing service at ${running.baseUrl}`));
299
+ console.log(startupCheck("info", "Auth", "Using existing service credentials; not rechecked"));
300
+ const { compressionSetup, imageEnabled, imageMcpSkipped } = await configureCodexClient();
298
301
 
299
302
  let predictionPacUrl = null;
300
303
  let predictionApp = null;
301
304
  let predictionProfile = null;
305
+ let persistedPredictionRoute = false;
306
+ let predictionConfigured = false;
307
+ let launchRoute = "unknown";
302
308
  try {
303
309
  const { readPredictionSettings } = await import("../src/native-prediction-profile.mjs");
304
310
  const preference = readPredictionSettings();
311
+ predictionConfigured = preference.enabled;
305
312
  if (preference.enabled) {
306
313
  predictionPacUrl = running.data?.native_prediction_pac || null;
307
314
  predictionApp = preference.app?.app;
308
315
  predictionProfile = preference.app?.profile;
316
+ const { hasInstalledPredictionRoute } = await import("../src/native-prediction-route.mjs");
317
+ const { predictionPaths } = await import("../src/native-prediction-profile.mjs");
318
+ persistedPredictionRoute = hasInstalledPredictionRoute({ ...predictionPaths({ app: preference.app }), pacUrl: predictionPacUrl });
309
319
  if (!predictionPacUrl) console.warn(status("warn", "Restart ccdx to activate the newly enabled prediction bridge"));
310
320
  }
311
321
  } catch (error) { console.warn(status("warn", error.message)); }
312
- await openCodex({ predictionPacUrl, predictionApp, predictionProfile });
313
- console.log(`
314
- ${status("ok", "Ready, using the existing ccdx adapter")}
315
-
316
- Adapter: ${running.baseUrl}
317
-
318
- Tip: Run ${CLI_NAME} help to view more features and commands.
319
- `);
322
+ await openCodex({ predictionPacUrl, predictionApp, predictionProfile, persistedPredictionRoute,
323
+ onPredictionRoute: route => { launchRoute = route; }, log: startupLogger("App") });
324
+ console.log(predictionStartupCheck({ configured: predictionConfigured, bridge: predictionPacUrl ? "running" : "unknown", launch_route: launchRoute }));
325
+ console.log(startupCheck(imageEnabled && imageMcpSkipped ? "warn" : "info", "Images", imageEnabled
326
+ ? imageMcpSkipped ? "Client setup skipped; see warning above" : "Configured; provider not tested" : "Off"));
327
+ console.log(startupReady({ baseUrl: running.baseUrl, commandName: CLI_NAME, reused: true }));
320
328
  await compressionSetup;
321
329
  return true;
322
330
  }
@@ -337,17 +345,14 @@ if (CLI.command === "doctor") {
337
345
  process.exit(checks.some((check) => check.kind === "err") ? 1 : 0);
338
346
  }
339
347
 
340
- console.log(`
341
- ${CLI_BANNER}
342
- Use Codex App with GitHub Copilot
343
- `);
348
+ console.log(`\n${startupBanner({ commandName: CLI_NAME, version: LOCAL_VERSION })}\n`);
344
349
 
345
350
  async function printUpdateNotice() {
346
351
  try {
347
352
  const { latestVersion, updateAvailable } = await checkForUpdate({ currentVersion: LOCAL_VERSION });
348
353
  if (!updateAvailable) return;
349
- console.log(`\n ${status("warn", `Update available: ${LOCAL_VERSION} -> ${latestVersion}`)}`);
350
- console.log(` Run ${CLI_NAME} update github to update, then restart ${CLI_NAME}.\n`);
354
+ console.log(`\n${status("warn", `Update available: ${LOCAL_VERSION} -> ${latestVersion}`)}`);
355
+ console.log(`Run ${CLI_NAME} update github to update, then restart ${CLI_NAME}.\n`);
351
356
  } catch {
352
357
  // Never block startup on the update check.
353
358
  }
@@ -364,7 +369,7 @@ try {
364
369
  }
365
370
 
366
371
  // Ensure GitHub login, using device flow if no token exists.
367
- await ensureAuth();
372
+ await ensureAuth({ log: startupLogger("Auth") });
368
373
 
369
374
  const profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient });
370
375
  const profileModels = createProfileModelRuntime({
@@ -373,11 +378,15 @@ try {
373
378
  timeoutMs: MODEL_REFRESH_TIMEOUT_MS,
374
379
  commandName: CLI_NAME,
375
380
  autoReviewModelResolver: () => autoReviewModelPreference().model,
381
+ log: (kind, message) => console.log(startupCheck(kind, "Models", message)),
376
382
  });
377
383
 
378
384
  // Refresh the VS Code version in the background; fallback is non-blocking.
379
385
  void refreshVSCodeVersion();
380
386
  await profileModels.initialize();
387
+ if (profileModels.codexRegistry.source !== "live") {
388
+ console.log(startupCheck("info", "Models", `${profileModels.codexRegistry.source} list loaded${profileModels.codexRegistry.refreshInFlight ? "; refreshing" : ""}`));
389
+ }
381
390
 
382
391
  if (!isLoopbackHost(ADAPTER_HOST)) {
383
392
  console.log(status("warn", `ADAPTER_HOST=${ADAPTER_HOST} exposes the adapter beyond loopback because CCDX_ALLOW_LAN=1 is set. Use only on trusted networks.`));
@@ -387,6 +396,7 @@ try {
387
396
  const terminalAnimationTheme = terminalAnimationPreference().theme;
388
397
  const codexModelCatalog = createCodexModelCatalog();
389
398
  activeServer = await startAdapter(ADAPTER_PORT, ADAPTER_HOST, {
399
+ log: startupLogger("Adapter"),
390
400
  autoReviewModelResolver: () => autoReviewPreference(),
391
401
  codexClient: profileRuntime.codexClient,
392
402
  codexModelCatalog,
@@ -401,13 +411,19 @@ try {
401
411
  });
402
412
 
403
413
  // Point Codex App at the adapter.
404
- const { compressionSetup } = await configureCodexClient();
414
+ const { compressionSetup, imageEnabled, imageMcpSkipped } = await configureCodexClient();
405
415
 
406
416
  // Optional native prediction setup must never prevent the core adapter from running.
407
417
  nativePrediction = await (await clientIntegrations()).start();
418
+ const persistentRoute = await nativePrediction?.prepareRoute();
408
419
 
409
420
  // Launch Codex when available. A running App is never forcibly restarted.
410
- await openCodex({ predictionPacUrl: nativePrediction?.pacUrl, predictionApp: nativePrediction?.app, predictionProfile: nativePrediction?.profile });
421
+ await openCodex({ predictionPacUrl: nativePrediction?.pacUrl, predictionApp: nativePrediction?.app, predictionProfile: nativePrediction?.profile,
422
+ preparePredictionRoute: () => nativePrediction?.prepareRoute(), persistedPredictionRoute: persistentRoute?.status === "installed",
423
+ onPredictionRoute: route => clientIntegration?.launched(route), log: startupLogger("App") });
424
+ console.log(predictionStartupCheck(clientIntegration?.snapshot().prediction));
425
+ console.log(startupCheck(imageEnabled && imageMcpSkipped ? "warn" : "info", "Images", imageEnabled
426
+ ? imageMcpSkipped ? "Client setup skipped; see warning above" : "Configured; provider not tested" : "Off"));
411
427
 
412
428
  // Periodically refresh the model list + endpoint cache so a long-running
413
429
  // adapter picks up newly released models without a restart.
@@ -419,15 +435,7 @@ try {
419
435
  modelRefreshTimer.unref?.();
420
436
  }
421
437
 
422
- console.log(`
423
- ${status("ok", "Ready, CCDX adapter is ready to use")}
424
-
425
- Adapter: ${adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT)}
426
-
427
- Tip: Run ${CLI_NAME} help to view more features and commands.
428
-
429
- Press Ctrl+C to stop.
430
- `);
438
+ console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
431
439
 
432
440
  const shutdown = async (signal) => {
433
441
  if (shuttingDown) return;
@@ -64,9 +64,24 @@ prediction lifecycle, with locked first-start persistence and no replacement
64
64
  on conflict. OS process inspection stays in the launcher/platform boundary;
65
65
  it runs only for explicit prediction-enabled launch/reuse, not per model request.
66
66
  macOS uses bounded system `ps` reads and Windows retains its existing registered
67
- process checks. No process is stopped, no permanent watcher or dependency is
67
+ process checks. No process is stopped and no App-process watcher or dependency is
68
68
  added. Core inference keeps its existing service port and lifecycle.
69
69
 
70
+ `native-prediction-recovery.mjs` supervises only the enabled optional bridge,
71
+ using a low-cost listener check, same-route restart, single-flight recovery and
72
+ a three-attempt budget. It does not watch App processes, modify proxy policy or
73
+ replay inference. `native-prediction-route.mjs` separately owns the closed-profile
74
+ preference transaction and its rollback metadata. It accepts direct environments
75
+ only, preserves company/user routing, and never treats a saved preference as
76
+ proof of a running route or visible candidate. App compatibility is rechecked only
77
+ when its recorded identity changes, before existing trust/port checks are reused.
78
+
79
+ `startup-ui.mjs` is pure terminal presentation: a static A atom, aligned checks
80
+ and the common new/reused-service footer. It depends only on terminal/status
81
+ utilities, not on inference or platform probes. The CLI feeds existing lifecycle
82
+ results into it; presentation does not run doctor, call models or wait for optional
83
+ background tasks. All status tags share one fixed-width column.
84
+
70
85
  Connection-ownership replay rejection is a provider-owned retry policy. It
71
86
  removes only unavailable reasoning once, preserving visible history and tools.
72
87
  Opaque compaction cannot be assumed equivalent to remaining plaintext. The
package/docs/REFERENCE.md CHANGED
@@ -155,8 +155,10 @@ fallback after upstream-proxy rejection is added. The default App profile
155
155
  is `~/Library/Application Support/Codex`; an explicit
156
156
  `CODEX_ELECTRON_USER_DATA_PATH` is respected. Quit the App before trust changes;
157
157
  CCDX never kills it. The launcher uses the exact App that passed the compatibility
158
- check. Updating the App invalidates that check: quit it and run `prediction on`
159
- again. Unknown client/store/configuration formats are not forcibly rewritten.
158
+ check. A changed App is rechecked once at bridge startup using the existing
159
+ signature/protocol and profile checks. The exact App/profile identity, saved port
160
+ and trust must remain unchanged; unsupported updates still require explicit setup.
161
+ Unknown client/store/configuration formats are not forcibly rewritten.
160
162
  These are checked compatibility boundaries, not a promise for every future App.
161
163
 
162
164
  The bridge changes only its own prediction fields and preserves already-enabled
@@ -173,14 +175,17 @@ provide a separate prediction-model picker.
173
175
  `prediction off` immediately disables new local overlays. Quit/reopen Codex to
174
176
  clear its cached predictions and temporary route. If the App is still running,
175
177
  trust removal is deferred; quit it and run `prediction off` again. Only the exact
176
- owned certificate record is removed, never the whole store. Failed activation
178
+ owned certificate record is removed, never the whole store. A CCDX-owned persistent
179
+ proxy preference is restored first, preserving all unrelated preference values.
180
+ User-replaced proxy preferences are not restored over. Failed activation
177
181
  rolls back newly added trust; certificate replacement keeps old trust until the
178
182
  new preference is committed. If the bridge stops, new connections can fall back
179
183
  to the original route; already-interrupted requests are not replayed. An App
180
184
  already using the saved address need not be relaunched just because CCDX restarts.
181
185
  If its route is missing or differs, fully quit Codex and run `ccdx` to attach it.
182
- `CCDX_AUTO_LAUNCH=0` keeps
183
- automatic launch disabled and does not attach the route to a manually opened App.
186
+ `CCDX_AUTO_LAUNCH=0` keeps automatic launch disabled and never hot-attaches a
187
+ running App. An already-persisted direct-environment preference can still be read
188
+ when the App is manually opened.
184
189
  Optional prediction failures never prevent the core adapter or image service from
185
190
  starting. `prediction status` reports the saved preference and, when a compatible
186
191
  running adapter responds, its bridge state, configuration-response observations
@@ -191,6 +196,36 @@ no prompt matching, UI injection, transcript scanning or extra inference is used
191
196
  to invent that status. Prediction settings are stored separately in
192
197
  `~/.config/codex-copilot-dx/native-prediction/` (or under `XDG_CONFIG_HOME`).
193
198
 
199
+ Since `0.9.34`, an enabled bridge has a lightweight 30-second listener check.
200
+ Healthy checks do not spawn processes, call upstream, inspect transcripts or
201
+ probe model endpoints. A failed owned listener/native company-routing worker can
202
+ 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
204
+ backoff gates; checks themselves run every 30 seconds. Occupied ports are not
205
+ stolen or rotated. Startup failures do not gain a retry loop, and configuration
206
+ HTTP errors or missing gray text alone do not trigger transport restarts. Existing
207
+ requests can fail during an outage and are never replayed by this supervisor.
208
+ Disabled prediction startup creates no recovery timer. The existing in-memory
209
+ overlay switch still observes explicit on/off changes independently.
210
+
211
+ Before enabled App launch, CCDX can persist its PAC in that verified profile's
212
+ `Default/Preferences`, but only in a direct environment, with initialized regular
213
+ profile files and the App closed. Existing explicit App proxies and all company
214
+ static/PAC/WPAD routes are preserved. Ownership intent is stored in `route.json`
215
+ before changing the one proxy field; unrelated settings are retained, concurrent
216
+ edits fail closed, and matching setup is not rewritten. If an App is already
217
+ running, first-time migration is deferred until a normal closed-App launch;
218
+ CCDX does not claim it can hot-attach a missing route. A manually reopened App
219
+ with a saved preference is reported as awaiting configuration traffic, not as
220
+ launch-route verified. This preference is a prevention measure, not a guarantee
221
+ for every future Chromium profile format or OS version. Company proxy users keep
222
+ the verified launch-argument path. Core inference/image routes are unchanged.
223
+
224
+ `prediction status` and `ccdx status` also expose launch-route evidence, persistent
225
+ route state, recovery attempts and recoveries. These are independent of the
226
+ unknown candidate-visibility value. A successful recovery only means the bridge
227
+ was recreated on the original address, not that gray text appeared.
228
+
194
229
  ### Configuration ownership
195
230
 
196
231
  Core setup, image setup/guidance, config doctor, optional history compression and
@@ -366,7 +401,18 @@ The upgrade intentionally does not delete or rewrite retired Claude or PM Studio
366
401
  ## Commands
367
402
 
368
403
  Run `ccdx <command> --help` for command-specific behavior and side-effect details.
369
- After startup, CCDX prints a short reminder that `ccdx help` lists all available commands.
404
+ Startup uses aligned status/project/result columns and a left-aligned Ready footer
405
+ with the Web UI URL and `ccdx help`. Ctrl+C is shown only for the foreground-owned
406
+ service, never a short-lived command reusing another service. A static, favicon-style
407
+ atom uses ANSI green and half-block characters only on interactive color terminals
408
+ at least 72 columns wide; narrow terminals, `NO_COLOR`, `TERM=dumb` and redirected
409
+ output keep a plain title. No new graphics/font/runtime dependency is installed.
410
+ Credentials found are not labeled online-authorized, cached model lists are not
411
+ labeled fresh upstream data, and image configuration is not a provider test.
412
+ Ready reports core readiness independently of optional prediction/image warnings.
413
+ Model refresh logs show counts; `ccdx models` retains the complete live list.
414
+ VS Code compatibility-version details remain available in debug logging. Startup
415
+ does not wait for optional update/compression work or add online doctor/model probes.
370
416
 
371
417
  ### Live models
372
418
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "0.9.33",
3
+ "version": "0.9.34",
4
4
  "description": "Use Codex App with GitHub Copilot",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -499,7 +499,7 @@ export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
499
499
  server.listen(port, host, () => {
500
500
  server.off("error", onListenError);
501
501
  const actualPort = server.address()?.port || port;
502
- console.log(status("ok", `Adapter listening on http://${host}:${actualPort}`));
502
+ (options.log || console.log)(status("ok", `Adapter listening on http://${host}:${actualPort}`));
503
503
  resolve(server);
504
504
  });
505
505
  });
@@ -192,6 +192,7 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
192
192
  const prediction = data.client_integrations?.prediction;
193
193
  if (prediction) {
194
194
  lines.push(status("info", `Native predictions: ${prediction.configured ? "on" : "off"}; bridge ${prediction.bridge}; client route ${prediction.client_route}; visible candidate unknown`));
195
+ 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`));
195
196
  if (prediction.reason) lines.push(status("warn", terminalCell(prediction.reason).slice(0, 400)));
196
197
  }
197
198
  if (data.profiles?.codex) {
@@ -3,10 +3,11 @@ import { readImageProviderConfig } from "./image-provider-config.mjs";
3
3
  import { ensureCodexThreadCompression } from "./codex-thread-compression.mjs";
4
4
  import { runInBackground } from "./startup.mjs";
5
5
  import { createPredictionState } from "./native-prediction-state.mjs";
6
+ import { supervisePrediction } from "./native-prediction-recovery.mjs";
6
7
 
7
8
  // The CLI composes the services; this module owns optional client integration
8
9
  // lifecycle. It never forwards model requests or depends on dashboard rendering.
9
- export function createClientIntegration({ port, host, info = () => {}, warning = () => {} } = {}) {
10
+ export function createClientIntegration({ port, host, info = () => {}, warning = () => {}, configLog } = {}) {
10
11
  const prediction = createPredictionState();
11
12
  let native = null;
12
13
  return {
@@ -18,23 +19,29 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
18
19
  if (result.preserved) warning("Modified prediction settings were preserved");
19
20
  } catch (error) { warning(`${error.message}. Core startup will continue.`); }
20
21
  const enabled = Boolean(readImageProviderConfig());
21
- const { imageMcpSkipped } = ensureCodexConfig(port, { host, imageProviderEnabled: enabled });
22
+ const { imageMcpSkipped } = ensureCodexConfig(port, { host, imageProviderEnabled: enabled, ...(configLog ? { log: configLog } : {}) });
22
23
  if (enabled && !imageMcpSkipped) {
23
24
  try {
24
25
  const { syncEnabledImageSkill } = await import("./cli-image.mjs");
25
26
  syncEnabledImageSkill({ adapterPort: port, adapterHost: host });
26
27
  } catch (error) { warning(`Image guidance could not be updated: ${error.message}`); }
27
28
  }
28
- return { compressionSetup: runInBackground(ensureCodexThreadCompression) };
29
+ return { imageEnabled: enabled, imageMcpSkipped, compressionSetup: runInBackground(ensureCodexThreadCompression) };
29
30
  },
30
31
  async start() {
31
32
  try {
32
33
  const { startNativePrediction } = await import("./native-prediction.mjs");
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
+ }
34
40
  } catch (error) { prediction.unavailable(error); warning(`${error.message}. Core startup will continue.`); }
35
41
  return native;
36
42
  },
37
43
  pacUrl() { return native?.pacUrl || null; },
44
+ launched(route) { prediction.launch(route); },
38
45
  snapshot() { return { prediction: prediction.snapshot() }; },
39
46
  async close() { await native?.close(); native = null; },
40
47
  };
package/src/config.mjs CHANGED
@@ -286,6 +286,7 @@ function ensureCodexConfigUnlocked(adapterPort = 2026, {
286
286
  filePath,
287
287
  host = "127.0.0.1",
288
288
  imageProviderEnabled = false,
289
+ log = console.log,
289
290
  } = {}) {
290
291
  const baseUrl = `${adapterBaseUrl(host, adapterPort)}/v1`;
291
292
 
@@ -304,10 +305,10 @@ function ensureCodexConfigUnlocked(adapterPort = 2026, {
304
305
  ? { content: initialCodexConfig(adapterPort, host), changed: true }
305
306
  : computeUpdatedCodexConfig(content, adapterPort, host);
306
307
  if (!core.changed) {
307
- console.log(status("ok", `Codex already points to ${baseUrl}`));
308
+ log(status("ok", `Codex already points to ${baseUrl}`));
308
309
  } else {
309
310
  atomicWriteFileIfChangedSync(filePath, core.content);
310
- console.log(status("ok", content === undefined ? `Created Codex configuration: ${filePath}` : `Configured Codex base URL: ${baseUrl}`));
311
+ log(status("ok", content === undefined ? `Created Codex configuration: ${filePath}` : `Configured Codex base URL: ${baseUrl}`));
311
312
  }
312
313
  // Disabled means no image maintenance, including no implicit removal of old
313
314
  // or user-owned entries. Explicit disable-image owns the cleanup operation.
package/src/copilot.mjs CHANGED
@@ -251,7 +251,7 @@ export async function refreshVSCodeVersion() {
251
251
  clearTimeout(timer);
252
252
  if (resp.ok) {
253
253
  cachedVersion = parseVSCodeVersion(await resp.json());
254
- console.log(status("info", `VS Code version: ${cachedVersion}`));
254
+ debugLog(`VS Code version: ${cachedVersion}`);
255
255
  }
256
256
  } catch {
257
257
  // Keep the fallback quietly.
@@ -10,6 +10,7 @@
10
10
  "Enabled": ["Enabled", "已开启"],
11
11
  "Disabled": ["Disabled", "已关闭"],
12
12
  "Running": ["Running", "运行中"],
13
+ "Recovering": ["Recovering", "恢复中"],
13
14
  "Stopped": ["Stopped", "未运行"],
14
15
  "Unavailable": ["Unavailable", "不可用"],
15
16
  "Observed": ["Observed", "已收到配置请求"],
@@ -149,7 +149,7 @@
149
149
  if (element("prediction-preference")) {
150
150
  const prediction = data.client_integrations?.prediction;
151
151
  text("prediction-preference", prediction ? prediction.configured ? "Enabled" : "Disabled" : "Unknown");
152
- text("prediction-bridge", ({ running: "Running", stopped: "Stopped", unavailable: "Unavailable" })[prediction?.bridge] || "Unknown");
152
+ text("prediction-bridge", ({ running: "Running", recovering: "Recovering", stopped: "Stopped", unavailable: "Unavailable" })[prediction?.bridge] || "Unknown");
153
153
  text("prediction-route", prediction?.client_route === "observed" ? "Observed" : "Unknown");
154
154
  text("prediction-candidate", "Unknown");
155
155
  const note = element("prediction-note");
package/src/launcher.mjs CHANGED
@@ -61,6 +61,7 @@ export function macPredictionAppProcesses(app, { exec = execFileSync } = {}) {
61
61
  }
62
62
 
63
63
  export async function openCodex({ env = process.env, spawnImpl = spawn, platform = process.platform, predictionPacUrl = null, predictionApp = null, predictionProfile = null,
64
+ preparePredictionRoute, persistedPredictionRoute = false, onPredictionRoute = () => {}, log = console.log,
64
65
  resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses,
65
66
  macAppProcesses = macPredictionAppProcesses } = {}) {
66
67
  if (platform === "win32" && autoLaunchEnabled(env) && typeof predictionPacUrl === "string"
@@ -82,10 +83,14 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
82
83
  const running = windowsAppProcesses(current.app, { env });
83
84
  if (running.length) {
84
85
  if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
85
- console.log(status("ok", "Running Codex App uses the current prediction route"));return true;
86
+ onPredictionRoute("verified");log(status("ok", "Running Codex App uses the current prediction route"));return true;
87
+ }
88
+ if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
89
+ onPredictionRoute("persisted");log(status("info", "App route preference is saved; waiting for configuration traffic to confirm it"));return true;
86
90
  }
87
91
  throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then run ccdx again; no process was stopped");
88
92
  }
93
+ await preparePredictionRoute?.();
89
94
  const launched = await new Promise(resolve => {
90
95
  const child = spawnImpl(current.app, [`--user-data-dir=${predictionProfile}`, `--proxy-pac-url=${predictionPacUrl}`], {
91
96
  cwd: path.win32.dirname(current.app), env: { ...env, CODEX_ELECTRON_USER_DATA_PATH: predictionProfile },
@@ -94,27 +99,28 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
94
99
  child.once("error", () => resolve(false));
95
100
  child.once("spawn", () => { child.unref(); resolve(true); });
96
101
  });
97
- if (!launched) { console.log(status("warn", "Could not launch the registered Windows Codex App"));return false; }
102
+ if (!launched) { onPredictionRoute("unverified");log(status("warn", "Could not launch the registered Windows Codex App"));return false; }
98
103
  await new Promise(resolve => setTimeout(resolve, 300));
99
104
  const actual = windowsAppProcesses(current.app, { env });
100
105
  const routeRetained = actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl;
101
- console.log(status(routeRetained ? "info" : "warn", routeRetained
106
+ onPredictionRoute(routeRetained ? "verified" : "unverified");
107
+ log(status(routeRetained ? "info" : "warn", routeRetained
102
108
  ? "Codex launch route verified; prediction status will show when configuration traffic is observed"
103
109
  : "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
104
110
  return routeRetained;
105
111
  } catch (error) {
106
- console.log(status("warn", `Optional Windows prediction launch skipped: ${error.message}`));
112
+ onPredictionRoute("unverified");log(status("warn", `Optional Windows prediction launch skipped: ${error.message}`));
107
113
  return false;
108
114
  }
109
115
  }
110
116
  if (platform !== "darwin") {
111
- console.log(status("warn", "Automatic launch requires macOS or an enabled Windows prediction setup"));
112
- console.log(status("info", "Open Codex App manually; it will connect to the adapter."));
117
+ log(status("warn", "Automatic launch requires macOS or an enabled Windows prediction setup"));
118
+ log(status("info", "Open Codex App manually; it will connect to the adapter."));
113
119
  return false;
114
120
  }
115
121
 
116
122
  if (!autoLaunchEnabled(env)) {
117
- console.log(status("info", "Auto-launch disabled (CCDX_AUTO_LAUNCH=0); open Codex App manually."));
123
+ log(status("info", "Auto-launch disabled (CCDX_AUTO_LAUNCH=0); open Codex App manually."));
118
124
  return false;
119
125
  }
120
126
 
@@ -126,38 +132,42 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
126
132
  const running = macAppProcesses(predictionApp);
127
133
  if (running.length) {
128
134
  if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
129
- console.log(status("ok", "Running Codex App uses the current prediction route"));return true;
135
+ onPredictionRoute("verified");log(status("ok", "Running Codex App uses the current prediction route"));return true;
136
+ }
137
+ if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
138
+ onPredictionRoute("persisted");log(status("info", "App route preference is saved; waiting for configuration traffic to confirm it"));return true;
130
139
  }
131
140
  throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then run ccdx again; no process was stopped");
132
141
  }
142
+ await preparePredictionRoute?.();
133
143
  if (!await tryOpen([predictionApp, ...extraArgs], { spawnImpl })) {
134
- console.log(status("warn", "Could not launch the verified macOS Codex App"));return false;
144
+ onPredictionRoute("unverified");log(status("warn", "Could not launch the verified macOS Codex App"));return false;
135
145
  }
136
146
  for (let attempt = 0; attempt < 10; attempt++) {
137
147
  const actual = macAppProcesses(predictionApp);
138
148
  if (actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl) {
139
- console.log(status("info", "Codex launch route verified; prediction status will show when configuration traffic is observed"));return true;
149
+ onPredictionRoute("verified");log(status("info", "Codex launch route verified; prediction status will show when configuration traffic is observed"));return true;
140
150
  }
141
151
  if (actual.length) break;
142
152
  if (attempt < 9) await new Promise(resolve => setTimeout(resolve, 100));
143
153
  }
144
- console.log(status("warn", "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
154
+ onPredictionRoute("unverified");log(status("warn", "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
145
155
  return false;
146
156
  } catch (error) {
147
- console.log(status("warn", `Optional macOS prediction launch skipped: ${error.message}`));return false;
157
+ onPredictionRoute("unverified");log(status("warn", `Optional macOS prediction launch skipped: ${error.message}`));return false;
148
158
  }
149
159
  }
150
160
  const attempts = launchAttempts();
151
161
  for (const attempt of attempts) {
152
162
  const args = [...attempt, ...extraArgs];
153
163
  if (await tryOpen(args, { spawnImpl })) {
154
- console.log(status("ok", "Codex app launched"));
164
+ log(status("ok", "Codex app launched"));
155
165
  return true;
156
166
  }
157
167
  }
158
168
 
159
- console.log(status("warn", "Could not launch the Codex app (checked com.openai.codex, Codex.app, ChatGPT.app)"));
160
- console.log(status("info", "Open Codex App manually; it will connect to the adapter."));
161
- console.log(status("info", "Download it from https://openai.com/codex"));
169
+ log(status("warn", "Could not launch the Codex app (checked com.openai.codex, Codex.app, ChatGPT.app)"));
170
+ log(status("info", "Open Codex App manually; it will connect to the adapter."));
171
+ log(status("info", "Download it from https://openai.com/codex"));
162
172
  return false;
163
173
  }
@@ -0,0 +1,39 @@
1
+ // Only the optional bridge is supervised. Model/image traffic, App processes,
2
+ // global proxy settings and certificate trust are never changed here.
3
+ export function supervisePrediction({ native, restart, state, warning = () => {},
4
+ intervalMs = 30_000, now = Date.now, setIntervalImpl = setInterval, clearIntervalImpl = clearInterval } = {}) {
5
+ let current = native, closed = false, flight = null, attempts = 0, retryAt = 0;
6
+ const delays = [30_000, 60_000, 120_000];
7
+ async function check() {
8
+ if (closed || flight || !current || current.enabled?.() === false || attempts >= delays.length || now() < retryAt) return;
9
+ if (current.healthy()) { state?.checked();return; }
10
+ const attempt = ++attempts;
11
+ retryAt = now() + delays[attempt - 1];
12
+ state?.recovering(attempt);
13
+ flight = (async () => {
14
+ try {
15
+ await current.close();
16
+ if (closed) return;
17
+ const resumed = await restart();
18
+ if (closed) { await resumed?.close();return; }
19
+ if (!resumed || resumed.pacUrl !== native.pacUrl) {
20
+ await resumed?.close();throw new Error("Prediction recovery did not retain the original route");
21
+ }
22
+ current = resumed;state?.recovered();
23
+ warning("Prediction bridge recovered on its original port; App restart was not requested");
24
+ } catch (error) {
25
+ state?.unavailable(error);
26
+ warning(`Prediction bridge recovery ${attempt}/${delays.length} failed: ${error.message}. Core service remains available`);
27
+ }
28
+ })();
29
+ try { await flight; } finally { flight = null; }
30
+ }
31
+ const timer = setIntervalImpl(() => { void check().catch(error => state?.unavailable(error)); }, intervalMs);
32
+ timer.unref?.();
33
+ return {
34
+ ...native,
35
+ check,
36
+ prepareRoute() { return current.prepareRoute?.(); },
37
+ async close() { closed = true;clearIntervalImpl(timer);await flight;await current?.close(); },
38
+ };
39
+ }
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { readBoundedFileSync } from "./bounded-file.mjs";
5
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
6
+ import { withFileLock } from "./lock.mjs";
7
+
8
+ const validPac = value => typeof value === "string" && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(value)
9
+ && Number(new URL(value).port) >= 1024 && Number(new URL(value).port) <= 65535;
10
+ const object = value => value && typeof value === "object" && !Array.isArray(value);
11
+
12
+ function regularFile(file) {
13
+ const stat = fs.lstatSync(file);
14
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Prediction route file is not a regular owned file; it was preserved");
15
+ }
16
+
17
+ function preferences(profile) {
18
+ for (const directory of [profile, path.join(profile, "Default")]) {
19
+ const stat = fs.lstatSync(directory);
20
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Prediction profile is not a regular directory; it was preserved");
21
+ }
22
+ regularFile(path.join(profile, "Local State"));
23
+ const file = path.join(profile, "Default", "Preferences");
24
+ regularFile(file);
25
+ const bytes = readBoundedFileSync(file);
26
+ const value = JSON.parse(bytes);
27
+ if (!object(value)) throw new Error("Unknown App preferences; they were preserved");
28
+ return { file, bytes, value };
29
+ }
30
+
31
+ function recordAt(file, profile) {
32
+ try {
33
+ regularFile(file);
34
+ const value = JSON.parse(readBoundedFileSync(file, { encoding: "utf8" }));
35
+ if (value?.version !== 1 || value.profile !== profile || !validPac(value.pacUrl)
36
+ || typeof value.hadProxy !== "boolean" || (value.hadProxy && !isDeepStrictEqual(value.previousProxy, { mode: "system" }))) {
37
+ throw new Error("Unknown saved prediction route ownership; no preference was changed");
38
+ }
39
+ return value;
40
+ } catch (error) { if (error.code === "ENOENT") return null; throw error; }
41
+ }
42
+
43
+ export function hasInstalledPredictionRoute({ directory, profile, pacUrl } = {}) {
44
+ try {
45
+ const record = recordAt(path.join(directory, "route.json"), profile);
46
+ return record?.pacUrl === pacUrl && isDeepStrictEqual(preferences(profile).value.proxy, { mode: "pac_script", pac_url: pacUrl });
47
+ } catch { return false; }
48
+ }
49
+
50
+ // A write is allowed only while the App is closed. The ownership intent is
51
+ // committed first, so an interrupted activation remains identifiable on off.
52
+ export async function updatePredictionRoute({ directory, profile, pacUrl, remove = false, assertClosed, direct = false,
53
+ writeFile = atomicWriteFileSync } = {}) {
54
+ if (!path.isAbsolute(profile || "") || (!remove && !validPac(pacUrl))) throw new Error("Invalid prediction route binding");
55
+ const recordFile = path.join(directory, "route.json");
56
+ if (remove && !fs.existsSync(recordFile)) return { status: "absent" };
57
+ if (!remove && !direct) return { status: "preserved", reason: "Existing system/company routing was preserved" };
58
+ return withFileLock(`${recordFile}.lock`, () => {
59
+ const record = recordAt(recordFile, profile);
60
+ if (remove && !record) return { status: "absent" };
61
+ let current;
62
+ try { current = preferences(profile); }
63
+ catch (error) {
64
+ if (error.code === "ENOENT" && !remove) return { status: "pending", reason: "App preferences are not initialized" };
65
+ throw error;
66
+ }
67
+ const owned = record && isDeepStrictEqual(current.value.proxy, { mode: "pac_script", pac_url: record.pacUrl });
68
+ if (remove && !owned) {
69
+ // The user replaced the route; retain their edit and remove only our intent.
70
+ fs.unlinkSync(recordFile);return { status: "preserved", reason: "User-edited App route was preserved" };
71
+ }
72
+ if (!remove && owned && record.pacUrl === pacUrl) return { status: "installed" };
73
+ if (!remove && !owned && Object.hasOwn(current.value, "proxy") && !isDeepStrictEqual(current.value.proxy, { mode: "system" })) {
74
+ return { status: "preserved", reason: "Existing App proxy preference was preserved" };
75
+ }
76
+ assertClosed();
77
+ if (!readBoundedFileSync(current.file).equals(current.bytes)) throw new Error("App preferences changed during route setup; retry after quitting the App");
78
+ if (remove) {
79
+ if (record.hadProxy) current.value.proxy = record.previousProxy;
80
+ else delete current.value.proxy;
81
+ } else {
82
+ const next = record || { version: 1, profile, pacUrl, hadProxy: Object.hasOwn(current.value, "proxy"),
83
+ ...(Object.hasOwn(current.value, "proxy") ? { previousProxy: current.value.proxy } : {}) };
84
+ writeFile(recordFile, JSON.stringify({ ...next, pacUrl }, null, 2) + "\n", { preserveMode: false });
85
+ current.value.proxy = { mode: "pac_script", pac_url: pacUrl };
86
+ }
87
+ // Recheck after committing the small intent file, before touching App data.
88
+ assertClosed();
89
+ if (!readBoundedFileSync(current.file).equals(current.bytes)) throw new Error("App preferences changed during route setup; the saved intent was retained");
90
+ writeFile(current.file, JSON.stringify(current.value) + "\n");
91
+ if (remove) fs.unlinkSync(recordFile);
92
+ return { status: remove ? "removed" : "installed" };
93
+ }, { timeoutMs: 100, pollMs: 10 });
94
+ }
@@ -3,11 +3,17 @@ import { operationErrorDetails } from "./operation-error.mjs";
3
3
 
4
4
  export function createPredictionState({ now = () => new Date().toISOString() } = {}) {
5
5
  let state = { configured: false, bridge: "stopped", client_route: "unknown", candidate: "unknown", reason: null,
6
+ launch_route: "unknown", persistence: "unknown", recovery: { attempts: 0, recovered: 0, last_check_at: null },
6
7
  configuration: {}, counters: { configuration_responses: 0, modified: 0, tls_errors: 0, upstream_errors: 0 }, last_event_at: null };
7
8
  return {
8
9
  configure(enabled) { state.configured = enabled === true; },
9
- running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy; },
10
+ running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy;delete state.error; },
10
11
  stopped() { state.bridge = "stopped"; },
12
+ launch(route) { state.launch_route = ["verified", "persisted"].includes(route) ? route : "unverified"; },
13
+ persistence(value) { state.persistence = value.status; },
14
+ checked() { state.recovery.last_check_at = now(); },
15
+ recovering(attempt) { state.bridge = "recovering";state.recovery.attempts = attempt;state.recovery.last_check_at = now(); },
16
+ recovered() { state.bridge = "running";state.reason = null;delete state.error;state.recovery.recovered++; },
11
17
  unavailable(error) {
12
18
  state.bridge = "unavailable";
13
19
  state.reason = redactDiagnosticText(String(error?.message || "Prediction setup failed")).slice(0, 400);
@@ -65,6 +65,7 @@ export async function startPredictionTransport({
65
65
  const sockets = new Set();
66
66
  const upstreams = new Set();
67
67
  let closing = false;
68
+ let listenerError = false;
68
69
  const gateway = https.createServer({ key, cert, minVersion: "TLSv1.2" }, (req, res) => {
69
70
  let target;
70
71
  try {
@@ -240,11 +241,16 @@ export async function startPredictionTransport({
240
241
  gateway.emit("connection", socket);
241
242
  });
242
243
  proxy.on("clientError", (_error, socket) => socket.destroy());
244
+ proxy.on("error", (error) => {
245
+ listenerError = true;
246
+ onEvent({ type: "bridge_error", error: operationErrorDetails(error) });
247
+ });
243
248
  let port;
244
249
  try { port = await listen(proxy, listenPort); }
245
250
  catch (error) { agent?.destroy();gateway.close();throw error; }
246
251
  return {
247
252
  port, pacUrl: `http://127.0.0.1:${port}/proxy.pac`,
253
+ healthy() { return !closing && !listenerError && proxy.listening; },
248
254
  async close() {
249
255
  closing = true;
250
256
  for (const upstream of upstreams) upstream.destroy();
@@ -8,6 +8,7 @@ import { retirePredictionIntegration } from "./prediction-retirement.mjs";
8
8
  import { networkRouteSnapshot } from "./network-route.mjs";
9
9
  import { withFileLock } from "./lock.mjs";
10
10
  import { windowsSystemProxy, windowsProxySettings, windowsProxyText } from "./native-prediction-windows.mjs";
11
+ import { updatePredictionRoute } from "./native-prediction-route.mjs";
11
12
 
12
13
  function systemProxy(exec = execFileSync, { platform = process.platform, env = process.env } = {}) {
13
14
  if (platform === "win32") return windowsSystemProxy({ exec, env });
@@ -49,12 +50,14 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
49
50
  if (action === "status") {
50
51
  output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (default: off)`);
51
52
  output("Uses the conversation's model. No prediction MCP, Hook, or panel.");
52
- if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; quit it and run ccdx prediction on to recheck compatibility.");
53
+ if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; bridge startup will recheck compatibility. Unsupported changes still require explicit setup.");
53
54
  if (runtimeSnapshot) {
54
55
  try {
55
56
  const runtime = (await runtimeSnapshot())?.client_integrations?.prediction;
56
57
  if (runtime) {
57
58
  output(`Bridge: ${runtime.bridge}; client route: ${runtime.client_route}; visible candidate: ${runtime.candidate}`);
59
+ if (runtime.launch_route) output(`App launch route: ${runtime.launch_route}; persistent route: ${runtime.persistence || "unknown"}`);
60
+ if (runtime.recovery) output(`Bridge recovery: ${runtime.recovery.recovered} recovered; ${runtime.recovery.attempts}/3 attempts used`);
58
61
  if (runtime.reason) output(runtime.reason);
59
62
  for (const [name, event] of Object.entries(runtime.configuration || {})) output(`${name}: HTTP ${event.status}${event.modified ? " (local compatibility)" : " (upstream)"}`);
60
63
  } else output("Runtime prediction state: unavailable; status is a saved preference, not proof of a visible suggestion.");
@@ -71,6 +74,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
71
74
  if (settings.certificateHash && settings.store) {
72
75
  try {
73
76
  assertCodexClosed(opts);
77
+ await updatePredictionRoute({ ...paths, remove: true, assertClosed: () => assertCodexClosed(opts) });
74
78
  const certificate = readPredictionCertificate(certificateDirectory(settings, paths), { ...opts, allowExpired: true });
75
79
  if (certificate.hash !== settings.certificateHash) throw new Error("Prediction certificate changed; trust cleanup was skipped");
76
80
  await updatePredictionTrust(settings.store, certificate, { remove: true });
@@ -150,7 +154,22 @@ export async function startNativePrediction({ env = process.env, platform = proc
150
154
  && (!Number.isInteger(settings.bridgePort) || settings.bridgePort < 1024 || settings.bridgePort > 65535)) {
151
155
  throw new Error("Saved prediction bridge port is invalid; no route was replaced");
152
156
  }
153
- if (!predictionAppMatches(settings.app)) throw new Error("Codex App changed; run ccdx prediction on after quitting it to recheck compatibility");
157
+ if (options.expectedPort !== undefined && settings.bridgePort !== options.expectedPort) throw new Error("Prediction route changed; automatic recovery was skipped");
158
+ if (!predictionAppMatches(settings.app)) {
159
+ const current = (options.resolveApp || installedPredictionApp)({ ...opts,
160
+ ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
161
+ if (current.app !== settings.app?.app || (platform === "win32" && current.profile !== settings.app?.profile)) {
162
+ throw new Error("Codex App identity/profile changed; run ccdx prediction on after quitting it to recheck compatibility");
163
+ }
164
+ const settingsFile = predictionPaths(opts).settings;
165
+ await withFileLock(`${settingsFile}.lock`, () => {
166
+ const latest = readPredictionSettings(opts);
167
+ if (JSON.stringify(latest) !== JSON.stringify(settings)) throw new Error("Prediction setup changed during App compatibility recheck");
168
+ writePredictionSettings({ ...latest, app: current }, opts);
169
+ }, { timeoutMs: 2000 });
170
+ settings.app = current;
171
+ warning("Codex App compatibility rechecked; prediction port and trust were preserved");
172
+ }
154
173
  const paths = predictionPaths({ ...opts, app: settings.app });
155
174
  if (settings.store !== paths.store || !fs.existsSync(paths.store)) throw new Error("Prediction profile trust is unavailable; run ccdx prediction on after quitting Codex");
156
175
  const certificate = readPredictionCertificate(certificateDirectory(settings, paths), opts);
@@ -214,12 +233,31 @@ export async function startNativePrediction({ env = process.env, platform = proc
214
233
  throw error;
215
234
  }
216
235
  state?.running(windowsNetwork ? { source: "system", type: "auto", bypass_rules: null, proxy_credentials: false } : networkRouteSnapshot(networkRoute));
217
- warning("Native prediction bridge enabled; only the two configuration hosts use its App-only route.");
218
- warning("If Codex uses a different or missing prediction route, fully quit it and run ccdx again.");
219
236
  return {
220
237
  app: settings.app.app,
221
238
  ...(platform === "win32" ? { profile: paths.profile } : {}),
222
239
  pacUrl: transport.pacUrl,
240
+ enabled() { return enabled; },
241
+ healthy() { return transport.healthy() && (!windowsNetwork || windowsNetwork.healthy()); },
242
+ async prepareRoute() {
243
+ try {
244
+ const direct = !windowsNetwork && !networkRoute?.http && !networkRoute?.https && !networkRoute?.bypass?.length;
245
+ if (!direct) {
246
+ // A profile previously configured on a direct network must not pin
247
+ // that local PAC after the environment switches to company routing.
248
+ await updatePredictionRoute({ ...paths, remove: true, assertClosed: () => assertCodexClosed(opts) });
249
+ }
250
+ const result = await updatePredictionRoute({ ...paths, pacUrl: transport.pacUrl, direct,
251
+ assertClosed: () => assertCodexClosed(opts) });
252
+ state?.persistence(result);
253
+ if (result.status === "preserved") warning(`Prediction route persistence skipped: ${result.reason}`);
254
+ return result;
255
+ } catch (error) {
256
+ state?.persistence({ status: "pending" });
257
+ if (!error.message.startsWith("Quit Codex App")) warning(`Prediction route persistence deferred: ${error.message}`);
258
+ return { status: "pending" };
259
+ }
260
+ },
223
261
  args: [...(platform === "win32" ? [`--user-data-dir=${paths.profile}`] : []), `--proxy-pac-url=${transport.pacUrl}`],
224
262
  async close() { clearInterval(timer); await transport.close(); windowsNetwork?.close(); state?.stopped(); },
225
263
  };
@@ -122,7 +122,7 @@ export function createProfileModelRuntime({
122
122
  }
123
123
  const gptModelIds = gptModelIdsFromCopilotModels(models);
124
124
  if (gptModelIds.length) {
125
- emit("ok", `Refreshed GPT models from GitHub Copilot: ${gptModelIds.join(", ")}`);
125
+ emit("ok", `Refreshed GPT models from GitHub Copilot: ${gptModelIds.length} available; run ${commandName} models for the list`);
126
126
  } else {
127
127
  emit("warn", "Copilot models response contained no GPT models");
128
128
  }
@@ -0,0 +1,54 @@
1
+ import { status } from "./status.mjs";
2
+ import { terminalCell } from "./terminal-text.mjs";
3
+
4
+ // The favicon's three ellipses, rasterized as terminal half-blocks. No runtime
5
+ // graphics library or terminal cursor control is needed.
6
+ const ATOM = [
7
+ " ▄█▀█▄▄ ▄▄█▀█▄ ",
8
+ " █ ███ █ ",
9
+ " █ ▄▄▄█▄█▄▄▄ █ ",
10
+ " ▄▄▀▀█▀█▀ ▀█▀█▀▀▄▄ ",
11
+ " █▀ ▀█ ▄█▄ █▀ ▀█ ",
12
+ " ▀█▄ █▀▄ ▀ ▄▀█ ▄█▀ ",
13
+ " ▀█▀███▄▄▄███▀█▀ ",
14
+ " █ █▄█ █ ",
15
+ " █▄ ▄▄█▀█▄▄ ▄█ ",
16
+ " ▀▀▀ ▀▀▀ ",
17
+ ];
18
+
19
+ export function startupBanner({ commandName = "ccdx", version, stream = process.stdout, env = process.env } = {}) {
20
+ const title = `${terminalCell(commandName)} v${terminalCell(version)} by Dale Xiao`;
21
+ const color = stream.isTTY === true && !Object.hasOwn(env, "NO_COLOR") && env.TERM !== "dumb";
22
+ if (!color || Number(stream.columns || 80) < 72) return `${title}\nUse Codex App with GitHub Copilot`;
23
+ const labels = new Map([[3, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [4, "by Dale Xiao"], [6, "Codex App + GitHub Copilot"]]);
24
+ return ATOM.map((line, i) => `\x1b[38;2;166;245;168m${line}\x1b[0m${labels.has(i) ? ` ${labels.get(i)}` : ""}`).join("\n");
25
+ }
26
+
27
+ export function startupCheck(kind, name, detail) {
28
+ const prefix = status(kind, "").trimEnd();
29
+ return `${prefix.padEnd(8)}${terminalCell(name).padEnd(12)}${terminalCell(detail)}`;
30
+ }
31
+
32
+ export function startupReady({ baseUrl, commandName = "ccdx", reused = false } = {}) {
33
+ return ["", startupCheck("ok", "Ready", reused ? "Using the existing CCDX adapter" : "Core service available"), "",
34
+ `Web UI ${baseUrl}`, `Help ${commandName} help`, ...(!reused ? ["Stop Ctrl+C"] : []), ""].join("\n");
35
+ }
36
+
37
+ export function startupLogger(name, output = console.log) {
38
+ return value => {
39
+ for (const line of String(value).split("\n")) {
40
+ const match = /^\[(OK|INFO|WARN|ERR|WAIT|DEBUG)\]\s+(.*)$/.exec(line);
41
+ output(match ? startupCheck(match[1].toLowerCase(), name, match[2]) : line);
42
+ }
43
+ };
44
+ }
45
+
46
+ export function predictionStartupCheck(prediction) {
47
+ if (!prediction?.configured) return startupCheck("info", "Prediction", "Off");
48
+ if (prediction.bridge !== "running") return startupCheck("warn", "Prediction", prediction.reason || "Bridge unavailable; core service is available");
49
+ const route = prediction.launch_route;
50
+ const summary = startupCheck(route === "unverified" ? "warn" : "info", "Prediction", route === "verified"
51
+ ? "Bridge running; App route verified; suggestion not checked"
52
+ : "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;
54
+ }
package/src/status.mjs CHANGED
@@ -13,5 +13,5 @@ export function status(kind, message) {
13
13
  const requestContext = currentRequestContext();
14
14
  const requestId = requestContext?.showRequestId ? requestContext.requestId : "";
15
15
  const context = requestId ? ` request_id=${requestId}` : "";
16
- return `${LABELS[kind] || LABELS.info}${context} ${message}`;
16
+ return `${(LABELS[kind] || LABELS.info).padEnd(8)}${context ? `${context.trimStart()} ` : ""}${message}`;
17
17
  }
@@ -119,5 +119,5 @@ export async function startWindowsPredictionNetwork({ settings, env = process.en
119
119
  if(stopped)queueMicrotask(()=>req.destroy(failure("proxy_worker_closed")));
120
120
  return req;
121
121
  };
122
- return {script,requestImpl,pac:port=>companyPredictionPac(script,port),close(){closing=true;stop(failure("proxy_worker_closed"));}};
122
+ return {script,requestImpl,pac:port=>companyPredictionPac(script,port),healthy:()=>!stopped,close(){closing=true;stop(failure("proxy_worker_closed"));}};
123
123
  }