codex-copilot-dx 1.2.6 → 1.2.8

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 (42) hide show
  1. package/README.md +5 -5
  2. package/bin/cli.mjs +42 -2
  3. package/docs/ARCHITECTURE.md +13 -1
  4. package/docs/README.md +5 -0
  5. package/docs/REFERENCE.md +31 -7
  6. package/package.json +1 -1
  7. package/src/account-tools.mjs +121 -0
  8. package/src/adapter.mjs +2 -0
  9. package/src/auth-credentials.mjs +18 -8
  10. package/src/auth-status.mjs +21 -7
  11. package/src/auth.mjs +1 -0
  12. package/src/claude-gateway.mjs +2 -2
  13. package/src/cli-auth.mjs +38 -1
  14. package/src/cli-options.mjs +46 -13
  15. package/src/cli-tools.mjs +25 -0
  16. package/src/cli-web.mjs +37 -0
  17. package/src/codex-config-doctor.mjs +4 -0
  18. package/src/copilot-client.mjs +1 -0
  19. package/src/copilot-token-session.mjs +9 -0
  20. package/src/dashboard/activity.js +27 -0
  21. package/src/dashboard/console.js +2 -1
  22. package/src/dashboard/icons.js +24 -0
  23. package/src/dashboard/index.html +63 -17
  24. package/src/dashboard/language.js +90 -0
  25. package/src/dashboard/status.js +10 -0
  26. package/src/dashboard/theme.js +3 -2
  27. package/src/dashboard/tools.js +151 -0
  28. package/src/dashboard/ui.css +73 -0
  29. package/src/dashboard/ui.js +5 -1
  30. package/src/dashboard-api.mjs +5 -0
  31. package/src/dashboard-tools.mjs +43 -0
  32. package/src/dashboard.mjs +3 -0
  33. package/src/doctor.mjs +3 -2
  34. package/src/local-tools.mjs +53 -0
  35. package/src/native-prediction-environment.mjs +1 -1
  36. package/src/observability.mjs +7 -1
  37. package/src/optional-routes.mjs +9 -3
  38. package/src/provider-runtime.mjs +2 -2
  39. package/src/stream-performance.mjs +7 -0
  40. package/src/terminal-colors.mjs +8 -3
  41. package/src/terminal-console.mjs +5 -3
  42. package/src/user-settings.mjs +2 -2
package/README.md CHANGED
@@ -14,15 +14,15 @@ npm install -g codex-copilot-dx@latest
14
14
  ccdx
15
15
  ```
16
16
 
17
- No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.6/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.6/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).
17
+ No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.8/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.8/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).
18
18
 
19
19
  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.
20
20
 
21
- The [local control console](http://127.0.0.1:2026/) keeps indented Codex/Claude pages, Model sources, Usage, Requests and Settings. Codex owns source/model, Auto Review, images, input suggestions and conversation buffering; Model sources owns accounts, catalogs and Microsoft 365 access. Browsing a catalog never changes routing. Usage offers animated bars (default) or curves without extra requests; reduced motion keeps them static. Overview shows an approximate token cache hit rate, retaining partial/unknown states. The existing visual style and logo remain. System proxy exceptions accept shortened IPv4 networks; M365 network failures retain specific, redacted reasons.
21
+ The [local control console](http://127.0.0.1:2026/) keeps indented Codex/Claude pages, Model sources, Usage, Requests and Settings. Codex owns source/model, Auto Review, images, input suggestions and conversation buffering; Model sources owns accounts, catalogs and Microsoft 365 access. Browsing a catalog never changes routing. Usage offers animated bars (default) or curves without extra requests; reduced motion keeps them static. Overview and the live terminal table show the same approximate token cache hit rate, retaining partial/unknown states. Overview adds six small activity dots; only idle has a breathing halo. Failed or six-second-old activity reads show unknown. The indicator shares existing status polling, so very short requests can fall between snapshots. The existing visual style and logo remain. System proxy exceptions accept shortened IPv4 networks; M365 network failures retain specific, redacted reasons.
22
22
 
23
23
  Startup shows bounded checks, sources with discovered model lists and Claude Code/App configuration. Prediction normally uses one summary line; `ccdx prediction status` retains recovery and environment details. After Ready, an interactive terminal shows current source/Claude state and a line-framed table of this process's returned usage and inference counters. Notices and activity each have their own line; individual requests do not scroll. Input includes reused input tokens. `ccdx --verbose` (also `--show-request-id`, or debug logging) retains detail output; optional file logging remains independently controlled. Source and Claude summaries wrap on narrow terminals. Failed reads show previous-data status and the last successful update time. Non-TTY, CI, dumb, or terminals too small for the full region use plain output (at least 40 columns / 16 rows are required). `Ready` only means the core service is available; discovered catalogs and configured clients do not prove inference access.
24
24
 
25
- WebUI settings apply animation choices live, pause/resume configured image calls and prediction adaptation without removing credentials/trust, change the Codex source explicitly, and manage the conversation-buffer limit. Saved preference and effective state are separate; browser opening is labeled for the next start. Clearing the conversation buffer clears **all** buffered continuations. Busy cleanup is refused; retry after active requests finish. Saved Codex transcripts are retained. First-time image/prediction setup still uses the existing CLI; trust, client routing and cached client capabilities may require a normal App relaunch. Busy M365 requests must finish before disabling that provider. Settings also offers independent webpage/terminal colors: classic green (default) or Klein blue. Web colors stay in this browser; terminal colors persist locally. Failed saves are reported. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings).
25
+ WebUI settings apply animation choices live, pause/resume configured image calls and prediction adaptation without removing credentials/trust, change the Codex source explicitly, and manage the conversation-buffer limit. Saved preference and effective state are separate; browser opening is labeled for the next start. Clearing the conversation buffer clears **all** buffered continuations. Busy cleanup is refused; retry after active requests finish. Saved Codex transcripts are retained. First-time image/prediction setup still uses the existing CLI; trust, client routing and cached client capabilities may require a normal App relaunch. Busy M365 requests must finish before disabling that provider. Settings also offers independent webpage/terminal colors: classic green (default), Klein blue or Soft pink. Web colors stay in this browser; terminal colors persist locally. Failed saves are reported. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings).
26
26
 
27
27
  While visible and auto-refresh is on, the console reads the small status snapshot about every two seconds and source/settings evidence about every 16 seconds. Catalogs and retained usage are fetched on demand and at most once per 30-minute refresh interval while their view is open. Hidden pages stop scheduled reads. First output uses **ms**, estimated speed **token/s**, and each protocol has its own samples. HTTP traffic includes catalog and routing requests; it is not a conversation count.
28
28
  The **Requests by source** section and `ccdx status` separate request outcomes by source and protocol. Process-local returned usage also retains bounded source totals; missing usage remains partial. Configuration, sign-in, discovery and a completed reply remain separate evidence. CLI text stays English; WebUI stays bilingual. See the [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md) and [1.2.0 verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.0.md).
@@ -39,7 +39,7 @@ The **Requests by source** section and `ccdx status` separate request outcomes b
39
39
  | `ccdx doctor --json` | Redacted structured diagnostics; combines with `--fix` |
40
40
  | `ccdx doctor config` | Read-only configuration check |
41
41
  | `ccdx doctor --compat` | Online inference/continuation compatibility probes |
42
- | `ccdx auth status` | Saved account; add `--online` to verify access |
42
+ | `ccdx auth status` / `login` / `reauth` / `check` / `logout` | Inspect, verify or safely replace CCDX sign-in; other apps stay signed in |
43
43
  | `ccdx models` | Fresh upstream model list |
44
44
  | `ccdx usage` | Recorded tokens and upstream prompt-cache hit rate |
45
45
  | `ccdx usage --provider ID` | Filter current or historical source-specific usage |
@@ -110,7 +110,7 @@ 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
- 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 automatically; failed checks remain unknown. 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
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.
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).
package/bin/cli.mjs CHANGED
@@ -48,6 +48,15 @@ if (CLI.command === "version") {
48
48
  console.log(CLI_BANNER);
49
49
  process.exit(0);
50
50
  }
51
+ if (CLI.command === "web") {
52
+ try {
53
+ const { runWebCommand } = await import("../src/cli-web.mjs");
54
+ const address = parseAdapterAddressOptions(process.env);
55
+ const server = await runWebCommand({ host: address.adapterHost, port: address.adapterPort });
56
+ if (server) await server.ccdxWebClosed;
57
+ process.exit(0);
58
+ } catch (error) { console.error(status("err", error.message));process.exit(1); }
59
+ }
51
60
  if (CLI.command === "m365") {
52
61
  try {
53
62
  const { runM365Command } = await import("../src/cli-m365.mjs");
@@ -68,6 +77,12 @@ if (CLI.command === "animation") {
68
77
  }
69
78
  if (CLI.command === "image") {
70
79
  try {
80
+ if (["pause", "resume"].includes(CLI.action)) {
81
+ const { pauseServiceFeature } = await import("../src/cli-tools.mjs");
82
+ const address = parseAdapterAddressOptions(process.env);
83
+ console.log(await pauseServiceFeature({ feature: "image", action: CLI.action, host: address.adapterHost, port: address.adapterPort }));
84
+ process.exit(0);
85
+ }
71
86
  const address = CLI.action === "enable"
72
87
  ? parseAdapterAddressOptions(process.env)
73
88
  : { adapterPort: 2026, adapterHost: "127.0.0.1" };
@@ -99,6 +114,12 @@ if (CLI.command === "suggestion") {
99
114
  }
100
115
  if (CLI.command === "prediction") {
101
116
  try {
117
+ if (["pause", "resume"].includes(CLI.action)) {
118
+ const { pauseServiceFeature } = await import("../src/cli-tools.mjs");
119
+ const address = parseAdapterAddressOptions(process.env);
120
+ console.log(await pauseServiceFeature({ feature: "prediction", action: CLI.action, host: address.adapterHost, port: address.adapterPort }));
121
+ process.exit(0);
122
+ }
102
123
  const { runPredictionCommand } = await import("../src/native-prediction.mjs");
103
124
  const result = await runPredictionCommand({ action: CLI.action, repairRuntime: async () => {
104
125
  const { requestPredictionFix } = await import("../src/native-prediction-fix.mjs");
@@ -182,6 +203,13 @@ if (CLI.command === "auth") {
182
203
  online: CLI.online,
183
204
  reauth: CLI.reauth,
184
205
  expectedLogin: CLI.expectedLogin,
206
+ yes: CLI.yes,
207
+ onChanged: async () => {
208
+ const { dashboardToolRequest } = await import("../src/cli-tools.mjs");
209
+ const address = parseAdapterAddressOptions(process.env);
210
+ try { await dashboardToolRequest({ host: address.adapterHost, port: address.adapterPort, body: { action: "reload" } }); }
211
+ catch { console.log("Restart the CCDX service to apply the sign-in change."); }
212
+ },
185
213
  commandName: CLI_NAME,
186
214
  format: CLI.outputFormat || "auto",
187
215
  output: process.stdout,
@@ -250,6 +278,16 @@ if (CLI.command === "update") {
250
278
  process.exit(1);
251
279
  }
252
280
  }
281
+ if (CLI.command === "doctor" && CLI.tool) {
282
+ try {
283
+ const { createLocalTools } = await import("../src/local-tools.mjs");
284
+ const address = parseAdapterAddressOptions(process.env);
285
+ const tools = createLocalTools({ host: address.adapterHost, port: address.adapterPort });
286
+ if (CLI.tool === "network") console.log((await tools.network()).summary);
287
+ else { await tools.check();console.log(JSON.stringify(tools.report(), null, 2)); }
288
+ process.exit(0);
289
+ } catch (error) { console.error(status("err", error.message));process.exit(1); }
290
+ }
253
291
  if (CLI.command === "doctor" && CLI.configOnly) {
254
292
  let probe;
255
293
  try {
@@ -430,7 +468,7 @@ try {
430
468
  const m365Setup = runInBackground(() => providerRuntime.start());
431
469
  if (providerRuntime.selection().codex === "github") {
432
470
  try { await ensureAuth({ log: startupLogger("Sign-in") }); }
433
- catch (error) { if (!await m365Setup) throw error;console.warn(startupCheck("warn", "Sign-in", "GitHub authorization is unavailable; Microsoft 365 is independent. Check ccdx m365 status or switch")); }
471
+ catch (error) { console.warn(startupCheck("warn", "Sign-in", "Sign-in unavailable. Use the dashboard or ccdx auth login; saved credentials kept.")); }
434
472
  } else {
435
473
  await m365Setup;
436
474
  console.log(startupCheck("info", "Source", "Codex source: Microsoft 365"));
@@ -468,7 +506,9 @@ try {
468
506
  streamIdleTimeoutMs: RUNTIME.streamIdleTimeoutMs,
469
507
  terminalAnimationTheme,
470
508
  terminalActivity: terminalConsole,
471
- dashboardOptions: { serviceControl, applyAnimation: theme => terminalConsole.apply({ theme }) },
509
+ dashboardOptions: { serviceControl, host: ADAPTER_HOST, port: ADAPTER_PORT,
510
+ credentialsChanged: () => { defaultCopilotClient.invalidateCredentials();profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient }); },
511
+ applyAnimation: theme => terminalConsole.apply({ theme }) },
472
512
  nativePredictionPac: () => clientIntegration?.pacUrl() || null,
473
513
  fixPrediction: async () => (await clientIntegrations()).fix(),
474
514
  clientIntegrationSnapshot: () => clientIntegration?.snapshot() || null,
@@ -262,6 +262,12 @@ settlement for two seconds; no successful plaintext cache or transcript index ex
262
262
 
263
263
  ## Dashboard reads
264
264
 
265
+ `account-tools.mjs` is the shared explicit GitHub sign-in/check/sign-out boundary for CLI and WebUI. It reuses bounded device polling and `auth-status.mjs` access checks, isolates candidate credentials until verification, compares the original credential under the existing cross-process auth lock, and atomically commits to the CCDX-owned store. It does not own Microsoft SSO. Public snapshots project fixed stages/codes and omit token material. A cancelled or failed candidate is never persisted; the service keeps one sign-in controller and one connection-check flight, with bounded lifetimes/cooldowns. Explicit cache invalidation aborts a pending token refresh while preserving the runtime's account binding. The CLI notifies a compatible local service after changes; account changes require a restart.
266
+
267
+ `local-tools.mjs` reuses doctor and the existing config writer. It projects redacted local checks and a revision-bound config preview rather than wrapping arbitrary shell commands. The config writer validates the revision again inside its own lock, then preserves unmanaged settings and backs up changed originals. `dashboard-tools.mjs` owns the small strict action schema and bounded request-body transport; `optional-routes.mjs` creates these tools lazily per handler and disposes sign-in work when the listener closes. `dashboard/tools.js` owns the source-specific account view, user-triggered checks/preview and local progress polling; source selection does not change routing. `dashboard/icons.js` supplies fixed local circle SVGs and separate localized text nodes, preserving language changes without replacing the icons. No runtime dependency or per-stream instrumentation is added.
268
+
269
+ `cli-web.mjs` provides an unauthenticated management bootstrap. It opens an existing compatible listener or composes the management listener and provider controls without app writes/launch, prediction setup or automatic M365 start. It is deliberately separate from normal launcher side effects; normal app startup follows after stopping this management-only process. CLI feature pause/resume delegates to the existing preference gates; full removal/setup remains in the original integration commands.
270
+
265
271
  `provider-runtime.mjs` composes read-only Provider descriptors separately from
266
272
  source-selection actions. `provider-metadata.mjs` projects bounded model metadata
267
273
  without transport or credential dependencies. `dashboard-api.mjs` sanitizes public
@@ -418,6 +424,12 @@ management. CLI and UI share advertised effort filtering and preference writes.
418
424
 
419
425
  ## Independent appearance settings (1.2.2)
420
426
 
421
- Web color (`green` / `klein`) and dark/light mode are browser-local presentation state applied before CSS in `dashboard/theme.js`. CSS semantic roles keep errors/warnings separate from theme accents. Terminal color uses a distinct `terminal_color_theme` config field; animation continues to use `terminal_animation`. `terminal-colors.mjs` owns terminal color capability checks and escaping, while the existing layout runs on plain text first. The one-per-second coherent settings snapshot carries terminal color; animation frames introduce no additional settings reads. No inference, provider-routing or installer dependency is added.
427
+ Web color (`green` / `klein` / `pink`) and dark/light mode are browser-local presentation state applied before CSS in `dashboard/theme.js`. CSS semantic roles keep errors/warnings separate from theme accents. Terminal color uses a distinct `terminal_color_theme` config field; animation continues to use `terminal_animation`. `terminal-colors.mjs` owns terminal color capability checks and escaping, while the existing layout runs on plain text first. The one-per-second coherent settings snapshot carries terminal color; animation frames introduce no additional settings reads. No inference, provider-routing or installer dependency is added.
422
428
 
423
429
  The existing same-origin bounded settings action saves terminal color through the strict locked atomic writer, then applies it to the live console. Read or save failures retain existing files and controls revert to the last confirmed choice. Model-list check errors project only bounded public diagnostic fields; UI associates them with the selected source and its last successful snapshot. Existing generation checks, cancellation and deduplication prevent late results from replacing another source's data.
430
+
431
+ ## Activity presentation and Messages timing (1.2.8)
432
+
433
+ The existing status payload projects `model_activity.active` from the three fixed inference route counters plus actual image-generation activity, never total HTTP activity or image MCP calls. It adds no history store, provider request or listener. `dashboard/activity.js` consumes this metadata through the existing refresh path, expires stale evidence after six seconds and pauses offscreen animation. Idle, active and unknown remain distinct; CSS owns six theme-colored dots and the idle-only halo. Terminal Cache hit reads the existing raw runtime aggregate rather than deriving a ratio from rounded display numbers.
434
+
435
+ The Claude gateway still relays original native SSE bytes. `stream-performance.mjs` classifies only nonempty text, thinking and tool-argument deltas as first output; empty and signature-only deltas remain transport metadata. Sparse/interleaved blocks are not reordered or translated. Existing provider generations, locked atomic settings writes, cancellation and route ownership remain the composition boundaries.
package/docs/README.md CHANGED
@@ -17,6 +17,11 @@ effective Codex configuration or validate every field against the installed app.
17
17
 
18
18
  ## Historical release evidence
19
19
 
20
+ - [1.2.8: Soft pink, accurate activity and terminal cache reuse](RELEASE_1.2.8.md)
21
+ - [1.2.7: Account tools, checks and repairs, consistent status icons](RELEASE_1.2.7.md)
22
+ - [1.2.6: Abbreviated proxy networks and preserved diagnostics](RELEASE_1.2.6.md)
23
+ - [1.2.5: Animated usage views and approximate cache hit rate](RELEASE_1.2.5.md)
24
+
20
25
  - [1.2.4: Navigation clarity and bounded version discovery](RELEASE_1.2.4.md)
21
26
 
22
27
  These reports record a specific release and test environment. Their version,
package/docs/REFERENCE.md CHANGED
@@ -715,7 +715,7 @@ Run `ccdx <command> --help` for command-specific behavior and side-effect detail
715
715
  Startup uses aligned status/project/result columns and a left-aligned Ready footer
716
716
  with the Web UI URL and `ccdx help`. Ctrl+C is shown only for the foreground-owned
717
717
  service, never a short-lived command reusing another service. A static, favicon-style
718
- atom uses ANSI green and half-block characters only on interactive color terminals
718
+ atom uses the saved terminal color (green by default) and half-block characters only on interactive color terminals
719
719
  at least 72 columns wide; narrow terminals, `NO_COLOR`, `TERM=dumb` and redirected
720
720
  output keep a plain title. No new graphics/font/runtime dependency is installed.
721
721
  Credentials found are not labeled online-authorized, cached model lists are not
@@ -799,7 +799,7 @@ not a guarantee that every browser will reuse an existing tab.
799
799
 
800
800
  The default TTY display uses wrapping source/Claude summaries, a line-framed usage/inference table, and separate notice/activity rows, without an alternate screen or raw keyboard input. It shows usage returned since this process began; pending
801
801
  usage is excluded, missing usage stays partial, and this is not an invoice.
802
- Business requests drive activity; status/catalog polling does not. Existing nine
802
+ Business requests drive terminal activity; status/catalog polling does not. The live table fills its existing last usage row with Cache hit, using the same process-local cache_hit_rate and partial marker as Overview. Unknown/invalid rates display —; a known zero displays 0.0%. Existing nine
803
803
  animation styles retain their timing and cycle pauses; the default green retains its original palette. `--verbose`,
804
804
  `--show-request-id` or `CCDX_LOG_LEVEL=debug` restore detailed terminal output.
805
805
  Failed reads show previous-data status and the last successful update time, or that no data has been received. Narrow summaries wrap rather than hiding Claude App/Code state. Non-TTY/CI/dumb/too-small terminals use plain output; repeated identical notices
@@ -842,13 +842,17 @@ auto-refresh still permits manual refresh/settings retry. No history-log scan is
842
842
  performed at the status cadence. The atom moves on load/manual refresh only and
843
843
  respects reduced motion. Client attribution absent from older records stays unknown.
844
844
 
845
+ ### Overview activity
846
+
847
+ Overview reserves a fixed-height row below its status summary. Six 4px theme-colored dots appear and retract in order while the status snapshot reports active Responses, compaction, Claude Messages or actual image generation. Catalog reads, token counting, image MCP discovery and management calls are excluded; retries do not add another logical request. Active dots have no halo. Idle shows one small dot with a breathing halo. Invalid/missing status or a read older than six seconds shows Activity unknown, without a halo. This reuses the existing two-second status polling; short requests between snapshots may not be shown. No model probing, stream connection or extra polling is added. Hidden pages/views pause motion; reduced motion shows static corresponding states.
848
+
845
849
  ### Color themes
846
850
 
847
- Settings separates Web appearance and Terminal appearance. Each offers Classic green (default) and Klein blue. Green preserves the previous palette and terminal table's original text colors. Blue colors the terminal logo, full table and activity animation without changing glyphs, timing or metric definitions. Webpage color is independent of terminal color, and of the page header's dark/light switch.
851
+ Settings separates Web appearance and Terminal appearance. Each offers Classic green (default), Klein blue and Soft pink. Green preserves the previous palette and terminal table's original text colors. Blue and pink color the terminal logo, full table and activity animation without changing glyphs, timing or metric definitions. Webpage color is independent of terminal color, and of the page header's dark/light switch.
848
852
 
849
- Web choices use `ccdx.dashboard.palette` (`green` / `klein`) and the existing `ccdx.dashboard.theme` (`dark` / `light`) in browser local storage. They are applied before the stylesheet, including the atom favicon. Same-origin tabs receive storage updates; other browsers retain their own choices. If storage is blocked, the current tab still changes and explicitly reports that the choice was not saved. No service request is needed to change webpage colors.
853
+ Web choices use `ccdx.dashboard.palette` (`green` / `klein` / `pink`) and the existing `ccdx.dashboard.theme` (`dark` / `light`) in browser local storage. They are applied before the stylesheet, including the atom favicon. Same-origin tabs receive storage updates; other browsers retain their own choices. If storage is blocked, the current tab still changes and explicitly reports that the choice was not saved. No service request is needed to change webpage colors.
850
854
 
851
- Terminal color uses `terminal_color_theme: "klein"` in the normal CCDX user config. An absent value means `green`; choosing green removes the override. It does not change `terminal_animation` or any capability flag. The same bounded, strict settings read, file lock and atomic writer are reused. Invalid/unreadable existing config is not overwritten with defaults. A successful save applies to the supported live status table; the startup logo uses the saved choice next time. Previously printed terminal lines are not rewritten. Color codes are added after width calculation and clipping. Truecolor, 256-color and ANSI-blue fallbacks are supported; `NO_COLOR`, dumb terminals and redirected output preserve plain output. A terminal's own palette and background can affect the displayed blue.
855
+ Terminal color uses `terminal_color_theme: "klein"` or `"pink"` in the normal CCDX user config. An absent value means `green`; choosing green removes the override. It does not change `terminal_animation` or any capability flag. The same bounded, strict settings read, file lock and atomic writer are reused. Invalid/unreadable existing config is not overwritten with defaults. A successful save applies to the supported live status table; the startup logo uses the saved choice next time. Previously printed terminal lines are not rewritten. Color codes are added after width calculation and clipping. Truecolor, 256-color and ordinary ANSI fallbacks are supported; `NO_COLOR`, dumb terminals and redirected output preserve plain output. A terminal's own palette and background affect the displayed color. Pink uses a darker tone when COLORFGBG explicitly identifies a light background (7 or 15); otherwise its default tone is pale pink. CCDX does not query or change the terminal background.
852
856
 
853
857
  The terminal sample in Settings is labeled Preview and uses sample numbers, not current usage. Existing nine animation previews and their save operation remain available beneath the color choice. Red errors and amber warnings keep their meaning across webpage themes.
854
858
 
@@ -1008,7 +1012,7 @@ Unknown support prevents an explicitly requested exception from starting.
1008
1012
  For an older updater that still requires Git, install the Release tarball directly:
1009
1013
 
1010
1014
  ```sh
1011
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.6/codex-copilot-dx-1.2.6.tgz
1015
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.8/codex-copilot-dx-1.2.8.tgz
1012
1016
  # Windows PowerShell: use npm.cmd instead of npm.
1013
1017
  ```
1014
1018
 
@@ -1375,6 +1379,26 @@ account-change decision, not merely a Copilot denial, package update, or failed
1375
1379
  network probe. Existing same-account recovery and explicit source selection are
1376
1380
  unchanged.
1377
1381
 
1382
+ ## Account and repair tools
1383
+
1384
+ `ccdx auth` defaults to local status. `auth check` is the explicit online alias: it checks GitHub identity, Copilot authorization and a bounded model directory without inference. `auth status --online` remains available. A saved file is not proof of online access. Copilot denial and network failures do not recommend reauthentication merely because access failed.
1385
+
1386
+ `ccdx auth login` starts GitHub device authorization when no sign-in is saved. `ccdx auth reauth` / `ccdx reauth` explicitly replaces an existing sign-in. `auth login --reauth` is also accepted. The existing account binding is required by default; `--login ACCOUNT` explicitly requests a different account, which needs a service restart before it can become the running inference account. The device request has a 30-second deadline, GitHub's interval/slow-down responses govern polling, and the device lifetime is limited to 15 minutes. Candidate identity, entitlement and directory validation has a 15-second deadline. No candidate is saved before all checks pass. A final cross-process lock and comparison prevent overwriting a concurrently changed credential. Cancellation, denial, mismatch, expiration or validation failure preserves the prior sign-in. One WebUI flow runs per service, with a 30-second minimum between starts; connection checks coalesce and retain a same-credential result for 10 seconds.
1387
+
1388
+ New explicit-tool sign-ins use `~/.local/share/ccdx/github_token` and fingerprint-bound `.account.json` metadata, with private permissions and the existing atomic paired writer. When present, this owned store takes precedence over `~/.local/share/copilot-api/github_token`; existing startup/discovery compatibility remains supported. `auth logout` requires interactive confirmation or `--yes`, writes an empty owned credential, and does not delete or revoke other apps' legacy credentials. This intentionally blocks inference's legacy fallback. New login or normal startup can perform the existing explicit discovery/sign-in process again. CLI changes notify a compatible running local service; if notification is unavailable, the CLI asks for a service restart. In-flight model requests are not replayed or forcibly stopped. A token cache invalidation preserves its running account binding, so switching accounts still requires a restart.
1389
+
1390
+ Model sources uses one source selector for the account controls and catalog. Selecting a tab is browsing only. GitHub offers sign-in, independent connection checks and cancellation; sign-out is under More actions. The browser opens only the fixed GitHub device authorization URL after the user chooses Open GitHub. No token or password entry field is added. Microsoft 365 retains local account discovery/selection and source controls; its corporate SSO is not replaced with a GitHub-style login. Raw codes remain under details and last-good model lists retain their previous timestamp after failures.
1391
+
1392
+ `ccdx web` opens an existing compatible dashboard or starts a management-only local listener without sign-in, app configuration, app launch, prediction setup or automatic M365 startup. It does not claim normal startup integrations are active. Stop that management listener with Ctrl+C before running normal `ccdx` for application routing and optional integrations. Opening the dashboard does not initiate a GitHub Device Flow or model inference.
1393
+
1394
+ Checks & repairs performs the existing local doctor checks without adapter/client online checks. Configuration repair uses the existing owned-key writer: the preview lists scope and backup filename, a revision check rejects changes since preview, and the writer rechecks that revision under its existing config lock. It preserves unowned TOML and refuses invalid/unsafe configurations. A changed existing file is backed up as `config.toml.ccdx-doctor.bak`; an unchanged file or a missing original has no previous file to back up. The page does not expose arbitrary commands, forced restarts, certificate setup or an automatic repair loop. Compatibility probes remain the explicitly displayed `ccdx doctor --compat` command and consume usage.
1395
+
1396
+ `ccdx doctor network` and the page's Network settings read proxy/trust summaries without external HTTP requests or policy edits. Linux reports environment routing; Windows/macOS also inspect their supported system settings. `ccdx doctor report` prints the local report as JSON; Export report downloads the same bounded redacted projection. Home paths and account email addresses are replaced, and credentials, arbitrary check fields, chats and request bodies are omitted. Reports include only local checks, not a full network trace or proof of provider entitlement.
1397
+
1398
+ `ccdx image pause|resume` and `ccdx prediction pause|resume` use the existing service preference gates. They keep credentials, trust and routes and cannot provision a feature that has not been configured. Running image requests may finish. Offline changes apply on service startup; online prediction adaptation uses the running service's settings action. The existing full `disable-image` / `prediction off` cleanup semantics are unchanged. `ccdx source` is an alias for `ccdx m365 switch`, with the same model validation and explicit selection rules.
1399
+
1400
+ The protected `/_ccdx/ui/account` and `/_ccdx/ui/checks` APIs require loopback, a local Host and `X-CCDX-Dashboard: 1`. POST actions additionally require the matching Origin and JSON content type; bodies are capped at 4 KiB with a five-second body deadline, and unknown actions/fields are rejected. GET reads only local/process state. Sign-in polling GETs read in-memory operation state and do not trigger extra GitHub polling. Device-flow controllers are cancelled when the owning listener closes. SVG state icons are shipped locally and load no external icon library; an empty circle means unknown/not checked, a circle-minus means unavailable, and running uses circle-play rather than the success check.
1401
+
1378
1402
  ## HTTP error diagnostics
1379
1403
 
1380
1404
  `http_errors.recent` keeps its 20-record rolling view. Independent
@@ -1409,7 +1433,7 @@ unset the variable after the investigation. Records disappear on service exit.
1409
1433
  - CCDX binds to loopback by default. Non-loopback hosts are rejected unless `CCDX_ALLOW_LAN=1` is set explicitly.
1410
1434
  - Enabling LAN binding exposes a Copilot-backed API to other reachable machines. Provide your own host firewall and network isolation; do not expose the listener to an untrusted network.
1411
1435
  - Inference POSTs reject any browser `Origin` header before reading the body or contacting upstream, including simple `text/plain` requests. Native Codex/Node requests without Origin and deliberately enabled native LAN clients keep their existing access. This is not authentication or protection against untrusted local native programs.
1412
- - The GitHub OAuth credential is stored locally at `~/.local/share/copilot-api/github_token`. Short-lived Copilot service tokens remain in process memory and are refreshed as needed.
1436
+ - Explicit auth tools store GitHub OAuth credentials at `~/.local/share/ccdx/github_token`, with precedence over the compatible legacy `~/.local/share/copilot-api/github_token` store. Short-lived Copilot service tokens remain in process memory and are refreshed as needed. See Account and repair tools for safe replacement/sign-out behavior.
1413
1437
  - The optional image API credential is stored separately with mode `0600` only after `ccdx enable-image`; it is never placed in Codex configuration or diagnostic output.
1414
1438
  - Runtime status and usage records retain metadata by default; explicitly enabled HTTP error excerpts can contain private context. Diagnostic logging records status and error messages; it is not a general redaction layer for arbitrary error text. See Debug logging before sharing logs.
1415
1439
  - Request/response bodies, request-admission queues, retained history, image work, SSE buffers, log queues, retries, and shutdown have explicit limits. These component limits are not a single process-wide memory ceiling; completed image files are persistent user artifacts, not an automatically evicted cache.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.6",
3
+ "version": "1.2.8",
4
4
  "description": "Local Codex adapter and optional Microsoft 365 Claude gateway",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -0,0 +1,121 @@
1
+ import os from "node:os";
2
+ import { randomUUID } from "node:crypto";
3
+ import { readAuthProfileCredentials } from "./auth-profile.mjs";
4
+ import { fetchGithubIdentity, requestGithubDeviceCode, pollGithubDeviceFlow } from "./auth.mjs";
5
+ import { githubTokenLockPath, managedGithubTokenPath, writeToken } from "./auth-credentials.mjs";
6
+ import { githubIdentityMatchesExpected, githubTokenFingerprint } from "./github-identity.mjs";
7
+ import { inspectGithubAccess } from "./auth-status.mjs";
8
+ import { withFileLock } from "./lock.mjs";
9
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
10
+
11
+ const knownReasons = new Set(["unconfigured", "empty_token", "github_token_invalid", "github_access_denied", "github_user_failed",
12
+ "github_user_request_failed", "github_identity_missing", "copilot_access_denied", "copilot_token_failed", "copilot_token_missing",
13
+ "copilot_token_parse_failed", "copilot_token_request_failed", "validation_timeout", "validation_cancelled"]);
14
+ const safeLogin = value => /^[a-z\d_-]{1,39}$/i.test(value || "") && redactDiagnosticText(value) === value ? value : "";
15
+ const failure = (code, statusCode = 409) => Object.assign(new Error(code), { code, statusCode });
16
+ function publicAccess(value) {
17
+ if (!value) return null;
18
+ const httpStatus = value.httpStatus || Number(/HTTP (\d{3})/.exec(value.reason || "")?.[1]) || null;
19
+ return { checked: value.checked === true, ok: value.ok === true,
20
+ reason: value.ok ? "" : knownReasons.has(value.reason) ? value.reason : "connection_unavailable",
21
+ http_status: httpStatus, login: safeLogin(value.login), models: Number.isSafeInteger(value.models) ? value.models : null,
22
+ stages: Object.fromEntries(["identity", "access", "models"].map(key => [key,
23
+ ["passed", "invalid", "unavailable"].includes(value.stages?.[key]) ? value.stages[key] : "not_checked"])) };
24
+ }
25
+
26
+ // One bounded sign-in and one connection check per service. Snapshots contain no credentials.
27
+ export function createAccountTools({ home = os.homedir(), env = process.env, fetchImpl = fetch,
28
+ onChanged = () => {}, now = Date.now, poll = pollGithubDeviceFlow, inspect = inspectGithubAccess } = {}) {
29
+ let operation = null, online = null, checkedAt = null, checkedFingerprint = "", checkFlight = null;
30
+ const credentials = () => readAuthProfileCredentials("codex", { home });
31
+ function snapshot() {
32
+ const local = credentials();
33
+ return { source: "account_tools", configured: local.configured, saved: local.valid,
34
+ login: safeLogin(local.identity?.login), store: local.paths.tokenPath === managedGithubTokenPath(home) ? "ccdx" : "legacy",
35
+ online: checkedFingerprint === githubTokenFingerprint(local.token) ? online : null,
36
+ checked_at: checkedFingerprint === githubTokenFingerprint(local.token) ? checkedAt : null,
37
+ operation: operation ? { id: operation.id, state: operation.state, reason: operation.reason || null,
38
+ ...(operation.state === "authorizing" ? { user_code: operation.userCode, verification_uri: operation.uri,
39
+ expires_at: operation.expiresAt } : {}) } : null };
40
+ }
41
+ async function check() {
42
+ if (checkFlight) return checkFlight;
43
+ const local = credentials(), fingerprint = githubTokenFingerprint(local.token);
44
+ if (checkedFingerprint === fingerprint && checkedAt && now() - Date.parse(checkedAt) < 10000) return snapshot();
45
+ checkFlight = (async () => {
46
+ const result = await inspect(local, { fetchImpl, timeoutMs: 15000 });
47
+ if (githubTokenFingerprint(credentials().token) === fingerprint) {
48
+ online = publicAccess(result);checkedAt = new Date(now()).toISOString();checkedFingerprint = fingerprint;
49
+ }
50
+ return snapshot();
51
+ })().finally(() => { checkFlight = null; });
52
+ return checkFlight;
53
+ }
54
+ async function start({ reauth = false, expectedLogin = "" } = {}) {
55
+ if (operation && ["starting", "authorizing", "verifying"].includes(operation.state)) throw failure("auth_busy");
56
+ if (operation && now() - operation.startedAt < 30000) throw failure("auth_retry_later", 429);
57
+ if (expectedLogin && !safeLogin(expectedLogin)) throw failure("auth_invalid_account", 400);
58
+ const before = credentials();
59
+ if (before.valid && !reauth) return snapshot();
60
+ const expected = expectedLogin ? { login: expectedLogin } : env.CCDX_GITHUB_LOGIN ? { login: env.CCDX_GITHUB_LOGIN } : before.identity;
61
+ const current = { id: randomUUID(), state: "starting", startedAt: now(), controller: new AbortController(), task: null };
62
+ operation = current;
63
+ try {
64
+ const result = await requestGithubDeviceCode({ fetchImpl, signal: current.controller.signal });
65
+ const data = result.data;
66
+ if (!result.response.ok || result.jsonError || !data || typeof data.device_code !== "string" || !data.device_code
67
+ || !/^[a-z\d-]{4,32}$/i.test(data.user_code || "") || data.verification_uri !== "https://github.com/login/device"
68
+ || !Number.isFinite(Number(data.expires_in)) || Number(data.expires_in) <= 0 || Number(data.expires_in) > 900) throw failure("auth_start_failed");
69
+ Object.assign(current, { state: "authorizing", userCode: data.user_code, uri: data.verification_uri,
70
+ expiresAt: new Date(now() + Number(data.expires_in) * 1000).toISOString() });
71
+ current.task = (async () => {
72
+ try {
73
+ const result = await poll({ deviceCode: data.device_code, interval: data.interval, expiresIn: data.expires_in,
74
+ fetchImpl, signal: current.controller.signal });
75
+ if (current.controller.signal.aborted) throw failure("auth_cancelled");
76
+ if (result.state !== "done") throw failure(result.state === "expired" ? "auth_expired" : "auth_denied");
77
+ current.state = "verifying";
78
+ const access = await inspect({ valid: true, token: result.token }, { fetchImpl, signal: current.controller.signal, timeoutMs: 15000 });
79
+ if (!access.ok) throw failure(access.reason === "copilot_access_denied" ? "copilot_access_denied" : "auth_verification_failed");
80
+ // Older identity metadata may be absent. Do not guess a different account's identity.
81
+ const identity = access.id ? access : await fetchGithubIdentity(result.token, { fetchImpl, signal: current.controller.signal });
82
+ if (!identity.id || !identity.login || !githubIdentityMatchesExpected(identity, expected)) throw failure("auth_account_mismatch");
83
+ await withFileLock(githubTokenLockPath(home), async () => {
84
+ const latest = credentials();
85
+ if (current.controller.signal.aborted) throw failure("auth_cancelled");
86
+ if (latest.token !== before.token || latest.paths.tokenPath !== before.paths.tokenPath) throw failure("auth_signin_changed");
87
+ writeToken(result.token, home, identity, { managed: true });
88
+ }, { timeoutMs: 1000 });
89
+ checkedFingerprint = githubTokenFingerprint(result.token);online = publicAccess(access);checkedAt = new Date(now()).toISOString();
90
+ current.state = "complete";
91
+ try { await onChanged(); } catch { current.reason = "auth_restart_required"; }
92
+ } catch (error) {
93
+ current.state = current.controller.signal.aborted ? "cancelled" : "failed";
94
+ current.reason = current.controller.signal.aborted ? "auth_cancelled" : /^auth_[a-z_]+$/.test(error.code || "") || error.code === "copilot_access_denied" ? error.code : "auth_verification_failed";
95
+ }
96
+ })();
97
+ return snapshot();
98
+ } catch (error) {
99
+ current.state = current.controller.signal.aborted ? "cancelled" : "failed";
100
+ current.reason = current.controller.signal.aborted ? "auth_cancelled" : "auth_start_failed";
101
+ throw failure(current.reason);
102
+ }
103
+ }
104
+ async function cancel(id) {
105
+ if (!operation || operation.id !== id) throw failure("auth_operation_changed");
106
+ if (["starting", "authorizing", "verifying"].includes(operation.state)) {
107
+ operation.controller.abort();await operation.task;
108
+ operation.state = "cancelled";operation.reason = "auth_cancelled";
109
+ }
110
+ return snapshot();
111
+ }
112
+ async function logout({ confirmed = false } = {}) {
113
+ if (confirmed !== true) throw failure("auth_confirmation_required", 400);
114
+ if (operation && ["starting", "authorizing", "verifying"].includes(operation.state)) throw failure("auth_busy");
115
+ await withFileLock(githubTokenLockPath(home), async () => { credentials();writeToken("", home, null, { managed: true }); }, { timeoutMs: 1000 });
116
+ online = null;checkedAt = null;checkedFingerprint = "";operation = null;await onChanged();
117
+ return snapshot();
118
+ }
119
+ return { snapshot, check, start, cancel, logout, wait: async () => { await operation?.task;return snapshot(); },
120
+ async reload() { await onChanged();return snapshot(); }, dispose() { operation?.controller.abort(); } };
121
+ }
package/src/adapter.mjs CHANGED
@@ -168,6 +168,7 @@ export function createAdapterHandler(options = {}) {
168
168
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
169
169
  const httpErrors = createHttpFailureDiagnostics();
170
170
  const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
171
+ credentialsChanged: options.dashboardOptions?.credentialsChanged || (() => codexClient.invalidateCredentials?.()),
171
172
  ...(options.providerRuntime ? { providerCatalogFn: input => options.providerRuntime.dashboardCatalog(input),
172
173
  providerStateFn: () => options.providerRuntime.dashboardProviders(),
173
174
  providerAccountsFn: () => options.providerRuntime.action({ action: "accounts" }) } : {}) } });
@@ -459,6 +460,7 @@ export function createAdapterHandler(options = {}) {
459
460
  }
460
461
  };
461
462
  handler.snapshot = statusSnapshot;
463
+ handler.cleanup = () => optionalRoutes.dispose();
462
464
  return handler;
463
465
  }
464
466
 
@@ -10,12 +10,23 @@ const DISABLE_TOKEN_DISCOVERY_VALUES = new Set(["1", "true", "yes"]);
10
10
  const MAX_AUTH_JSON_BYTES = 1024 * 1024;
11
11
  const pathKey = value => process.platform === "win32" ? path.resolve(value).toLowerCase() : path.resolve(value);
12
12
 
13
- export function githubTokenPath(home = os.homedir()) {
13
+ export function managedGithubTokenPath(home = os.homedir()) {
14
+ return path.join(home, ".local", "share", "ccdx", "github_token");
15
+ }
16
+
17
+ export function legacyGithubTokenPath(home = os.homedir()) {
14
18
  return path.join(home, ".local", "share", "copilot-api", "github_token");
15
19
  }
16
20
 
21
+ export function githubTokenPath(home = os.homedir()) {
22
+ const managed = managedGithubTokenPath(home);
23
+ try { fs.lstatSync(managed);return managed; }
24
+ catch (error) { if (error.code !== "ENOENT") return managed; }
25
+ return legacyGithubTokenPath(home);
26
+ }
27
+
17
28
  export function githubTokenLockPath(home = os.homedir()) {
18
- return `${githubTokenPath(home)}.lock`;
29
+ return `${legacyGithubTokenPath(home)}.lock`;
19
30
  }
20
31
 
21
32
  export function githubTokenMetadataPath(home = os.homedir()) {
@@ -23,11 +34,9 @@ export function githubTokenMetadataPath(home = os.homedir()) {
23
34
  }
24
35
 
25
36
  export function githubReauthMessage(reason, home = os.homedir()) {
26
- const tokenPath = githubTokenPath(home);
27
37
  return `${reason}
28
- Delete the saved GitHub token, then run ccdx again to log in:
29
- rm '${tokenPath}'
30
- ccdx`;
38
+ Run ccdx auth reauth to sign in again.
39
+ The saved sign-in is kept until verification succeeds.`;
31
40
  }
32
41
 
33
42
  function expandHome(filePath, home = os.homedir()) {
@@ -243,15 +252,16 @@ export function writeToken(token, home = os.homedir(), identity = null, {
243
252
  now = () => new Date(),
244
253
  writeFile = atomicWriteFileSync,
245
254
  unlinkFile = fs.unlinkSync,
255
+ managed = false,
246
256
  } = {}) {
247
- const GITHUB_TOKEN_PATH = githubTokenPath(home);
257
+ const GITHUB_TOKEN_PATH = managed ? managedGithubTokenPath(home) : githubTokenPath(home);
248
258
  const directory = path.dirname(GITHUB_TOKEN_PATH);
249
259
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
250
260
  fs.chmodSync(directory, 0o700);
251
261
  atomicWriteFilePairSync(
252
262
  GITHUB_TOKEN_PATH,
253
263
  token,
254
- githubTokenMetadataPath(home),
264
+ `${GITHUB_TOKEN_PATH}.account.json`,
255
265
  githubTokenMetadataData(identity, token, now),
256
266
  { mode: 0o600, writeFile, unlinkFile },
257
267
  );
@@ -4,6 +4,7 @@ import { AUTH_PROFILE_CODEX, readAuthProfileCredentials } from "./auth-profile.m
4
4
  import { buildHeaders, FALLBACK_VSCODE_VERSION, parseApiBase } from "./copilot.mjs";
5
5
  import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "./http-transport.mjs";
6
6
  import { profileRouting } from "./profile-routing.mjs";
7
+ import { awaitWithSignal } from "./auth-device-flow.mjs";
7
8
 
8
9
  const DEFAULT_COPILOT_CATALOG_TIMEOUT_MS = 30 * 1000;
9
10
 
@@ -47,16 +48,16 @@ async function fetchCopilotCatalog(tokenData, {
47
48
  initiator: "user",
48
49
  vision: false,
49
50
  });
50
- const response = await fetchImpl(`${apiBase}/models`, {
51
+ const response = await awaitWithSignal(() => fetchImpl(`${apiBase}/models`, {
51
52
  headers,
52
53
  redirect: "error",
53
54
  signal: controller.signal,
54
- });
55
- const modelText = await readBoundedResponseText(response, {
55
+ }), controller.signal);
56
+ const modelText = await awaitWithSignal(() => readBoundedResponseText(response, {
56
57
  maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES,
57
58
  label: "Copilot model catalog",
58
59
  signal: controller.signal,
59
- });
60
+ }), controller.signal);
60
61
  if (!response.ok) {
61
62
  const detail = responseDetail(modelText);
62
63
  throw new Error(`Copilot model catalog failed with HTTP ${response.status}${detail ? `: ${detail}` : ""}`);
@@ -87,7 +88,7 @@ function publicProfile(credentials) {
87
88
  reason: credentials.reason,
88
89
  login: credentials.identity?.login || "",
89
90
  id: credentials.identity?.id || "",
90
- source: "legacy",
91
+ source: credentials.paths?.tokenPath.replace(/\\/g, "/").split("/").at(-2) === "ccdx" ? "ccdx" : "legacy",
91
92
  };
92
93
  }
93
94
 
@@ -114,13 +115,17 @@ export function authStatus({ home = os.homedir() } = {}) {
114
115
  };
115
116
  }
116
117
 
117
- async function inspectProfileOnline(credentials, { fetchImpl, timeoutMs } = {}) {
118
+ export async function inspectGithubAccess(credentials, { fetchImpl = fetch, timeoutMs = 10000, signal } = {}) {
118
119
  if (!credentials.valid) {
119
120
  return { checked: false, ok: false, reason: credentials.reason || "unconfigured" };
120
121
  }
121
122
 
122
123
  const controller = new AbortController();
123
124
  const timer = setTimeout(() => controller.abort(new Error(`timed out after ${timeoutMs}ms`)), timeoutMs);
125
+ const cancel = () => controller.abort(signal.reason);
126
+ signal?.addEventListener("abort", cancel, { once: true });
127
+ if (signal?.aborted) cancel();
128
+ const stages = { identity: "not_checked", access: "not_checked", models: "not_checked" };
124
129
  try {
125
130
  const validation = await validateGithubToken(credentials.token, {
126
131
  fetchImpl,
@@ -128,13 +133,18 @@ async function inspectProfileOnline(credentials, { fetchImpl, timeoutMs } = {})
128
133
  });
129
134
  if (controller.signal.aborted) throw abortError(controller.signal);
130
135
  if (!validation.ok) {
136
+ stages.identity = validation.login ? "passed" : validation.reason === "github_token_invalid" ? "invalid" : "unavailable";
137
+ if (validation.login) stages.access = "unavailable";
131
138
  return {
132
139
  checked: true,
133
140
  ok: false,
134
141
  reason: validation.reason,
135
142
  httpStatus: validation.status || null,
143
+ stages,
136
144
  };
137
145
  }
146
+ stages.identity = "passed";stages.access = "passed";
147
+ stages.models = "unavailable";
138
148
  const { catalog, apiBase } = await fetchCopilotCatalog(validation.copilotTokenData, {
139
149
  fetchImpl,
140
150
  signal: controller.signal,
@@ -144,7 +154,9 @@ async function inspectProfileOnline(credentials, { fetchImpl, timeoutMs } = {})
144
154
  return {
145
155
  checked: true,
146
156
  ok: true,
157
+ stages: { ...stages, models: "passed" },
147
158
  login: validation.login || credentials.identity?.login || "",
159
+ id: validation.id || "",
148
160
  models: catalogModels(catalog).length,
149
161
  upstreamHost,
150
162
  };
@@ -153,9 +165,11 @@ async function inspectProfileOnline(credentials, { fetchImpl, timeoutMs } = {})
153
165
  checked: true,
154
166
  ok: false,
155
167
  reason: controller.signal.aborted ? `timed out after ${timeoutMs}ms` : error.message,
168
+ stages,
156
169
  };
157
170
  } finally {
158
171
  clearTimeout(timer);
172
+ signal?.removeEventListener("abort", cancel);
159
173
  }
160
174
  }
161
175
 
@@ -165,7 +179,7 @@ export async function authStatusOnline({
165
179
  timeoutMs = 10000,
166
180
  } = {}) {
167
181
  const local = authStatus({ home });
168
- const online = await inspectProfileOnline(readStatusCredentials(home), { fetchImpl, timeoutMs });
182
+ const online = await inspectGithubAccess(readStatusCredentials(home), { fetchImpl, timeoutMs });
169
183
  return {
170
184
  ...local,
171
185
  profiles: {
package/src/auth.mjs CHANGED
@@ -10,6 +10,7 @@ import { githubTokenPath, githubTokenLockPath, readGithubTokenMetadata, readSave
10
10
  import { requestGithubDeviceCode, pollGithubDeviceFlow, awaitWithSignal, abortError, cancelResponseBody,
11
11
  sleep, DEFAULT_DEVICE_CODE_TIMEOUT_MS } from "./auth-device-flow.mjs";
12
12
  export { githubTokenPath, githubTokenLockPath, githubTokenMetadataPath, githubReauthMessage,
13
+ managedGithubTokenPath, legacyGithubTokenPath,
13
14
  githubTokenSources, sourceDescription, extractGithubTokenFromAuthJson, readGithubTokenSource,
14
15
  readGithubTokenMetadata, writeGithubTokenMetadata, writeToken } from "./auth-credentials.mjs";
15
16
  export { interpretPoll, requestGithubDeviceCode, pollGithubDeviceFlow } from "./auth-device-flow.mjs";