codex-copilot-dx 1.3.7 → 1.3.9

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 (46) hide show
  1. package/README.md +7 -16
  2. package/bin/cli.mjs +55 -31
  3. package/docs/ARCHITECTURE.md +25 -1
  4. package/docs/REFERENCE.md +45 -10
  5. package/package.json +3 -3
  6. package/src/claude-gateway.mjs +21 -18
  7. package/src/cli-command-spec.mjs +3 -2
  8. package/src/cli-image.mjs +2 -80
  9. package/src/cli-options.mjs +1 -1
  10. package/src/client-integration.mjs +11 -4
  11. package/src/connection-runtime.mjs +1 -0
  12. package/src/dashboard/connections.js +5 -1
  13. package/src/dashboard/console.js +12 -6
  14. package/src/dashboard/features.js +73 -0
  15. package/src/dashboard/index.html +15 -14
  16. package/src/dashboard/language.js +60 -16
  17. package/src/dashboard/tools.js +4 -1
  18. package/src/dashboard/ui.js +1 -1
  19. package/src/dashboard/usage.js +2 -2
  20. package/src/dashboard-api.mjs +7 -2
  21. package/src/dashboard-tools.mjs +2 -1
  22. package/src/dashboard.mjs +1 -0
  23. package/src/doctor-compat.mjs +19 -13
  24. package/src/doctor.mjs +1 -1
  25. package/src/image-setup.mjs +110 -0
  26. package/src/local-privacy.mjs +15 -11
  27. package/src/local-tools.mjs +8 -2
  28. package/src/messages-history-transfer.mjs +12 -2
  29. package/src/messages-system-policy.mjs +20 -0
  30. package/src/model-capabilities.mjs +2 -2
  31. package/src/native-prediction-profile.mjs +5 -2
  32. package/src/native-prediction.mjs +18 -2
  33. package/src/optional-routes.mjs +1 -1
  34. package/src/prediction-control.mjs +64 -0
  35. package/src/prediction-operations.mjs +68 -0
  36. package/src/prediction-preference.mjs +75 -0
  37. package/src/privacy-model.mjs +35 -21
  38. package/src/privacy-transform.mjs +35 -4
  39. package/src/providers/m365.mjs +5 -2
  40. package/src/service-control.mjs +33 -7
  41. package/src/service-supervisor.mjs +39 -18
  42. package/src/service-worker.mjs +13 -1
  43. package/src/terminal-console.mjs +2 -2
  44. package/src/usage-analytics.mjs +6 -1
  45. package/src/usage-store.mjs +21 -8
  46. package/src/usage.mjs +18 -5
package/README.md CHANGED
@@ -17,8 +17,8 @@ ccdx
17
17
 
18
18
  Without Node.js, download and run the installer for your system:
19
19
 
20
- - macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.7/install.sh), then `sh install.sh`.
21
- - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.7/install.ps1), then `./install.ps1` under your current shell policy.
20
+ - macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/latest/download/install.sh), then `sh install.sh`.
21
+ - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/latest/download/install.ps1), then `./install.ps1` under your current shell policy.
22
22
 
23
23
  The installer reuses a compatible Node.js or installs a private, verified copy. Git and a compiler are not required. Complete platform packages include their dependencies. Company registry, proxy, certificate and shell policies are kept.
24
24
 
@@ -57,22 +57,13 @@ Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; th
57
57
 
58
58
  **1.3 uses one command tree.** Old command names and the `codex-copilot-dx` executable have been removed. This changes command entrypoints, not saved accounts, model selections or chats. See the [command reference](docs/REFERENCE.md#commands).
59
59
 
60
- ## Optional features
60
+ ## Features and maintenance
61
61
 
62
- Images, native input suggestions and overnight updates are **off by default**. Existing enabled settings are retained.
62
+ Use the Web UI for accounts, APIs, models, client access, input suggestions, image setup, local masking, appearance, diagnostics and updates. CLI commands remain available for automation and recovery. See the [control reference](docs/REFERENCE.md#webui-and-cli-controls).
63
63
 
64
- - **Images:** `ccdx app codex image setup`. [Image guide](docs/REFERENCE.md#optional-image-generation).
65
- - **Input suggestions:** `ccdx app codex prediction setup`. Setup adds trust within the Codex profile and locally decrypts traffic for the configured prediction hosts. Read the [setup and removal guide](docs/REFERENCE.md#optional-native-predictions) first.
66
- - **Appearance and updates:** open Settings. Web and terminal colors are independent.
67
-
68
- ## Update and troubleshoot
69
-
70
- Finish active tasks before updating the active installation. Install the update, then restart CCDX normally:
71
-
72
- ```sh
73
- ccdx update github
74
- ccdx version
75
- ```
64
+ - **Input suggestions:** new integrations attempt setup by default when Codex is closed. Saved off choices are retained. The Web UI can enable, disable, finish setup, open Codex and repair the bridge. Setup synchronizes Show predictions, adds App-profile trust and locally decrypts the prediction hosts' HTTPS traffic. App/thread eligibility still applies. [Details](docs/REFERENCE.md#optional-native-predictions).
65
+ - **Images:** configure the address, key and model in Codex → Image generation. Image setup and overnight updates remain off by default.
66
+ - **Updates:** Settings → Install update downloads and verifies a stable release, then switches the installed service when idle. Busy work postpones the switch. Unmanaged launches require the installer or an installed command. [Details](docs/REFERENCE.md#installation-and-updates).
76
67
 
77
68
  Web UI activity updates through server push; the terminal uses the same in-process activity feed. Reconnecting restores current state and bounded recent records.
78
69
 
package/bin/cli.mjs CHANGED
@@ -38,6 +38,15 @@ if (CLI.command === "manage") {
38
38
  process.exit(1);
39
39
  }
40
40
  }
41
+ if (CLI.command === "update-managed") {
42
+ try {
43
+ if (!CLI.yes) throw new Error("Confirm with --yes to install and switch the idle service. You can also use Settings in the WebUI.");
44
+ const { dashboardToolRequest } = await import("../src/cli-tools.mjs");
45
+ const address = parseAdapterAddressOptions(process.env);
46
+ console.log(JSON.stringify((await dashboardToolRequest({ host: address.adapterHost, port: address.adapterPort, path: "settings", body: { action: "update", confirmed: true }, detailedErrors: true })).last_operation));
47
+ process.exit(0);
48
+ } catch (error) { console.error(status("err", error.message));process.exit(1); }
49
+ }
41
50
  if (CLI.command === "web") {
42
51
  try {
43
52
  const { runWebCommand } = await import("../src/cli-web.mjs");
@@ -95,11 +104,21 @@ if (CLI.command === "image") {
95
104
  }
96
105
  if (CLI.command === "prediction") {
97
106
  try {
98
- if (["pause", "resume"].includes(CLI.action)) {
99
- const { pauseServiceFeature } = await import("../src/cli-tools.mjs");
107
+ if (!["status", "fix"].includes(CLI.action)) {
108
+ const { checkRunningAdapter } = await import("../src/running-adapter.mjs");
109
+ const { dashboardToolRequest } = await import("../src/cli-tools.mjs");
100
110
  const address = parseAdapterAddressOptions(process.env);
101
- console.log(await pauseServiceFeature({ feature: "prediction", action: CLI.action, host: address.adapterHost, port: address.adapterPort }));
102
- process.exit(0);
111
+ const running = await checkRunningAdapter({ host: address.adapterHost, port: address.adapterPort });
112
+ const operation = { on: "setup", off: "remove", fix: "repair" }[CLI.action] || CLI.action;
113
+ if (running.ok) {
114
+ const data = await dashboardToolRequest({ host: address.adapterHost, port: address.adapterPort, path: "settings", body: { action: "prediction", operation }, detailedErrors: true, timeoutMs: 210000 });
115
+ const result = data.last_operation?.result || data.features?.prediction;
116
+ console.log(JSON.stringify(result));process.exit(result?.status === "failed" ? 1 : 0);
117
+ }
118
+ if (["enable", "disable", "setup", "remove", "pause", "resume", "open"].includes(operation)) {
119
+ const { controlPrediction } = await import("../src/prediction-control.mjs");
120
+ console.log(JSON.stringify(await controlPrediction(operation)));process.exit(0);
121
+ }
103
122
  }
104
123
  const { readAdapterStatus } = await import("../src/cli-status.mjs");
105
124
  const { runPredictionCommand } = await import("../src/native-prediction.mjs");
@@ -234,6 +253,24 @@ if (CLI.command === "doctor" && CLI.configOnly) {
234
253
  process.exit(checks.some((check) => check.kind === "err") ? 1 : 0);
235
254
  }
236
255
 
256
+ let serviceWorker = null;
257
+ if (CLI.command === "start" && !(process.send && process.env.CCDX_SUPERVISED_SERVICE === "1")) {
258
+ const { nightlyUpdatePreference } = await import("../src/user-settings.mjs");
259
+ const { checkRunningAdapter } = await import("../src/running-adapter.mjs");
260
+
261
+ const { installedUpdateEnvironment } = await import("../src/nightly-update.mjs");
262
+ const address = parseAdapterProbeOptions(process.env);
263
+ const existing = await checkRunningAdapter({ host: address.adapterHost, port: address.adapterPort, timeoutMs: address.existingAdapterTimeoutMs });
264
+ let environment;
265
+ try { if (!existing.ok && !existing.incompatible) environment = installedUpdateEnvironment(); }
266
+ catch { if (nightlyUpdatePreference()) console.warn(status("warn", "Dashboard updates need a writable, matching npm installation. Starting without automatic updates.")); }
267
+ if (environment) {
268
+ const { runServiceSupervisor } = await import("../src/service-supervisor.mjs");
269
+ try { process.exit(await runServiceSupervisor({ environment })); }
270
+ catch { console.warn(status("warn", "Nightly runtime preparation failed. Starting without automatic updates.")); }
271
+ }
272
+ }
273
+
237
274
  // Startup components are loaded only after read-only and local tool commands exit.
238
275
  const { ensureAuth, openCodex } = await import("../src/launcher.mjs");
239
276
  const { startAdapter } = await import("../src/adapter.mjs");
@@ -257,24 +294,9 @@ const { createTerminalConsole } = await import("../src/terminal-console.mjs");
257
294
  const { createServiceControl } = await import("../src/service-control.mjs");
258
295
  const { openDashboard } = await import("../src/browser-launch.mjs");
259
296
 
260
- let serviceWorker = null;
261
- if (CLI.command === "start") {
262
- if (process.send && process.env.CCDX_SUPERVISED_SERVICE === "1") {
263
- const { createServiceWorker } = await import("../src/service-worker.mjs");
264
- serviceWorker = await createServiceWorker();
265
- } else if (nightlyUpdatePreference()) {
266
- const { installedUpdateEnvironment } = await import("../src/nightly-update.mjs");
267
- const address = parseAdapterProbeOptions(process.env);
268
- const existing = await checkRunningAdapter({ host: address.adapterHost, port: address.adapterPort, timeoutMs: address.existingAdapterTimeoutMs });
269
- let environment;
270
- try { if (!existing.ok && !existing.incompatible) environment = installedUpdateEnvironment(); }
271
- catch { console.warn(status("warn", "Nightly updates need a writable, matching npm installation. Starting without automatic updates.")); }
272
- if (environment) {
273
- const { runServiceSupervisor } = await import("../src/service-supervisor.mjs");
274
- try { process.exit(await runServiceSupervisor({ environment })); }
275
- catch { console.warn(status("warn", "Nightly runtime preparation failed. Starting without automatic updates.")); }
276
- }
277
- }
297
+ if (CLI.command === "start" && process.send && process.env.CCDX_SUPERVISED_SERVICE === "1") {
298
+ const { createServiceWorker } = await import("../src/service-worker.mjs");
299
+ serviceWorker = await createServiceWorker();
278
300
  }
279
301
 
280
302
  let RUNTIME;
@@ -415,10 +437,9 @@ try {
415
437
  else if (command.status === "preserved") console.warn(startupCheck("warn", "Command", "Existing launcher preserved; use ccdx.cmd doctor to inspect it"));
416
438
  } catch { console.warn(startupCheck("warn", "Command", "Command setup skipped; service will start")); }
417
439
  }
418
- const updateNotice = runInBackground(printUpdateNotice);
419
440
  if (!serviceWorker?.warming && await reuseRunningAdapterIfAvailable()) {
420
441
  // Ready is already displayed; finish the bounded check before this short-lived CLI exits.
421
- await updateNotice;
442
+ await printUpdateNotice();
422
443
  serviceWorker?.reused();
423
444
  startupPresentation.finish();await LOGGING.cleanup();
424
445
  process.exit(0);
@@ -445,7 +466,7 @@ try {
445
466
  githubCredentialFingerprint: () => profileRuntime.codexCredentialFingerprint,
446
467
  log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "M365", message)) });
447
468
  const codexEnabled = providerRuntime.connections().clients.find(client => client.id === "codex").enabled;
448
- const predictionSetup = codexEnabled && !serviceWorker?.warming ? runInBackground(() => earlyIntegration.start()) : Promise.resolve(null);
469
+ const predictionSetup = codexEnabled && !serviceWorker?.warming ? runInBackground(() => earlyIntegration.start({ autoSetup: !serviceWorker?.preserving })) : Promise.resolve(null);
449
470
  const m365Setup = runInBackground(() => providerRuntime.start());
450
471
  if (providerRuntime.selection().codex === "github") {
451
472
  try { await ensureAuth({ log: startupLogger("Sign-in"), interactive: serviceWorker?.preserving !== true,
@@ -483,7 +504,9 @@ try {
483
504
  snapshot: () => activeServer?.ccdxSnapshot?.() || {},
484
505
  subscribe: listener => activeServer?.ccdxSubscribeActivity?.(listener),
485
506
  preferences: () => { const { saved, theme, color_theme } = serviceSettingsSnapshot();return { ...saved, theme, color_theme }; } });
486
- const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole, nightlyStatus: () => serviceWorker?.status() || null, nightlyChanged: enabled => serviceWorker?.preferenceChanged(enabled) });
507
+ const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole,
508
+ adapterPort: ADAPTER_PORT, adapterHost: ADAPTER_HOST, manualUpdate: serviceWorker ? () => serviceWorker.requestUpdate() : undefined,
509
+ nightlyStatus: () => serviceWorker?.status() || null, nightlyChanged: enabled => serviceWorker?.preferenceChanged(enabled) });
487
510
  const codexModelCatalog = createCodexModelCatalog();
488
511
  activeServer = await startAdapter(serviceWorker?.warming ? 0 : ADAPTER_PORT, serviceWorker?.warming ? "127.0.0.1" : ADAPTER_HOST, {
489
512
  log: startupLogger("Service"),
@@ -503,7 +526,7 @@ try {
503
526
  credentialsChanged: () => { defaultCopilotClient.invalidateCredentials();profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient }); },
504
527
  applyAnimation: theme => terminalConsole.apply({ theme }) },
505
528
  nativePredictionPac: () => clientIntegration?.pacUrl() || null,
506
- fixPrediction: async () => (await clientIntegrations()).fix(),
529
+ fixPrediction: async () => (await import("../src/prediction-control.mjs")).controlPrediction("repair", { integration: await clientIntegrations() }),
507
530
  clientIntegrationSnapshot: () => clientIntegration?.snapshot() || null,
508
531
  });
509
532
 
@@ -536,6 +559,7 @@ try {
536
559
 
537
560
  startupComplete = true;
538
561
  if (!startupPresentation.enabled) console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
562
+ runInBackground(printUpdateNotice);
539
563
  await launchDashboard();
540
564
  if (!serviceWorker?.warming) {
541
565
  startupPresentation.finish();for (const [method, args] of startupPresentation.warnings) terminalConsole.log(method, args);
@@ -571,7 +595,7 @@ try {
571
595
  const { clientStateFingerprint, serviceBusinessState } = await import("../src/service-worker.mjs");
572
596
  if (serviceWorker.preserving) providerRuntime.validateLocalKeys();
573
597
  await serviceWorker.ready({
574
- notice: code => console.warn(status("warn", `Nightly update paused: ${code}. Run ccdx update github for details.`)),
598
+ notice: code => console.warn(status("warn", `Update notice: ${code}. See Checks & repairs in the WebUI.`)),
575
599
  stop: () => shutdown("supervisor"),
576
600
  exportState: () => ({ ...activeServer.ccdxExportState(), providers: providerRuntime.exportPrivateState() }),
577
601
  importState: async state => { await activeServer.ccdxImportState(state);providerRuntime.importPrivateState(state.providers); },
@@ -582,13 +606,13 @@ try {
582
606
  },
583
607
  resume: async () => {
584
608
  if (!activeServer.listening) await new Promise((resolve, reject) => { activeServer.once("error", reject);activeServer.listen(ADAPTER_PORT, ADAPTER_HOST, () => { activeServer.off("error", reject);resolve(); }); });
585
- await earlyIntegration.start();earlyIntegration.setPredictionActive(servicePreferences().prediction_enabled);
609
+ await earlyIntegration.start({ autoSetup: false });earlyIntegration.setPredictionActive(servicePreferences().prediction_enabled);
586
610
  await LOGGING.cleanup();LOGGING = configureLogging();terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
587
611
  },
588
612
  promote: async () => {
589
613
  await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });
590
614
  await new Promise((resolve, reject) => { activeServer.once("error", reject);activeServer.listen(ADAPTER_PORT, ADAPTER_HOST, () => { activeServer.off("error", reject);resolve(); }); });
591
- if (codexEnabled) { nativePrediction = await earlyIntegration.start();await nativePrediction?.prepareRoute();earlyIntegration.setPredictionActive(servicePreferences().prediction_enabled); }
615
+ if (codexEnabled) { nativePrediction = await earlyIntegration.start({ autoSetup: false });await nativePrediction?.prepareRoute();earlyIntegration.setPredictionActive(servicePreferences().prediction_enabled); }
592
616
  },
593
617
  activate: async () => {
594
618
  await LOGGING.cleanup();try { LOGGING = configureLogging(); } catch { LOGGING = configureLogging({ env: { ...process.env, CCDX_LOG_PATH: "" } }); }
@@ -598,7 +622,7 @@ try {
598
622
  const data = activeServer.ccdxSnapshot(), routes = data.requests.by_route;
599
623
  let fingerprint = null;try { fingerprint = clientStateFingerprint(); } catch {}
600
624
  return { version: LOCAL_VERSION, fingerprint, business: serviceBusinessState(providerRuntime),
601
- busy: !fingerprint || activeServer.ccdxBusy() || clientIntegration.busy() || data.models.refresh_in_flight === true || data.model_activity.active === null,
625
+ busy: !fingerprint || activeServer.ccdxBusy() || clientIntegration.busy() || serviceControl.busy() || data.models.refresh_in_flight === true || data.model_activity.active === null,
602
626
  health: { github: profileRuntime.codexClient.runtimeStatus().token_cached === true && !profileModels.codexRegistry.lastError,
603
627
  m365: data.providers?.m365?.state === "ready", prediction: earlyIntegration.bridgeHealthy() },
604
628
  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) } };
@@ -521,7 +521,7 @@ projects the optional lightweight response; full status stays the default public
521
521
  contract. Hidden status regions defer DOM updates, and summary rendering never
522
522
  replaces the full request/history cache.
523
523
 
524
- `dashboard/usage.js` owns bar/curve geometry and viewport-gated, one-shot Web Animations. The two views share retained analytics and accessible day buttons; their paths never connect unavailable history or overshoot adjacent values. View-only changes leave the calendar nodes intact. The UI lifecycle cancels motion on hidden/suspended views and reduced-motion changes; no animation timer or chart dependency is added. `usage-store.mjs` shares cache-evidence validation between retained summaries and process-local totals; runtime snapshots expose the weighted cache ratio plus a partial-evidence flag, without new persistence or log scans. The Overview renderer formats that snapshot and preserves unknown/invalid values.
524
+ `dashboard/usage.js` owns bar/curve geometry and viewport-gated, one-shot Web Animations. The two views share retained analytics and accessible day buttons; their paths never connect unavailable history or overshoot adjacent values. View-only changes leave the calendar nodes intact. The UI lifecycle cancels motion on hidden/suspended views and reduced-motion changes; no animation timer or chart dependency is added. `usage-store.mjs` shares cache-evidence validation between retained summaries and process-local totals. It keeps paired input/cache-read sums and known/unknown record counts separate from full token totals; CLI/TUI, WebUI and daily analytics use those same sums for the weighted rate and partial-coverage flag. Aggregate snapshots expose that basis without new persistence or log scans. The Overview renderer formats that snapshot and preserves unknown/invalid values.
525
525
 
526
526
  `dashboard-updates.mjs` is loaded only by the protected update-information route. It projects bounded public stable-release metadata and publication dates, with process-local single-flight, five-minute success and one-minute failure caches. Its asynchronous npm network-configuration read reuses the installer's existing policy-preserving downloader; it adds no runtime dependency, credentials or synchronous child process on the service event loop. Metadata has a four-second per-request deadline and 128 KiB decoded-body bound. It never installs or restarts anything and does not alter startup's independent web-redirect lookup. `dashboard/updates.js` renders current/available/unknown states and validated, pinned installation command text; `refresh.js` owns its visible Settings refresh cadence. Failed checks preserve explicitly labeled prior metadata. No provider authentication or inference is involved.
527
527
 
@@ -1069,3 +1069,27 @@ Progress and readiness share the existing coalesced activity SSE. The settings c
1069
1069
  Local privacy failures carry a separate origin. Request-check and response-restoration messages state different outcomes. Explicit failed tool results in the latest Messages input add only a count to request metadata, without retaining their content or changing a successful model response into a claim of tool-workflow success. SDK tests use independent client parsers; native CLI replays execute a local MCP fixture in temporary profiles, return its result and require the following response to complete.
1070
1070
 
1071
1071
  Claude passthrough now holds incomplete SSE frames and validates complete data before forwarding. Malformed tails do not precede the terminal error; valid final JSON without a newline remains deliverable. Capability restoration and replacement writes use the existing ownership journal in one transaction, preserving both files and ownership on failure.
1072
+
1073
+ ## WebUI feature controls
1074
+
1075
+ `service-control.mjs` serializes management actions and projects saved/effective state. WebUI and CLI prediction/update commands call this same boundary. `prediction-control.mjs` coordinates existing native setup, bridge lifecycle and App launch; `prediction-preference.mjs` owns the closed-App display-setting transaction across desktop TOML and legacy state. A pending display write is explicit and never reported as visible-suggestion proof. Fresh default setup runs only before App launch and preserves saved off choices.
1076
+
1077
+ `image-setup.mjs` owns image provider inspection and the existing atomic config/credential and guidance transaction. CLI owns terminal prompts; `dashboard/features.js` owns browser forms. Neither renderer receives saved image keys. The model compatibility action uses `doctor-compat.mjs` through local tools and requires explicit quota confirmation.
1078
+
1079
+ The existing supervisor accepts a bounded manual update request as well as its optional nightly scheduler. Both use the same staged package verification, immutable worker, state-transfer, installation commit and rollback path. Manual and scheduled updates are mutually exclusive; settings operations contribute to busy state and image configuration and stable prediction intent/trust participate in the state fingerprint; native port allocation and App stat bookkeeping do not. Warm handoff suppresses first-time prediction setup and pending display writes. Explicit prediction reconfiguration replaces the old bridge after committing trust. An unowned installation falls back to the existing standalone launch and exposes that self-update is unavailable. No inference protocol, privacy transport or native authentication path is changed by these controls.
1080
+
1081
+ Native discovery, configuration and startup environment inspection run in bounded temporary `prediction-operations.mjs` workers. PowerShell, certificate and filesystem work do not block the gateway event loop. Registered-App discovery precedes default trust/proxy setup; missing Apps leave core startup available. Private environment results feed only bridge initialization and are not returned by WebUI actions.
1082
+
1083
+ ### Stable Messages prefixes and bounded privacy work
1084
+
1085
+ `messages-system-policy.mjs` selects transformation from the resolved endpoint capability, separately from client alias mapping. M365 declares native inline system support: only leading system messages join the top-level system field; later messages, cache-control blocks and signed history remain in order. Other Claude App API endpoints retain the prior legacy transformation unless their model explicitly declares `mid_conversation_system`; ordinary API passthrough is unchanged. History ownership validation accepts only text in inline system messages and fingerprints conversation turns independently of instruction placement, as it already does for top-level system text. Canonical and legacy journals therefore retain current signed tool continuations across this upgrade; tool and signature checks remain enforced. This is a protocol capability, with no App version or model-name pattern.
1086
+
1087
+ M365 count-token capability probes use the existing bounded API count coordinator before privacy detection. One source/model/header scope shares its initial probe; real 404 responses suppress further count probes for 60 seconds. Generation is independent and no estimate is fabricated. Long-text rule detection caches hashed keys and span metadata within 1 MiB/2048 entries. Neural detection still uses its existing separate bounded cache. Last-waiter cancellation stops unused shared detection, while a non-interruptible native job retains its physical admission slot until reply/deadline. Numeric neural secret predictions require an adjacent secret label; deterministic secret rules remain effective.
1088
+
1089
+ Native components stage under `components/<release>` without replacing a running executable. Current checksums are verified on load; a verified ABI-compatible 1.3.6 component remains usable while a background upgrade is staged. No model mapping or request text is persisted.
1090
+
1091
+ ### CI and release evidence
1092
+
1093
+ Unit suites are automatically discovered on macOS and Windows with Node 22.15 and 24. A temporary HOME and an OS-variable allowlist keep developer credentials and configuration out of unit fixtures. Installer/network replay jobs retain their explicitly configured proxy and certificate policy. Browser theme cases run in four parallel palette groups without reducing the language/theme/viewport matrix. Independent checks continue after another check fails, and any failed check keeps the result failed. Native client versions are pinned; compatibility baseline coverage remains separate.
1094
+
1095
+ Publication requires a successful full CI run on the exact tagged commit, downloads its four runtime and four privacy artifacts, and stages one checksummed GitHub release. The same source tarball goes to npm. Downloaded draft bytes, public npm bytes, a fresh native dependency installation and every public GitHub asset are verified. The release receipt is generated from these checks; it does not checksum itself. Failed publication can resume only when an existing npm version has identical integrity.
package/docs/REFERENCE.md CHANGED
@@ -106,7 +106,7 @@ Catalog diagnostics distinguish local cached data from an online response and ex
106
106
  - **Local checks:** `doctor` is read-only by default. `--online` checks access; `--compat` sends minimal inference and consumes usage. `--fix` backs up owned configuration and performs bounded repairs. It does not enable optional features, change company policy or force-restart apps. Partial repairs exit 1.
107
107
  - **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
108
108
 
109
- Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input, with unknown/partial data indicated. It is not a request-based cache rate or a billing receipt.
109
+ Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input from records with valid counts for both. Unknown/invalid records remain in token totals but are excluded from both sides of the rate, with partial coverage indicated. It is not a request-based cache rate or a billing receipt.
110
110
 
111
111
  ## Settings and appearance
112
112
 
@@ -242,9 +242,38 @@ client after its owned configuration changes. All tests using sample capabilitie
242
242
  are isolated; they do not assign sample limits to a user's real models.
243
243
 
244
244
 
245
+ ## WebUI and CLI controls
246
+
247
+ Normal management belongs in the WebUI. CLI provides the same backend operations plus scripting and recovery:
248
+
249
+ | WebUI task | CLI | Effect |
250
+ | --- | --- | --- |
251
+ | Accounts, APIs and models | `source`, `app <id> models` | Shared connection graph, catalogs and credential storage |
252
+ | Client access and synchronization | `app <id> enable/disable/sync` | Preview/recheck ownership; no forced App exit |
253
+ | Delete a disabled, unbound API | `source <id> remove` | Shared impact revision; selected consumers block deletion |
254
+ | Input suggestions: enable/disable | `app codex prediction enable/disable` | Synchronize bridge preference and native Show predictions |
255
+ | Prediction setup/remove/repair/open | `app codex prediction setup/remove/repair/open` | Shared control; App closure may be required |
256
+ | Images: configure/remove/pause/resume | `app codex image setup/remove/pause/resume` | Shared image configuration transaction; keys never returned by WebUI |
257
+ | Install a stable update | `update apply --yes` | Same supervisor request; download, verify and idle service handoff |
258
+ | Standalone update/recovery | `update github/npm`, `doctor` | Available when service management is unavailable |
259
+ | Local/network checks, repair and report | `doctor`, `doctor network/report`, `doctor --fix` | Existing checks and configuration repair |
260
+ | Explicit model compatibility test | `doctor --compat` | Finite Codex Responses/stream/compaction requests; supports vendor IDs; local client credential stays on loopback; WebUI confirms quota use |
261
+ | Decoded request limit | `config limits --decoded <MiB>` | 128–512 MiB; saved for next start; launch environment has priority |
262
+ | Usage, requests, appearance and backups | `usage`, `requests`, `config` | Shared service data/preferences; browser appearance stays browser-local |
263
+
264
+ CLI-only interaction forms include JSON output, file input, key stdin and shell pipelines. Initial installation/startup, a failed service and headless hosts need an external launch/recovery entrypoint. These are not prerequisites for prediction or image configuration. Full runtime-cache purges, batch/file/key-stdin input, JSON formatting and one-installation remote-download exceptions remain advanced CLI operations. Company policy changes remain outside CCDX control.
265
+
266
+ ## Prediction controls
267
+
268
+ WebUI → Codex → Input suggestions is the complete enable/disable control. Setup and explicit enable write only `desktop.composer-predictions-enabled` in Codex TOML and its legacy persisted-atom equivalent; unrelated configuration/state remains intact. Writes require Codex to be closed. An open App keeps a pending display change; quit it and Continue setup, or normally launch CCDX again. The WebUI can open Codex after setup without a terminal command. No running App is forcibly closed.
269
+
270
+ Native configuration and startup environment checks use temporary work threads so OS/crypto work does not block the core service. Missing Apps are checked before trust/proxy setup. A normal cold startup attempts setup once when no CCDX prediction record exists, prediction access is allowed, and the App display preference is not saved off. Failed setup leaves core startup available and can be completed in WebUI. Saved off records and App off choices are preserved. Explicit enable intentionally overrides a prior App display-off setting. Repair keeps the selected on/off intent. Disable retains trust and routing; Remove setup owns trust/route cleanup and may defer cleanup until Codex closes. Visible predictions still require native App/thread eligibility and an actual returned suggestion.
271
+
272
+ Installed command launches use the existing supervisor and immutable workers. WebUI updates preserve accounts, models and request continuation through verified handoff; failure rolls back to the previous installation/runtime. Warm version handoff does not perform first-time setup or apply pending App display writes. Prediction intent/trust participates in the handoff fingerprint; port allocation and App stat bookkeeping are runtime data. Manual updates do not enable the overnight schedule, do not downgrade, and defer while requests or settings operations are active. Launches outside a writable matched installation display their limitation explicitly.
273
+
245
274
  ## Optional native predictions
246
275
 
247
- Native next-message predictions are **off by default** and use no MCP, Hook, skill,
276
+ New native next-message integrations **attempt setup by default when Codex is closed**. Existing CCDX or App off choices are retained. They use no MCP, Hook, skill,
248
277
  panel, renderer injection, or client-program modification. This compatibility
249
278
  feature uses the App's existing composer UI and the conversation's
250
279
  selected model through CCDX. Suggestions are not sent automatically. Native
@@ -429,9 +458,9 @@ No extra inference or bridge exists for users who leave the feature disabled.
429
458
  When enabled, prediction requests consume Copilot usage; the setting does not
430
459
  provide a separate prediction-model picker.
431
460
 
432
- `prediction off` immediately disables new local overlays. Quit/reopen Codex to
461
+ `app codex prediction remove` immediately disables new local overlays. Quit/reopen Codex to
433
462
  clear its cached predictions and temporary route. If the App is still running,
434
- trust removal is deferred; quit it and run `prediction off` again. Only the exact
463
+ trust removal is deferred; quit it and use Remove setup in WebUI again. Only the exact
435
464
  owned certificate record is removed, never the whole store. A CCDX-owned persistent
436
465
  proxy preference is restored first, preserving all unrelated preference values.
437
466
  User-replaced proxy preferences are not restored over. Failed activation
@@ -542,7 +571,7 @@ was recreated on the original address, not that gray text appeared.
542
571
 
543
572
  ## Optional image generation
544
573
 
545
- Image generation is disabled by default. Configure it interactively only when you want Codex App to receive the local CCDX image tool:
574
+ Image generation is disabled by default. Configure it in WebUI → Codex → Image generation: enter an HTTPS address and key, read models, choose one and save. An empty key retains the existing key only for the same origin. Discovery and saving use the existing missing-prompt protocol check; they do not generate an image. Removing setup deletes the saved image credential and only CCDX-owned configuration/guidance. Existing calls may finish when pausing. The same setup transaction is available interactively for advanced CLI use:
546
575
 
547
576
  ```bash
548
577
  ccdx app codex image setup
@@ -554,7 +583,7 @@ An empty key answer retains the saved key only when the normalized endpoint has
554
583
 
555
584
  The provider credential is stored in `~/.config/codex-copilot-dx/image-provider.json`, or under `XDG_CONFIG_HOME`, with mode `0600`. The API key is never written to `~/.codex/config.toml`; that file receives only a marked local MCP entry pointing to the running CCDX adapter with a 210-second tool timeout. Only after enabling, CCDX installs `ccdx-image` guidance under `~/.codex/skills`, with a self-contained Node helper. The concise `SKILL.md` keeps operation selection, safety, and final-image delivery rules; editing details and helper instructions live in references read only for those operations. Codex uses the MCP tool directly, including through deferred tool search; an already-open task without that tool can use the helper to call the same local service and display the saved image. Neither route requires Python, an OpenAI SDK, or copying credentials. Built-in skills and unrelated tools are not modified.
556
585
 
557
- The enable command verifies the local MCP handshake and generation-tool directory without generating an image. It reports provider configuration separately from local service readiness; it cannot assert that every running Codex task has refreshed its catalog. Codex normally detects changed skills; restart Codex App once if an open task has not refreshed them. Normal CCDX startup installs or updates this guidance only for an already-enabled provider, without repeating API setup. Without `enable-image`, it installs neither this skill nor the MCP registration. Unchanged guidance is not rewritten. The existing adapter can remain running because provider settings are loaded when the tool is invoked.
586
+ The enable command verifies the local MCP handshake and generation-tool directory without generating an image. It reports provider configuration separately from local service readiness; it cannot assert that every running Codex task has refreshed its catalog. Codex normally detects changed skills; restart Codex App once if an open task has not refreshed them. Normal CCDX startup installs or updates this guidance only for an already-enabled provider, without repeating API setup. Without image setup, it installs neither this skill nor the MCP registration. Unchanged guidance is not rewritten. The existing adapter can remain running because provider settings are loaded when the tool is invoked.
558
587
 
559
588
  For Qwen-style image responses, CCDX accepts canonical PNG, JPEG, or WebP `data:image/...;base64,` output within the existing 32 MiB image limit. Public HTTPS image URLs still use the same pinned-DNS download checks; HTTP, private-network targets, and URLs with embedded credentials remain rejected.
560
589
 
@@ -655,7 +684,13 @@ When upstream responses contain usage fields, CCDX records token counts, model n
655
684
  ccdx usage
656
685
  ```
657
686
 
658
- The summary covers the current log and its single rotated backup, not an unbounded lifetime history. It reports recorded responses and per-model input, cache-read, output, and total token metadata.
687
+ The summary covers the current log and its single rotated backup, not an unbounded lifetime history. It reports recorded responses and per-model input, cache-read, cache-write, output, and total token metadata.
688
+
689
+ M365 preserves system instructions at their original mid-conversation position. This avoids moving each new reminder ahead of the already cached history. Other Claude App API endpoints keep legacy behavior unless the model's `mid_conversation_system` capability is explicitly true. A false override selects legacy hoisting; Responses and Chat use their existing paths. This preserves instruction priority rather than converting system messages to user text.
690
+
691
+ Messages input is the sum of Anthropic uncached input, cache-read and cache-creation tokens. Cache creation is new input, not a cache hit; output tokens, including thinking output, are not added to the cache-hit denominator. M365 follows this same protocol accounting. Cache writes are shown separately when reported; missing write counts remain unknown. Stream usage updates replace cumulative counters, preserve earlier values when a later field is null or absent, and retain explicit zero. Each gateway request writes at most one usage row; forwarded usage is unchanged.
692
+
693
+ CLI/TUI, WebUI totals and daily analytics use the same paired evidence for cache rates. Aggregate JSON exposes `cache_hit_known_requests`, `cache_hit_unknown_requests`, `cache_hit_input_tokens` and `cache_hit_read_tokens` so the rate and its coverage can be checked. `~` marks incomplete coverage; a rate without a positive known input basis remains unknown. Historical logs are re-aggregated without rewriting their records, and unknown cache values are never filled with zero.
659
694
 
660
695
  Usage writes are asynchronous and batched under the existing cross-process rotation lock. Pending and in-flight records share a 4096-record / 4 MiB ceiling. If either ceiling is reached, new excess records are dropped with a warning and a status counter; inference does not wait or retry. Normal records and per-record rotation boundaries are unchanged. The bounded shutdown flush remains 1.5 seconds; disk failures and shutdown deadlines can prevent persistence, so usage is diagnostic rather than a billing ledger.
661
696
 
@@ -740,7 +775,7 @@ Usage queries share a bounded aggregate checkpoint only when file identities, fi
740
775
 
741
776
  ## Local masking
742
777
 
743
- Settings → Advanced → Local masking is off by default. Enabling it downloads the optional local component and AstrLink Guard 0.1.3, verifies their checksums and loads the model before activating protection. The npm package and ordinary installation do not contain model weights or require Go, Python or CUDA. The model and tokenizer total 38,958,270 bytes; the executable and optional macOS acceleration cache require additional space.
778
+ Settings → Advanced → Local masking is off by default. Enabling it downloads the optional local component and AstrLink Guard 0.1.3, verifies their checksums and loads the model before activating protection. The npm package and ordinary installation do not contain model weights or require Go, Python or CUDA. The model and tokenizer total 38,958,270 bytes; the executable and optional macOS acceleration cache require additional space. Component upgrades stage in a separate version directory. A verified compatible older component keeps serving during a failed download; the staged component takes over on the next engine load. Model weights with matching checksums are reused.
744
779
 
745
780
  Covered text includes conversation instructions, message text, tool results, tool argument values and tool descriptions on Responses, Chat and Messages routes. Protocol identifiers, tool schemas, authentication headers, images, signed thinking and encrypted reasoning retain their current behavior. Masking cannot retroactively remove data already sent to a service or control an agent's file/tool permissions. Personal-information detection is a separate opt-in; detection can miss values or mistake ordinary text.
746
781
 
@@ -752,8 +787,8 @@ Each request pins its masking choice, including compatibility retries. A check e
752
787
 
753
788
  Turning masking off affects subsequent requests. Existing protected replies keep their restoration mappings until they finish. The downloaded component can then be deleted separately. Settings reset backs up and resets masking choices while keeping accounts, model selections, client connections, images and prediction access. Older settings backups inherit masking off.
754
789
 
755
- Try locally sends sample text only to the local component. Request records show the number of replacements and elapsed local-check time, never the original values. Download failures keep protection off; configured but unavailable protection refuses covered requests. Downloads retain the selected npm's proxy, certificate and offline policy, with no automatic policy relaxation or alternate downloader.
790
+ Try locally sends sample text only to the local component. Request records show the number of replacements and elapsed local-check time, never the original values. Initial setup failures keep protection off; failed component upgrades retain verified compatible protection. Configured but unavailable protection refuses covered requests. Downloads retain the selected npm's proxy, certificate and offline policy, with no automatic policy relaxation or alternate downloader.
756
791
 
757
792
  Privacy failures have a separate local diagnostic origin. Response-restoration failures report that the response was stopped; request-check failures report that nothing was sent. When the latest Messages input explicitly contains failed tool results, request details show their count without retaining their content. HTTP success describes the model response, not proof that a client executed its tools successfully.
758
793
 
759
- The optional component is pinned to the v1.3.6 Release; later code-only updates can reuse it. Its source and license notices are in `native/privacy-guard` and `src/privacy-notices.txt`. AstrLink Guard model files use their publisher's Apache-2.0 license.
794
+ The optional component targets the v1.3.9 Release; later code-only updates can reuse it. A verified ABI-compatible v1.3.6 installation can continue serving while the new component is staged. Its source and license notices are in `native/privacy-guard` and `src/privacy-notices.txt`. AstrLink Guard model files use their publisher's Apache-2.0 license.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.7",
3
+ "version": "1.3.9",
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",
@@ -38,7 +38,7 @@
38
38
  "node": ">=22.15.0"
39
39
  },
40
40
  "scripts": {
41
- "test": "node --test",
41
+ "test": "node scripts/run-tests.mjs",
42
42
  "test:smoke": "node scripts/offline-smoke.mjs && node scripts/sse-idle-replay.mjs",
43
43
  "test:package": "node scripts/package-lifecycle-smoke.mjs",
44
44
  "test:nightly-package": "node scripts/nightly-package-replay.mjs",
@@ -47,7 +47,7 @@
47
47
  "bench:payload": "node scripts/benchmark.mjs --large-payload",
48
48
  "bench:check": "node scripts/benchmark.mjs --check",
49
49
  "pack:check": "npm pack --dry-run --json",
50
- "verify": "npm test && npm run test:smoke && npm run bench:check && npm run pack:check",
50
+ "verify": "node scripts/verify.mjs",
51
51
  "prepublishOnly": "npm run verify",
52
52
  "release:pack": "node scripts/release-artifacts.mjs",
53
53
  "release:runtime": "node scripts/runtime-package.mjs",
@@ -17,6 +17,8 @@ import { operationErrorDetails, transportErrorDetails } from "./operation-error.
17
17
  import { requestApplication } from "./request-application.mjs";
18
18
  import { observeContextSession } from "./context-metrics.mjs";
19
19
  import { catalogCapabilities } from "./model-capabilities.mjs";
20
+ import { applyMessagesSystemPolicy } from "./messages-system-policy.mjs";
21
+ import { createApiTokenCounter } from "./providers/api-token-count.mjs";
20
22
 
21
23
  function observeMessagesWindow(provider, model, capability, entry) {
22
24
  try {
@@ -39,19 +41,6 @@ function send(res, code, value) {
39
41
  const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
40
42
  const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
41
43
  || typeof block.text === "string" && block.text.length || typeof block.thinking === "string" && block.thinking.length));
42
- function desktopMessages(body) {
43
- const messages = [], instructions = [];
44
- const blocks = content => {
45
- if (typeof content === "string") return [{ type: "text", text: content }];
46
- if (Array.isArray(content) && content.every(block => block?.type === "text" && typeof block.text === "string")) return content;
47
- throw Object.assign(new Error("System instructions must contain text"), { code: "ccdx_messages_system_invalid", statusCode: 400 });
48
- };
49
- for (const message of body.messages) {
50
- if (message?.role === "system") instructions.push(...blocks(message.content));
51
- else messages.push(message);
52
- }
53
- return instructions.length ? { ...body, system: [...(body.system === undefined ? [] : blocks(body.system)), ...instructions], messages } : body;
54
- }
55
44
  function authenticated(headers, key) {
56
45
  const candidates = [headers["x-api-key"], typeof headers.authorization === "string" ? /^Bearer (.+)$/i.exec(headers.authorization)?.[1] : null];
57
46
  const expected = Buffer.from(key);
@@ -106,12 +95,13 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
106
95
  finish() { output = [];consume(decoder.decode());if (fragments.length) line(fragments.join(""), false);if (wire.length && !/\r?\n\r?\n$/.test(wire.join(""))) wire.push("\n\n");frame();return output; } };
107
96
  }
108
97
 
109
- export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
98
+ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
110
99
  resolveRequest, privacy, privacyClient = "claude", record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
111
100
  if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
112
101
  const config = loadRuntimeConfig(env), performance = sharedPerformance || createStreamPerformanceMetrics({ routeNames: ["messages"] });
113
102
  const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
114
103
  const stats = { total: 0, active: 0, completed: 0, incomplete: 0, failed: 0, cancelled: 0, last_request_at: null, last_model: null };
104
+ const countCoordinators = new WeakMap();
115
105
  async function dispatch(req, res) {
116
106
  let selectedProvider = provider, finishProvider = () => {};
117
107
  if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers.host === undefined || !isLoopbackHostHeader(req.headers.host)
@@ -162,7 +152,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
162
152
  body = { ...body, model: configuredModel };tracker?.setProvider(selectedProvider.id);
163
153
  const context = currentRequestContext();if (context) context.provider = selectedProvider.id;
164
154
  }
165
- if (desktopAliases) body = desktopMessages(body);
155
+ const inlineSystem = selectedCapability?.values?.mid_conversation_system;
156
+ body = applyMessagesSystemPolicy(body, inlineSystem === true ? "native" : inlineSystem === false ? "legacy" : selectedProvider.messagesSystemMode ?? messagesSystemMode);
166
157
  model = body.model;streamed = !countTokens && body.stream === true;
167
158
  if (!resolveRequest && (provider.configuredModels || desktopAliases)) {
168
159
  selectedModel = resolveClaudeModel(provider.models("claude"), model, { desktopAliases });
@@ -181,7 +172,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
181
172
  if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
182
173
  terminalOrigin = "transport";
183
174
  const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
184
- const upstream = await call(body, { headers: req.headers, countTokens, signal: abort.signal,
175
+ const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
185
176
  onCountObservation(value) {
186
177
  context.countObservation = { ...context.countObservation, ...value };
187
178
  if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
@@ -191,7 +182,16 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
191
182
  const timeout = streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs;
192
183
  if (countTokens) countDeadline ??= Date.now() + timeout;
193
184
  abort.setTimeout(countTokens ? Math.max(1, countDeadline - Date.now()) : timeout, "upstream_timeout");
194
- } });
185
+ } };
186
+ let upstream;
187
+ if (countTokens && selectedProvider.coordinateMessagesCounts) {
188
+ let counter = countCoordinators.get(selectedProvider);
189
+ if (!counter) {
190
+ counter = createApiTokenCounter({ request: (value, options) => options.perform(value, options) });
191
+ countCoordinators.set(selectedProvider, counter);
192
+ }
193
+ upstream = await counter.count(body, { ...callOptions, perform: call });
194
+ } else upstream = await call(body, callOptions);
195
195
  body = null;
196
196
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
197
197
  tracker?.upstreamHeaders(upstream.status);
@@ -234,7 +234,10 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
234
234
  || event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) conversation?.commit?.({ tool: event.content_block?.type === "tool_use" });
235
235
  if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
236
236
  if (event.type === "content_block_delta" && isMessagesOutputDelta(event.delta)) tracker?.firstOutput();
237
- if (event.type === "message_delta") { usage = { ...usage, ...event.usage };stopReason = event.delta?.stop_reason || stopReason; }
237
+ if (event.type === "message_delta") {
238
+ usage = { ...usage, ...Object.fromEntries(Object.entries(event.usage || {}).filter(([, value]) => value != null)) };
239
+ stopReason = event.delta?.stop_reason || stopReason;
240
+ }
238
241
  if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
239
242
  }, config.maxSseBufferBytes, clientModel);
240
243
  const reader = upstream.body.getReader();
@@ -126,8 +126,8 @@ export const MANAGED_COMMANDS = [
126
126
  outputFormat: flags.format,
127
127
  })
128
128
  ),
129
- ...["setup", "remove", "pause", "resume", "repair"].map(action =>
130
- command(`app codex prediction ${action}`, "Manage the optional Codex prediction integration", {}, () => ({
129
+ ...["enable", "disable", "setup", "remove", "pause", "resume", "repair", "open"].map(action =>
130
+ command(`app codex prediction ${action}`, ({ enable: "Enable suggestions and synchronize native display", disable: "Disable suggestions; synchronize display after App closure", setup: "Configure or renew App trust and suggestion display", remove: "Remove owned prediction trust and routing", pause: "Pause suggestions while retaining setup", resume: "Resume a configured prediction integration", repair: "Check and restore the selected prediction state", open: "Open Codex with the configured prediction route" })[action], {}, () => ({
131
131
  command: "prediction",
132
132
  action: { setup: "on", remove: "off", repair: "fix" }[action] || action,
133
133
  }))
@@ -188,6 +188,7 @@ export const MANAGED_COMMANDS = [
188
188
  "--provider": "value",
189
189
  }),
190
190
  command("update check", "Check a stable release without installing", read),
191
+ command("update apply", "Request the WebUI's verified idle service update", { "--yes": "flag" }, flags => ({ command: "update-managed", yes: !!flags.yes })),
191
192
  ];
192
193
 
193
194
  function pathMatch(pattern, values, partial = false) {