codex-copilot-dx 1.2.21 → 1.2.23

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.
Files changed (47) hide show
  1. package/README.md +7 -7
  2. package/bin/cli.mjs +77 -14
  3. package/docs/ARCHITECTURE.md +94 -3
  4. package/docs/REFERENCE.md +142 -6
  5. package/package.json +2 -1
  6. package/src/account-tools.mjs +1 -1
  7. package/src/adapter.mjs +23 -6
  8. package/src/api-catalog-refresh.mjs +6 -2
  9. package/src/api-secrets.mjs +28 -9
  10. package/src/auth.mjs +2 -0
  11. package/src/bounded-result-cache.mjs +12 -0
  12. package/src/claude-gateway.mjs +19 -3
  13. package/src/cli-status.mjs +2 -2
  14. package/src/client-gateway-keys.mjs +7 -3
  15. package/src/client-integration.mjs +3 -0
  16. package/src/connection-runtime.mjs +25 -6
  17. package/src/conversation-source-guard.mjs +3 -1
  18. package/src/dashboard/console.js +12 -2
  19. package/src/dashboard/flow.js +62 -33
  20. package/src/dashboard/index.html +8 -0
  21. package/src/dashboard/language.js +47 -0
  22. package/src/dashboard/status.js +29 -8
  23. package/src/dashboard/ui.css +18 -2
  24. package/src/dashboard/ui.js +4 -4
  25. package/src/dashboard/view-boundary.js +41 -0
  26. package/src/dashboard-tools.mjs +1 -0
  27. package/src/dashboard.mjs +26 -5
  28. package/src/image-mcp.mjs +3 -0
  29. package/src/image-references.mjs +9 -0
  30. package/src/local-tools.mjs +1 -1
  31. package/src/m365-settings.mjs +5 -0
  32. package/src/nightly-update.mjs +107 -0
  33. package/src/optional-routes.mjs +19 -5
  34. package/src/provider-runtime.mjs +3 -2
  35. package/src/providers/api-token-count.mjs +61 -0
  36. package/src/providers/api.mjs +17 -7
  37. package/src/release-install.mjs +24 -12
  38. package/src/request-context.mjs +8 -0
  39. package/src/response-failures.mjs +25 -5
  40. package/src/response-history.mjs +50 -0
  41. package/src/responses-handler.mjs +3 -0
  42. package/src/service-control.mjs +9 -3
  43. package/src/service-supervisor.mjs +168 -0
  44. package/src/service-worker.mjs +87 -0
  45. package/src/stream-performance.mjs +3 -1
  46. package/src/terminal-console.mjs +1 -0
  47. package/src/user-settings.mjs +15 -0
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # codex-copilot-dx
2
2
 
3
- CCDX connects Codex App to GitHub Copilot by default: discovery, adapted model catalogs, Responses streaming, tool calls and conversation history. Eligible Microsoft 365 environments can also use a protocol-isolated Claude gateway on the main listener and manually select M365 as a Codex backup. Default Auto-review: **GPT-6.1 Sol / low**. Image generation is **off by default**. Native predictions are also **off by default**.
3
+ CCDX connects Codex App to GitHub Copilot by default: discovery, adapted model catalogs, Responses streaming, tool calls and conversation history. Eligible Microsoft 365 environments can also use a protocol-isolated Claude gateway on the main listener and manually select M365 as a Codex backup. Default Auto-review: **GPT-6.1 Sol / low**. Image generation is **off by default**. Native predictions and nightly software updates are also **off by default**.
4
4
 
5
5
  ## Install and run
6
6
 
@@ -11,13 +11,13 @@ npm install -g codex-copilot-dx@latest
11
11
  ccdx
12
12
  ```
13
13
 
14
- No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.21/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.21/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
14
+ No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.23/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.23/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
15
15
 
16
16
  CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
17
17
 
18
18
  The [local control console](http://127.0.0.1:2026/) separates Overview, Codex/Claude, Model sources, Usage, Requests, Checks & repairs and Settings, with a stable sticky header. Model sources owns API accounts, keys and model capabilities; application pages own visible models and defaults. Settings owns independent web/terminal colors (classic green, Klein blue or Soft pink), startup and updates. Accounts and model catalogs stay with Model sources; client-specific tools stay with their application. CLI remains English; WebUI supports English/Chinese. An interactive terminal shows bounded startup checks, source/client state, a usage table with approximate cache hit rate, notices and animation. Plain/NO_COLOR/narrow output remains supported; `--verbose` retains request detail.
19
19
 
20
- Requests shows live app/source/model flow above existing summaries and finished records. Usage offers animated bars or curves; reduced motion stays static. Hidden pages stop scheduled reads; status refreshes about every two seconds and source/settings evidence about every 16 seconds. Catalogs and retained usage load on demand or every 30 minutes while open. The UI does not add inference calls. Ready means local service availability, not verified model access. First output uses ms, speed token/s, and partial/unknown usage remains explicit. Images/predictions stay opt-in; their first setup uses CLI. 1.2.18 preserves Codex sign-in and unavailable model selections after saving bindings. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings), [1.2.18 fixes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.18.md) and [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md).
20
+ Requests shows live app/source/model flow above existing summaries and finished records; a thin theme-colored ring rotates around its atom while requests are active. Usage offers animated bars or curves; reduced motion stays static. Hidden pages stop scheduled reads; status refreshes about every two seconds and source/settings evidence about every 16 seconds. Catalogs and retained usage load on demand or every 30 minutes while open. The UI does not add inference calls. Ready means local service availability, not verified model access. First output uses ms, speed token/s, and partial/unknown usage remains explicit. Images/predictions stay opt-in; their first setup uses CLI. 1.2.18 preserves Codex sign-in and unavailable model selections after saving bindings. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings), [1.2.18 fixes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.18.md) and [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md).
21
21
 
22
22
  ## Commands
23
23
  | Command | Purpose |
@@ -52,11 +52,11 @@ Requests shows live app/source/model flow above existing summaries and finished
52
52
 
53
53
  ## Add your own API
54
54
 
55
- Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
55
+ Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. Token counting is separate from message generation. For manual APIs, an observed count-endpoint 404 is remembered for one minute per model/API-header scope; CCDX returns a clear 404 without inventing a token count. Identical concurrent count requests share bounded upstream work. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
56
56
 
57
57
  Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving reads model metadata automatically, without inference. Startup and the existing model refresh cycle also refresh enabled APIs when the 30-minute cache expires; failed reads retain saved configuration. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
58
58
 
59
- Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.21 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.21.md) cover native GitHub integration, friendly model names and startup/ownership protection.
59
+ Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.23 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.23.md) cover request attribution, bounded token-count compatibility and lower-cost flow rendering while retaining native GitHub sign-in/model protections.
60
60
 
61
61
  ## Microsoft 365 access
62
62
 
@@ -110,9 +110,9 @@ See the [M365 reference](docs/REFERENCE.md#microsoft-365-provider) for ownership
110
110
  expose it to the public internet. The dashboard is not an authentication wall
111
111
  for the API. Inference rejects browser Origin headers; native clients remain supported. Diagnostic errors may contain sensitive upstream text.
112
112
 
113
- Open `ccdx web` for source-specific account tools and Checks & repairs without signing in first. It starts a management-only service when needed; stop it before normal app startup. Safe reauth, config preview/backup, local reports, feature pause/resume and matching circle SVG status icons are described in the [account tools reference](docs/REFERENCE.md#account-and-repair-tools). Existing themes, layout and bilingual support are preserved. Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`. Settings → Version & updates shows the running version, release dates and newer releases, with copyable update and macOS/Windows recovery commands. This separate, cached GitHub metadata check never installs automatically; failed checks remain unknown. See the [reference](docs/REFERENCE.md#version-and-update-information).
113
+ Open `ccdx web` for source-specific account tools and Checks & repairs without signing in first. It starts a management-only service when needed; stop it before normal app startup. Safe reauth, config preview/backup, local reports, feature pause/resume and matching circle SVG status icons are described in the [account tools reference](docs/REFERENCE.md#account-and-repair-tools). Existing themes, layout and bilingual support are preserved. Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`. Settings → Version & updates shows the running version, release dates and newer releases, with copyable update and macOS/Windows recovery commands. This separate, cached GitHub metadata check never installs; failed checks remain unknown. The separate **Update overnight** switch defaults off and requires a normal CCDX restart after enabling. Its foreground supervisor checks during 00:00–04:00 local time after ten observed idle minutes, selects same-series stable patches at least 24 hours old, stages verified packages and attempts rollback on failure. Ctrl+C stops it; no OS service is installed. Review the displayed risk and [handoff limits](docs/REFERENCE.md#nightly-updates-opt-in) before enabling. See the [reference](docs/REFERENCE.md#version-and-update-information).
114
114
  GitHub updates verify and install the exact Release tarball without Git; dependencies still use npm's configured registry. Lookup errors identify HTTP refusal, timeout, network failure or invalid redirects. For npm `EALLOWREMOTE`, only if policy permits and the update is trusted, use `ccdx update github --allow-remote`: explicit URL-download permission for that installation's whole dependency tree, not a hostname allowlist. Persistent npm settings stay unchanged.
115
- Updates back up the discovered CCDX package and commands, restore them on install/runtime-check failure, and verify the installed version (exact for GitHub). Mismatched npm targets warn without changing PATH/prefix. Restart the adapter separately. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
115
+ Updates back up the discovered CCDX package and commands, restore them on install/runtime-check failure, and verify the installed version (exact for GitHub). Mismatched npm targets warn without changing PATH/prefix. Manual updates require a separate adapter restart. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
116
116
  Recent errors separate HTTP and model failures. By default HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged. Explicit, bounded error-excerpt collection is described in the [reference](docs/REFERENCE.md#http-error-diagnostics).
117
117
 
118
118
  See [architecture boundaries](docs/ARCHITECTURE.md) and 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.
package/bin/cli.mjs CHANGED
@@ -14,7 +14,7 @@ import { runInBackground } from "../src/startup.mjs";
14
14
  import { cliCommandName, cliHelp, parseAdapterAddressOptions, parseAdapterProbeOptions, parseCliArgs, parseRuntimeOptions } from "../src/cli-options.mjs";
15
15
  import { formatAdapterStatus, readAdapterStatus } from "../src/cli-status.mjs";
16
16
  import { closeHttpServer } from "../src/shutdown.mjs";
17
- import { autoReviewModelPreference, autoReviewPreference, responseHistoryLimitPreference, terminalAnimationPreference, servicePreferences, serviceSettingsSnapshot } from "../src/user-settings.mjs";
17
+ import { autoReviewModelPreference, autoReviewPreference, responseHistoryLimitPreference, terminalAnimationPreference, servicePreferences, serviceSettingsSnapshot, nightlyUpdatePreference } from "../src/user-settings.mjs";
18
18
  import { formatLiveCopilotModels } from "../src/cli-models.mjs";
19
19
  import { runAuthCommand } from "../src/cli-auth.mjs";
20
20
  import { createProfileRuntime } from "../src/profile-runtime.mjs";
@@ -305,6 +305,26 @@ if (CLI.command === "doctor" && CLI.configOnly) {
305
305
  process.exit(checks.some((check) => check.kind === "err") ? 1 : 0);
306
306
  }
307
307
 
308
+ let serviceWorker = null;
309
+ if (CLI.command === "start") {
310
+ if (process.send && process.env.CCDX_SUPERVISED_SERVICE === "1") {
311
+ const { createServiceWorker } = await import("../src/service-worker.mjs");
312
+ serviceWorker = await createServiceWorker();
313
+ } else if (nightlyUpdatePreference()) {
314
+ const { installedUpdateEnvironment } = await import("../src/nightly-update.mjs");
315
+ const address = parseAdapterProbeOptions(process.env);
316
+ const existing = await checkRunningAdapter({ host: address.adapterHost, port: address.adapterPort, timeoutMs: address.existingAdapterTimeoutMs });
317
+ let environment;
318
+ try { if (!existing.ok && !existing.incompatible) environment = installedUpdateEnvironment(); }
319
+ catch { console.warn(status("warn", "Nightly updates need a writable, matching npm installation. Starting without automatic updates.")); }
320
+ if (environment) {
321
+ const { runServiceSupervisor } = await import("../src/service-supervisor.mjs");
322
+ try { process.exit(await runServiceSupervisor({ environment })); }
323
+ catch { console.warn(status("warn", "Nightly runtime preparation failed. Starting without automatic updates.")); }
324
+ }
325
+ }
326
+ }
327
+
308
328
  let RUNTIME;
309
329
  try {
310
330
  RUNTIME = parseRuntimeOptions(process.env);
@@ -318,7 +338,8 @@ const ADAPTER_PORT = RUNTIME.adapterPort;
318
338
  const ADAPTER_HOST = RUNTIME.adapterHost;
319
339
  const MODEL_REFRESH_TIMEOUT_MS = RUNTIME.modelRefreshTimeoutMs;
320
340
  const EXISTING_ADAPTER_TIMEOUT_MS = RUNTIME.existingAdapterTimeoutMs;
321
- const LOGGING = configureLogging();
341
+ let LOGGING = configureLogging({ env: serviceWorker?.warming ? { ...process.env, CCDX_LOG_PATH: "" } : process.env });
342
+ if (serviceWorker?.warming) LOGGING.setTerminalSink(() => {});
322
343
  let activeServer = null;
323
344
  let modelRefreshTimer = null;
324
345
  let shuttingDown = false;
@@ -400,6 +421,7 @@ async function reuseRunningAdapterIfAvailable() {
400
421
  }
401
422
 
402
423
  async function configureCodexClient() {
424
+ if (serviceWorker?.preserving) return { compressionSetup: Promise.resolve(), imageEnabled: false, imageMcpSkipped: false };
403
425
  return (await clientIntegrations()).configure();
404
426
  }
405
427
 
@@ -440,9 +462,10 @@ try {
440
462
  } catch { console.warn(startupCheck("warn", "Command", "Command setup skipped; service will start")); }
441
463
  }
442
464
  const updateNotice = runInBackground(printUpdateNotice);
443
- if (await reuseRunningAdapterIfAvailable()) {
465
+ if (!serviceWorker?.warming && await reuseRunningAdapterIfAvailable()) {
444
466
  // Ready is already displayed; finish the bounded check before this short-lived CLI exits.
445
467
  await updateNotice;
468
+ serviceWorker?.reused();
446
469
  await LOGGING.cleanup();
447
470
  process.exit(0);
448
471
  }
@@ -462,16 +485,16 @@ try {
462
485
  log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "Models", message)),
463
486
  });
464
487
  providerRuntime = createProviderRuntime({ githubClient: profileRuntime.codexClient, githubRegistry: profileModels.codexRegistry,
465
- corePort: ADAPTER_PORT,
488
+ corePort: ADAPTER_PORT, preserveClientConfiguration: () => serviceWorker?.preserving === true || serviceWorker?.draining === true,
466
489
  clientAccessChanged: async enabled => { earlyIntegration.setPredictionActive(enabled && servicePreferences().prediction_enabled);if (enabled) await earlyIntegration.configure(); },
467
490
  githubCredentialFingerprint: () => profileRuntime.codexCredentialFingerprint,
468
491
  log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "M365", message)) });
469
492
  const codexEnabled = providerRuntime.connections().clients.find(client => client.id === "codex").enabled;
470
- const predictionSetup = codexEnabled ? runInBackground(() => earlyIntegration.start()) : Promise.resolve(null);
493
+ const predictionSetup = codexEnabled && !serviceWorker?.warming ? runInBackground(() => earlyIntegration.start()) : Promise.resolve(null);
471
494
  const m365Setup = runInBackground(() => providerRuntime.start());
472
495
  if (providerRuntime.selection().codex === "github") {
473
- try { await ensureAuth({ log: startupLogger("Sign-in") }); }
474
- catch (error) { console.warn(startupCheck("warn", "Sign-in", "Sign-in unavailable. Use the dashboard or ccdx auth login; saved credentials kept.")); }
496
+ try { await ensureAuth({ log: startupLogger("Sign-in"), interactive: serviceWorker?.preserving !== true }); }
497
+ catch (error) { if (serviceWorker?.preserving) throw error;console.warn(startupCheck("warn", "Sign-in", "Sign-in unavailable. Use the dashboard or ccdx auth login; saved credentials kept.")); }
475
498
  } else {
476
499
  if (providerRuntime.selection().codex === "m365") await m365Setup;
477
500
  const source = providerRuntime.connections().providers.find(source => source.id === providerRuntime.selection().codex);
@@ -481,8 +504,9 @@ try {
481
504
 
482
505
  // Refresh the VS Code version in the background; fallback is non-blocking.
483
506
  void refreshVSCodeVersion();
484
- if (providerRuntime.selection().codex === "github") {
507
+ if (providerRuntime.selection().codex === "github" || serviceWorker?.needsGithub) {
485
508
  await profileModels.initialize();
509
+ if (serviceWorker?.warming) await profileModels.refreshAll();
486
510
  // Provider setup can run before GitHub's directory exists. Reconcile again
487
511
  // before opening the App, then join any existing stale-cache refresh.
488
512
  const refreshing = profileModels.codexRegistry.refreshInFlight ? profileModels.refreshAll() : null;
@@ -502,9 +526,9 @@ try {
502
526
  terminalConsole = createTerminalConsole({ baseUrl: webUiUrl, verbose: CLI.verbose === true || CLI.showRequestId === true || LOGGING.level === "debug",
503
527
  snapshot: () => activeServer?.ccdxSnapshot?.() || {},
504
528
  preferences: () => { const { saved, theme, color_theme } = serviceSettingsSnapshot();return { ...saved, theme, color_theme }; } });
505
- const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole });
529
+ const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole, nightlyStatus: () => serviceWorker?.status() || null, nightlyChanged: enabled => serviceWorker?.preferenceChanged(enabled) });
506
530
  const codexModelCatalog = createCodexModelCatalog();
507
- activeServer = await startAdapter(ADAPTER_PORT, ADAPTER_HOST, {
531
+ activeServer = await startAdapter(serviceWorker?.warming ? 0 : ADAPTER_PORT, serviceWorker?.warming ? "127.0.0.1" : ADAPTER_HOST, {
508
532
  log: startupLogger("Service"),
509
533
  autoReviewModelResolver: () => autoReviewPreference(),
510
534
  codexClient: profileRuntime.codexClient,
@@ -517,6 +541,7 @@ try {
517
541
  streamIdleTimeoutMs: RUNTIME.streamIdleTimeoutMs,
518
542
  terminalAnimationTheme,
519
543
  terminalActivity: terminalConsole,
544
+ handoffState: serviceWorker?.takeState(), isDraining: () => serviceWorker?.draining === true,
520
545
  dashboardOptions: { serviceControl, host: ADAPTER_HOST, port: ADAPTER_PORT,
521
546
  credentialsChanged: () => { defaultCopilotClient.invalidateCredentials();profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient }); },
522
547
  applyAnimation: theme => terminalConsole.apply({ theme }) },
@@ -555,20 +580,20 @@ try {
555
580
  startupComplete = true;
556
581
  console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
557
582
  await launchDashboard();
558
- terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
583
+ if (!serviceWorker?.warming) { terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args)); }
559
584
 
560
585
  const shutdown = async (signal) => {
561
586
  if (shuttingDown) return;
562
587
  shuttingDown = true;
563
- LOGGING.setTerminalSink(null);terminalConsole?.cleanup();
588
+ LOGGING.setTerminalSink(serviceWorker?.draining ? () => {} : null);terminalConsole?.cleanup();
564
589
  console.log(`\n${status("wait", `Stopping: ${signal}`)}`);
565
590
  let exitCode = 0;
566
591
  try {
567
592
  if (modelRefreshTimer) clearInterval(modelRefreshTimer);
568
- await clientIntegration?.close();
569
- await providerRuntime?.close();
570
593
  const result = await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });
571
594
  if (result.forced) console.warn(status("warn", "Remaining service connections closed"));
595
+ await clientIntegration?.close();
596
+ await providerRuntime?.close();
572
597
  await flushUsageWrites();
573
598
  } catch (e) {
574
599
  exitCode = 1;
@@ -581,6 +606,44 @@ try {
581
606
  process.once("SIGINT", () => { void shutdown("SIGINT"); });
582
607
  process.once("SIGTERM", () => { void shutdown("SIGTERM"); });
583
608
  await compressionSetup;
609
+ if (serviceWorker) {
610
+ const { clientStateFingerprint, serviceBusinessState } = await import("../src/service-worker.mjs");
611
+ if (serviceWorker.preserving) providerRuntime.validateLocalKeys();
612
+ await serviceWorker.ready({
613
+ notice: code => console.warn(status("warn", `Nightly update paused: ${code}. Run ccdx update github for details.`)),
614
+ stop: () => shutdown("supervisor"),
615
+ exportState: () => ({ ...activeServer.ccdxExportState(), providers: providerRuntime.exportPrivateState() }),
616
+ importState: async state => { await activeServer.ccdxImportState(state);providerRuntime.importPrivateState(state.providers); },
617
+ release: async () => {
618
+ terminalConsole.pause();await flushUsageWrites();await LOGGING.cleanup();
619
+ LOGGING = configureLogging({ env: { ...process.env, CCDX_LOG_PATH: "" } });LOGGING.setTerminalSink(() => {});
620
+ await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });await earlyIntegration.pauseForUpdate();
621
+ },
622
+ resume: async () => {
623
+ if (!activeServer.listening) await new Promise((resolve, reject) => { activeServer.once("error", reject);activeServer.listen(ADAPTER_PORT, ADAPTER_HOST, () => { activeServer.off("error", reject);resolve(); }); });
624
+ await earlyIntegration.start();earlyIntegration.setPredictionActive(servicePreferences().prediction_enabled);
625
+ await LOGGING.cleanup();LOGGING = configureLogging();terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
626
+ },
627
+ promote: async () => {
628
+ await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });
629
+ await new Promise((resolve, reject) => { activeServer.once("error", reject);activeServer.listen(ADAPTER_PORT, ADAPTER_HOST, () => { activeServer.off("error", reject);resolve(); }); });
630
+ if (codexEnabled) { nativePrediction = await earlyIntegration.start();await nativePrediction?.prepareRoute();earlyIntegration.setPredictionActive(servicePreferences().prediction_enabled); }
631
+ },
632
+ activate: async () => {
633
+ await LOGGING.cleanup();try { LOGGING = configureLogging(); } catch { LOGGING = configureLogging({ env: { ...process.env, CCDX_LOG_PATH: "" } }); }
634
+ terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
635
+ },
636
+ inspect: () => {
637
+ const data = activeServer.ccdxSnapshot(), routes = data.requests.by_route;
638
+ let fingerprint = null;try { fingerprint = clientStateFingerprint(); } catch {}
639
+ return { version: LOCAL_VERSION, fingerprint, business: serviceBusinessState(providerRuntime),
640
+ busy: !fingerprint || activeServer.ccdxBusy() || clientIntegration.busy() || data.models.refresh_in_flight === true || data.model_activity.active === null,
641
+ health: { github: profileRuntime.codexClient.runtimeStatus().token_cached === true && !profileModels.codexRegistry.lastError,
642
+ m365: data.providers?.m365?.state === "ready", prediction: earlyIntegration.bridgeHealthy() },
643
+ activity: { active: data.model_activity.active || 0, total: ["responses", "responses_compact", "messages"].reduce((n, key) => n + (routes[key]?.total || 0), data.image_generation?.total || 0) } };
644
+ },
645
+ });
646
+ }
584
647
  } catch (e) {
585
648
  LOGGING.setTerminalSink(null);terminalConsole?.cleanup();
586
649
  console.error(status("err", e.message));
@@ -212,7 +212,7 @@ boundary, not a plugin framework, daemon, IPC protocol or package split.
212
212
  The HTTP dispatch boundary rejects browser Origin-bearing inference requests
213
213
  before body admission, credential use or provider dispatch; native LAN opt-in is unchanged.
214
214
 
215
- Package installation is an explicit management operation in `package-update.mjs`,
215
+ Manual package installation is an explicit management operation in `package-update.mjs`,
216
216
  not part of inference or optional client integration. Windows uses the system
217
217
  command interpreter only for the fixed `npm.cmd` installer command; stable-tag
218
218
  validation remains upstream of launch. macOS/Linux use direct npm argv. There
@@ -231,7 +231,7 @@ The source lock retains exact versions/integrities without binding smol-toml to
231
231
  developer's corporate feed; omitted registry resolution is delegated to npm.
232
232
  Readonly update preflight reports Node/npm, the running package and npm's selected
233
233
  global target. A different target warns, but never changes PATH or prefix. Its
234
- bounded npm probe is limited to explicit update and full doctor commands.
234
+ bounded npm probe is limited to explicit update/full doctor commands and opted-in supervisor startup, never inference.
235
235
  Its stdout/stderr are captured separately; npm configuration warnings do not
236
236
  leak into doctor output. The real installer's inherited streams are unchanged.
237
237
  After installation, the updater verifies bounded package metadata at that same
@@ -533,7 +533,7 @@ Byte-weighted request admission is not a simultaneous-stream limit. The 1.2.0 lo
533
533
  and no-Node bootstraps. It bounds downloads/decompression, verifies the exact
534
534
  release package and checksum, backs up only this package/commands under an
535
535
  exclusive lock, restores on failure and validates the version/sharp/broker.
536
- It reuses the selected npm's bundled downloader with named proxy/CA/TLS/offline settings and no retries; no new download dependency is added. No installer work runs on startup or inference paths. `package-update.mjs` keeps
536
+ It reuses the selected npm's bundled downloader with named proxy/CA/TLS/offline settings and no retries; no new download dependency is added. No network installation runs on ordinary startup or inference paths. Opted-in supervisor startup copies/verifies its current immutable runtime; its separate night scheduler is described below. `package-update.mjs` keeps
537
537
  source choice, named npm-policy probes and fixed platform launch arguments;
538
538
  verified filenames enter cmd.exe, while paths enter cwd. Private-runtime commands
539
539
  are regenerated before committing a successful update. This provides error
@@ -701,3 +701,94 @@ backup during native reconciliation, before the config transaction commits.
701
701
  Unknown/partial caches are not claimed. On config commit failure, the old cache
702
702
  is restored only if the client has not created a new cache. This is a bounded
703
703
  schema migration, not a periodic cache purge or a credential/session reset.
704
+
705
+
706
+ ## Optional supervised nightly updates
707
+
708
+ `nightly-update.mjs` owns local-window/version eligibility, bounded public Release
709
+ lookup, policy-preserving staging and real runtime checks. It reuses
710
+ `release-install.mjs` package transactions, checksum checks and private command
711
+ writers. Rollback restores launcher symlinks by link text; it never follows a
712
+ relative symlink from its backup location. Completed rollback is idempotent and
713
+ cleanup errors do not conceal a successful restoration.
714
+
715
+ `service-supervisor.mjs` is loaded by normal `start` only after an explicit saved
716
+ opt-in and recognized/writable npm preflight. It keeps a foreground controller
717
+ and one active gateway worker, briefly warming a second candidate on an internal
718
+ loopback port. It stages beside the active immutable tree and serializes
719
+ one version transition. The controller carries no request-forwarding hot path.
720
+ Manual startup and all other commands retain their existing process model.
721
+ An unsupported copy/verification setup falls back to ordinary startup.
722
+
723
+ `service-worker.mjs` is the version-one private process protocol. It is enabled
724
+ only on an inherited IPC channel plus the worker marker, not by a WebUI request.
725
+ It exposes bounded inspect/quiesce/import/release/promote/resume/commit operations
726
+ to its parent and
727
+ forwards preference changes and notices; notices use the worker's existing
728
+ terminal sink. Source/model defaults, client files and sign-in fingerprints are
729
+ compared around the transition. Maintenance startup defers client synchronizers,
730
+ skips interactive login and client writes, checks selected GitHub discovery
731
+ without inference, and imports history before taking the original public port.
732
+ The old instance retains its provider state until the warmed replacement passes
733
+ validation; rollback resumes it rather than rebuilding a cold directory. GitHub
734
+ identity comparisons ignore refreshed verification timestamps.
735
+
736
+ `response-history.mjs` validates complete acyclic source-namespaced history and
737
+ its byte/entry budget before publication. `image-references.mjs` validates
738
+ provider-scoped image handles before importing its bounded LRU. `api-secrets.mjs` permits private transfer only of cached references still allowed
739
+ by the unchanged configuration. Those plaintext in-memory values remain confined
740
+ to inherited IPC; they are never written to a checkpoint, UI snapshot or log. The snapshot is consumed and released during
741
+ private handoff; no plaintext disk checkpoint or key-store rewrite is added.
742
+ `optional-routes.mjs` also counts pending optional requests so management/sign-in
743
+ work cannot be mistaken for an idle gateway. Ordinary shutdown drains HTTP
744
+ requests before closing providers. User stop/disconnect takes precedence over
745
+ updates; fallback is attempted once, not an unbounded restart loop.
746
+
747
+ The schema and failure limits, local schedule, install-owner checks and recovery
748
+ boundaries are normative in REFERENCE.md. Future patch releases accepted by this
749
+ channel must preserve private protocol v1 and the native client contracts.
750
+
751
+ ## Incremental Web rendering and cold-start sharing
752
+
753
+ `dashboard/view-boundary.js` contains optional view failures without introducing
754
+ a plugin runtime. Only a fixed set of view methods is wrapped; a failed view
755
+ keeps the latest arguments per method for explicit retry. Shared refresh
756
+ generation checks and request cancellation remain in `refresh.js`.
757
+ `dashboard/flow.js` retains active detail rows by request ID. CSS alone rotates
758
+ the theme ring, with visibility/staleness and reduced-motion gates.
759
+
760
+ `dashboard.mjs` snapshots the static bundle lazily, checks its package version,
761
+ stamps HTML resource URLs, and computes byte-specific ETags once. Sensitive and
762
+ dynamic endpoints remain uncached. No shell/provider dependency is added to
763
+ rendering, and no content-bearing response is reused across credential scopes.
764
+
765
+ `api-secrets.mjs` joins concurrent reads of one reference and prevents late
766
+ reads from republishing after clear/set/remove. `providers/api.mjs` reuses the
767
+ existing cancellation-aware single-flight for transport initialization: one
768
+ waiter cannot abort another, while the last cancellation or provider closure
769
+ stops the shared setup. Existing native stream validation, byte admission,
770
+ connection reuse, bounded metrics/logging and pinned source semantics remain.
771
+
772
+
773
+ ## Request evidence and optional counting
774
+
775
+ The existing AsyncLocalStorage request context owns safe requested model and
776
+ client evidence before model resolution. Claude keeps the outer HTTP context,
777
+ while its generation metrics stay separate from count operations. Selected
778
+ source/model, logical upstream calls and fixed resolution reasons reach HTTP
779
+ diagnostics; no alternate route is chosen to improve a diagnostic result.
780
+
781
+ `providers/api-token-count.mjs` is owned by one immutable manual-API
782
+ configuration. It joins bounded identical count operations with independent
783
+ waiter cancellation and keeps only bounded, short-lived 404 observations.
784
+ It does not implement a general circuit breaker, protocol translation,
785
+ inference fallback or tokenizer. Counts have their own diagnostics category;
786
+ generation failure totals do not include this auxiliary capability.
787
+
788
+ Flow rendering caches geometry until observed element size, topology, model
789
+ labels or language change. Phase-only updates retain SVG path/circle nodes.
790
+ Hidden pages stop the two-second status timer and refresh on visibility return;
791
+ foreground freshness and the existing CSS motion remain unchanged. Catalog
792
+ failure backoff is source-revision scoped and never holds the configuration
793
+ transaction during network work. Existing body serialization ownership is
794
+ retained: the ordinary manual Responses path serializes its final body once.
package/docs/REFERENCE.md CHANGED
@@ -1302,7 +1302,7 @@ Unknown support prevents an explicitly requested exception from starting.
1302
1302
  For an older updater that still requires Git, install the Release tarball directly:
1303
1303
 
1304
1304
  ```sh
1305
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.21/codex-copilot-dx-1.2.21.tgz
1305
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.23/codex-copilot-dx-1.2.23.tgz
1306
1306
  # Windows PowerShell: use npm.cmd instead of npm.
1307
1307
  ```
1308
1308
 
@@ -1693,11 +1693,14 @@ The protected `/_ccdx/ui/account` and `/_ccdx/ui/checks` APIs require loopback,
1693
1693
  ## HTTP error diagnostics
1694
1694
 
1695
1695
  `http_errors.recent` keeps its 20-record rolling view. Independent
1696
- `actionable_recent` (20 inference/other failures) and `protocol_recent` (eight
1697
- image-MCP HTTP 405 records) prevent route/method noise from erasing inference
1698
- evidence. `by_category` counts inference, protocol, route and other HTTP failures;
1696
+ `actionable_recent` (20 generation/other failures and actionable count errors),
1697
+ `capability_recent` (20 token-count errors), `route_recent` (eight path errors)
1698
+ and `protocol_recent` (eight image-MCP HTTP 405 records) prevent route/method noise from erasing inference
1699
+ evidence. `by_category` counts inference, capability, protocol, route and other HTTP failures;
1699
1700
  classification does not discard errors, grant access or retry requests.
1700
- The WebUI prioritizes actionable records; raw HTTP counters remain visible.
1701
+ The WebUI defaults to reply issues and provides separate capability and connection/path views. Repeated capability/path notices are grouped within the bounded retained records, with their occurrence count and latest request details; raw HTTP counters remain visible. A count-endpoint 404 is not a failed generation. Count authentication, rate-limit and server failures remain actionable.
1702
+
1703
+ Before model resolution, safe requested model IDs and the client hint are retained even for local rejection. Known binding failures include a specific reason: model not selected, ambiguous name, unavailable catalog entry or disabled access. These diagnostics never authorize a model or replace it with a default. Claude records propagate the actual model/source and distinguish a cached capability result from an upstream HTTP failure. Upstream attempts count logical calls; shared counts are marked `shared_upstream`, and cached 404s report zero calls. No prompt or key is retained.
1701
1704
 
1702
1705
  New records retain safe error code/type/parameter paths, method, an allowlisted
1703
1706
  endpoint without a query, and upstream attempt count. Requested/served model
@@ -1806,7 +1809,7 @@ Set `CCDX_LOG_PATH=1` to record diagnostic logs independently of quiet terminal
1806
1809
 
1807
1810
  Long computer-use sessions can accumulate screenshots that are sent again on later turns. This can increase local preparation time, upstream handshake latency, and the chance of a `413 Payload Too Large` response.
1808
1811
 
1809
- The response-history cache is process-local and byte/entry bounded. Restarting the adapter discards it; a `previous_response_id` stored only in that process becomes unavailable. CCDX does not persist conversation history to disk. Near-limit status diagnostics report the largest tree and actual lookup misses, but do not recover an already evicted ID or change the cache budget. Clients can still submit explicit history in the request body, subject to the same limits.
1812
+ The response-history cache is process-local and byte/entry bounded. Ordinary adapter restarts discard it; verified opt-in nightly handoff is the exception described below. Without such a handoff, a `previous_response_id` stored only in that process becomes unavailable. CCDX does not persist conversation history to disk. Near-limit status diagnostics report the largest tree and actual lookup misses, but do not recover an already evicted ID or change the cache budget. Clients can still submit explicit history in the request body, subject to the same limits.
1810
1813
 
1811
1814
  CCDX attempts to downsample inline base64 images to model-appropriate pixel bounds, with a 2048 px long-edge fallback, and initially encodes them as WebP quality 82. It never replaces an image with a larger encoding and uses one global concurrency limit across direct images and function/custom-tool outputs. GIFs and non-inline references are not re-encoded. An encoding/decode failure keeps the original image; the final request-byte limit still applies.
1812
1815
 
@@ -1948,3 +1951,136 @@ The Responses WebSocket protocol is not implemented by CCDX. Upgrade requests
1948
1951
  are refused promptly so supported native clients can fall back to HTTP/SSE.
1949
1952
  This is tested separately from model-directory and provider-identity behavior;
1950
1953
  SSE events are not relabeled as a WebSocket protocol.
1954
+
1955
+
1956
+ ### Nightly updates (opt-in)
1957
+
1958
+ Available from 1.2.22 after one manual upgrade. Settings → Version & updates →
1959
+ Update overnight writes the boolean `nightly_updates`, false when absent. Enabling
1960
+ it requires a normal CCDX restart; disabling it cancels pending automatic work in
1961
+ a supervised service. Management-only `ccdx web` never installs updates. The risk
1962
+ text explains that automatic installation/restart can affect conversation
1963
+ continuation. The feature does not promise zero downtime or infallible rollback.
1964
+
1965
+ Only an owned, writable npm installation with recognized command launchers can
1966
+ use the supervisor. Standard execution stays unchanged when disabled. When enabled,
1967
+ a foreground parent runs the gateway from an immutable private package tree;
1968
+ Ctrl+C stops both, and no launchd/systemd/Windows service or boot task is installed.
1969
+ Stopping CCDX, sleeping or powering off does not start a separate updater. After
1970
+ a long observation gap, a new ten-minute idle interval is required.
1971
+
1972
+ The parent observes bounded local state once a minute. A release check occurs at
1973
+ most once per local calendar day, within 00:00–04:00, after ten observed idle
1974
+ minutes. The new version must be a stable patch in the same major/minor series
1975
+ and have been published at least 24 hours earlier. No prerelease or automatic
1976
+ minor/major migration is accepted. Active inference, image work, configuration
1977
+ operations, discovery or sign-in defer the update. New work during preparation
1978
+ also defers it. Checks do not invoke models.
1979
+
1980
+ Preparation uses the official pinned GitHub Release tarball and checksum, an
1981
+ independent npm prefix, the configured registry/proxy/CA/TLS/offline policy and
1982
+ ignored lifecycle scripts. Existing private-runtime launchers are regenerated;
1983
+ custom launchers are not silently claimed. No Git, new Node installation,
1984
+ permission override, certificate change or public-registry fallback is added.
1985
+ A policy refusal, unavailable dependency or runtime check failure leaves the
1986
+ current service running. The supported native broker is checked when already
1987
+ present in the original installation.
1988
+
1989
+ Before switching, the parent compares client/configuration fingerprints and
1990
+ authorized model/default selections, backs up the global package and commands,
1991
+ and validates the candidate on an internal loopback-only ephemeral listener while
1992
+ the current instance continues serving. Previously healthy selected sources must remain healthy, every previously
1993
+ published model must remain available, and defaults/credential scopes must match.
1994
+ Additional upstream models are allowed. API discovery publication and client
1995
+ writers are paused during this warmup. Only then is the old gateway quiesced.
1996
+ A bounded private IPC message transfers Responses
1997
+ history, source-scoped parent links/opaque items, image-edit references and
1998
+ already-cached API keys limited to unchanged configured references.
1999
+ Conversation payloads, image references and cached keys are never written to a
2000
+ handoff file or diagnostics. Ordinary process-local counters begin a new run;
2001
+ retained usage files remain available.
2002
+ The combined serialized state is limited to 64 MiB; oversized/busy state defers
2003
+ the update without eviction. New requests during the brief switching interval
2004
+ can receive a temporary failure with `Retry-After: 1`.
2005
+
2006
+ The warmed replacement imports state before taking over the same main port. Its
2007
+ maintenance startup preserves client configuration, skips interactive GitHub
2008
+ login, and opens neither browser nor client. Model/default selections and
2009
+ configuration fingerprints must match before it accepts normal traffic. Failed
2010
+ startup, discovery or a mismatched candidate leaves the original instance
2011
+ alive. A failed port/prediction handover attempts package rollback and resumes
2012
+ that same instance with its original caches. Cleanup of a retired runtime is
2013
+ best-effort; pending cleanup suspends further automatic transitions. The old
2014
+ process is retired only
2015
+ after the replacement has acknowledged acceptance. A deliberate Ctrl+C
2016
+ never starts another worker. Unexpected later worker exits are reported once;
2017
+ this is not a general crash-respawn mechanism.
2018
+
2019
+ The private `nightly-update-state.json` beside settings stores only the attempted
2020
+ local day and paused version. Installed candidates that fail verification are
2021
+ not repeatedly attempted; a newer version or explicit manual update is needed.
2022
+ Unreadable records pause automatic updates without stopping the gateway. A
2023
+ failed package rollback or failed restoration can require manual recovery;
2024
+ Settings retains the full platform installation commands.
2025
+
2026
+ ### Web resilience and resource versions
2027
+
2028
+ Optional status/usage/animation views contain local initialization/render errors,
2029
+ retain the surrounding shell and expose a local retry. Retry replays only the
2030
+ latest bounded call state per view method. Network errors retain their existing
2031
+ last-successful snapshots and explicit unknown/error status. Request-flow detail
2032
+ rows are keyed and updated in place, retaining selection and DOM identity.
2033
+
2034
+ The flow atom's thin ring is static while idle and rotates once per five seconds
2035
+ while fresh active requests are observed, including waits/retries. The atom itself
2036
+ does not rotate; counts do not accelerate the ring. Hidden/stale views stop it,
2037
+ and reduced motion disables rotation. Existing curves, tables, palettes,
2038
+ client identification and authorization remain unchanged.
2039
+
2040
+ Static dashboard bytes are snapshotted together on first use and reused by the
2041
+ process. HTML remains `no-store` and stamps script/style URLs with the service
2042
+ version. Other assets use content-derived ETags and `no-cache` revalidation;
2043
+ matching validators return 304. A mismatched version query returns 409 rather
2044
+ than mixing resources, requiring a page reload. If the installed package changed
2045
+ before a coherent bundle could be loaded, the optional page fails explicitly;
2046
+ inference remains separate. Protected JSON/account/settings routes stay
2047
+ `no-store`. No API-body caching, compression worker or new dependency is added.
2048
+
2049
+ `CCDX_SUPERVISED_SERVICE` is an internal inherited worker marker. It is used only
2050
+ with a private parent IPC channel; do not set it as a user preference. It grants
2051
+ no network action and is not a replacement for the saved nightly-update opt-in.
2052
+
2053
+
2054
+ ### Manual API token counting
2055
+
2056
+ Messages support does not establish support for `POST /v1/messages/count_tokens`.
2057
+ CCDX forwards the configured Messages endpoint plus `/count_tokens`. A manual
2058
+ API's observed HTTP 404 is remembered in memory for 60 seconds, separately for
2059
+ each model and Anthropic version/beta-header scope. This is an observed endpoint
2060
+ failure, not a declaration that the model source is down. Cached and initial
2061
+ results return HTTP 404 with `ccdx_api_count_tokens_unavailable`; no estimated
2062
+ or synthetic count is returned. Changing the source configuration/key creates
2063
+ a new scope. Other statuses, including 401/403/405/429/5xx, are not cached by
2064
+ this compatibility mechanism; status and safe Retry-After metadata survive.
2065
+
2066
+ Identical concurrent count requests share one bounded upstream operation.
2067
+ Each caller cancels independently; the last cancelled waiter aborts shared
2068
+ work. Joining is limited to bodies up to 1 MiB, 16 shared operations and 4 MiB
2069
+ of shared request text. Larger/overflow requests use their normal admitted
2070
+ path. Count responses are capped at 64 KiB. At most 128 recent unavailable
2071
+ scopes are retained. Successful results and request bodies are not retained
2072
+ after the operation. Counts neither invoke generation nor fail over to another
2073
+ source. This does not supply a missing tokenizer or guarantee every Claude App
2074
+ context-management feature on a third-party model.
2075
+
2076
+ Background manual-API catalog failures back off for 1, 5, 30 and then 120
2077
+ minutes; successful publication resets the sequence. Explicit refresh retains
2078
+ the existing one-minute minimum interval rather than the longer background
2079
+ backoff. A valid upstream Retry-After also applies, bounded to 24 hours. These
2080
+ are read eligibility gates, not added background retry timers. Revision changes
2081
+ invalidate prior eligibility and obsolete results never publish.
2082
+
2083
+ Claude Code's validated `x-claude-code-agent-id` separates a child task's local
2084
+ source guard from its parent's guard when a session is identified. Parent keys
2085
+ without that header remain unchanged. This header is correlation only: model
2086
+ access and the company's account/history checks remain authoritative.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.21",
3
+ "version": "1.2.23",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -42,6 +42,7 @@
42
42
  "test": "node --test",
43
43
  "test:smoke": "node scripts/offline-smoke.mjs && node scripts/sse-idle-replay.mjs",
44
44
  "test:package": "node scripts/package-lifecycle-smoke.mjs",
45
+ "test:nightly-package": "node scripts/nightly-package-replay.mjs",
45
46
  "test:e2e": "bash test/e2e.sh",
46
47
  "bench": "node scripts/benchmark.mjs",
47
48
  "bench:payload": "node scripts/benchmark.mjs --large-payload",
@@ -116,6 +116,6 @@ export function createAccountTools({ home = os.homedir(), env = process.env, fet
116
116
  online = null;checkedAt = null;checkedFingerprint = "";operation = null;await onChanged();
117
117
  return snapshot();
118
118
  }
119
- return { snapshot, check, start, cancel, logout, wait: async () => { await operation?.task;return snapshot(); },
119
+ return { snapshot, check, start, cancel, logout, busy: () => Boolean(checkFlight || operation && ["starting", "authorizing", "verifying"].includes(operation.state)), wait: async () => { await operation?.task;return snapshot(); },
120
120
  async reload() { await onChanged();return snapshot(); }, dispose() { operation?.controller.abort(); } };
121
121
  }