codex-copilot-dx 1.2.5 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,11 +14,11 @@ 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.5/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.5/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.7/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.7/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.
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.
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
 
@@ -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,
@@ -48,6 +48,11 @@ to M365. No GitHub token, image credential or browser Cookie is reused. Windows
48
48
  use a separate OS WinHTTP worker for M365 company routing; macOS preserves static
49
49
  system/environment routing and reports unsupported dynamic PAC. Native runtime
50
50
  absence and policy refusal do not disable GitHub.
51
+
52
+ `network-route.mjs` canonicalizes abbreviated IPv4 CIDRs only while adapting system `ExceptionsList` input, before merging it with the unchanged strict `NO_PROXY` input. `network-bypass.mjs` remains the shared strict Node/PAC matcher; it performs no DNS lookup. This fixes no-proxy and static-proxy macOS configurations without dropping exception rules or weakening unsupported dynamic-PAC protection.
53
+
54
+ `providers/m365-network-diagnostic.mjs` is a small pure projection of fixed proxy failure codes, source and stage, shared by transport, provider state, protected dashboard routes and CLI. Raw error chains/settings never cross that boundary. M365 retains existing outer error categories; the source runtime forwards the bounded diagnostic, and existing bilingual renderers expose a readable explanation with technical details. Startup uses the same fixed English explanation. Refresh failures retain last-good catalogs and never change the selected provider; successful transport creation clears the setup diagnostic. No new service, storage, dependency, route fallback or provider retry is introduced.
55
+
51
56
  `claude-client-lifecycle.mjs` owns configuration reconciliation and restore state, independently from source auth/catalog code. It checks lifecycle/profile validity after asynchronous policy inspection and preserves the existing field-ownership writer.
52
57
  Claude handler/configuration readiness is also separate from M365 provider
53
58
  readiness. A Claude setup failure or a GPT-only catalog cannot block the explicitly
@@ -257,6 +262,12 @@ settlement for two seconds; no successful plaintext cache or transcript index ex
257
262
 
258
263
  ## Dashboard reads
259
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
+
260
271
  `provider-runtime.mjs` composes read-only Provider descriptors separately from
261
272
  source-selection actions. `provider-metadata.mjs` projects bounded model metadata
262
273
  without transport or credential dependencies. `dashboard-api.mjs` sanitizes public
package/docs/README.md CHANGED
@@ -17,6 +17,10 @@ effective Codex configuration or validate every field against the installed app.
17
17
 
18
18
  ## Historical release evidence
19
19
 
20
+ - [1.2.7: Account tools, checks and repairs, consistent status icons](RELEASE_1.2.7.md)
21
+ - [1.2.6: Abbreviated proxy networks and preserved diagnostics](RELEASE_1.2.6.md)
22
+ - [1.2.5: Animated usage views and approximate cache hit rate](RELEASE_1.2.5.md)
23
+
20
24
  - [1.2.4: Navigation clarity and bounded version discovery](RELEASE_1.2.4.md)
21
25
 
22
26
  These reports record a specific release and test environment. Their version,
package/docs/REFERENCE.md CHANGED
@@ -66,6 +66,10 @@ origin. Explicit proxy/trust settings are preserved. Windows delegates system
66
66
  PAC/WPAD and integrated authentication to its own isolated WinHTTP worker;
67
67
  unsupported macOS dynamic PAC is reported rather than bypassed.
68
68
 
69
+ System `ExceptionsList` entries such as `169.254/16`, `10/8`, `172.16/12` and `192.168.1/24` are normalized to full four-octet IPv4 CIDRs before the existing shared Node/PAC matcher. Missing octets become zero only when the supplied octets cover the prefix; invalid octets, ambiguous leading zeros, out-of-range or underspecified prefixes remain errors. User-supplied `NO_PROXY` retains its existing strict syntax. No system setting, proxy bypass policy, DNS lookup or network probe is added. The shared system-input correction also applies to prediction environment parsing.
70
+
71
+ M365 proxy-setup failures retain their existing outer category (`m365_proxy_settings_unsupported`, `m365_proxy_discovery_failed`, or the existing environment-failure category `m365_network_error`) and add an optional `network_diagnostic`: fixed `source` (`system`/`environment`), `stage` (`proxy_discovery`/`proxy_config`) and `cause_code`. Causes distinguish discovery, dynamic PAC/WPAD, invalid bypass rules, invalid static settings and invalid/unsupported proxy addresses; unknown causes stay generic. CLI/startup explain the specific cause without suggesting a new sign-in for a known network setup failure. WebUI shows the bilingual reason in source status (codes in its tooltip) and the existing model-check details, with source/stage/cause fields. Proxy URLs, credentials, raw settings and raw nested errors are never projected. These local setup failures happen before the model HTTP request; a local 502/503 does not establish a model-service denial. Successful transport setup or a later unrelated refresh failure clears the previous setup diagnostic. Failed catalog reads still remain failures and preserve last-good data; they are not successful empty catalogs. No automatic route substitution or extra polling is added.
72
+
69
73
  The M365 profile under `~/.local/share/codex-copilot-dx/profiles/m365/` contains
70
74
  `settings.json`, nonsecret `account.json`, account-bound `models.json`, a private
71
75
  local `gateway.json` key, and `client-config.json` field ownership. JSON reads are
@@ -1004,7 +1008,7 @@ Unknown support prevents an explicitly requested exception from starting.
1004
1008
  For an older updater that still requires Git, install the Release tarball directly:
1005
1009
 
1006
1010
  ```sh
1007
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.5/codex-copilot-dx-1.2.5.tgz
1011
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.7/codex-copilot-dx-1.2.7.tgz
1008
1012
  # Windows PowerShell: use npm.cmd instead of npm.
1009
1013
  ```
1010
1014
 
@@ -1371,6 +1375,26 @@ account-change decision, not merely a Copilot denial, package update, or failed
1371
1375
  network probe. Existing same-account recovery and explicit source selection are
1372
1376
  unchanged.
1373
1377
 
1378
+ ## Account and repair tools
1379
+
1380
+ `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.
1381
+
1382
+ `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.
1383
+
1384
+ 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.
1385
+
1386
+ 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.
1387
+
1388
+ `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.
1389
+
1390
+ 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.
1391
+
1392
+ `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.
1393
+
1394
+ `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.
1395
+
1396
+ 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.
1397
+
1374
1398
  ## HTTP error diagnostics
1375
1399
 
1376
1400
  `http_errors.recent` keeps its 20-record rolling view. Independent
@@ -1405,7 +1429,7 @@ unset the variable after the investigation. Records disappear on service exit.
1405
1429
  - CCDX binds to loopback by default. Non-loopback hosts are rejected unless `CCDX_ALLOW_LAN=1` is set explicitly.
1406
1430
  - 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.
1407
1431
  - 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.
1408
- - 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.
1432
+ - 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.
1409
1433
  - 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.
1410
1434
  - 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.
1411
1435
  - 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.5",
3
+ "version": "1.2.7",
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";
package/src/cli-auth.mjs CHANGED
@@ -1,5 +1,8 @@
1
1
  import { authStatus, authStatusOnline } from "./auth-status.mjs";
2
2
  import { status } from "./status.mjs";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { createAccountTools } from "./account-tools.mjs";
5
+ import { terminalCell as safeCell } from "./terminal-text.mjs";
3
6
  import {
4
7
  cliOutputFormat,
5
8
  cliOutputWidth,
@@ -29,7 +32,7 @@ function onlineStatusLine(profile) {
29
32
  function authStatusPlainLines(snapshot, { commandName }) {
30
33
  return [
31
34
  `${commandName} auth status`,
32
- status(snapshot.profiles.codex.valid ? "ok" : "warn", `Codex: ${accountLabel(snapshot.profiles.codex)} [legacy path]`),
35
+ status(snapshot.profiles.codex.valid ? "ok" : "warn", `Codex: ${accountLabel(snapshot.profiles.codex)} [${snapshot.profiles.codex.source === "ccdx" ? "CCDX store" : "legacy path"}]`),
33
36
  onlineStatusLine(snapshot.profiles.codex),
34
37
  status("info", `Routing: responses -> ${snapshot.routing.responses}`),
35
38
  ].filter(Boolean);
@@ -103,6 +106,40 @@ export async function runAuthCommand({
103
106
  output = process.stdout,
104
107
  ...options
105
108
  } = {}) {
109
+ if (["login", "reauth", "logout", "check"].includes(action)) {
110
+ const tools = options.tools || createAccountTools(options);
111
+ if (action === "check") {
112
+ const checked = await tools.check(), snapshot = authStatus(options);
113
+ snapshot.profiles.codex.online = checked.online ? { ...checked.online, httpStatus: checked.online.http_status } : null;
114
+ return { action, output: formatAuthStatus(snapshot, { commandName, format, output }), snapshot };
115
+ }
116
+ if (action === "logout") {
117
+ if (!options.yes) {
118
+ const input = options.input || process.stdin;
119
+ if (!input.isTTY || !output.isTTY) throw new Error("Use --yes to sign out of CCDX. Other apps stay signed in.");
120
+ const prompt = createInterface({ input, output });
121
+ try { if (!/^y(?:es)?$/i.test((await prompt.question("Sign out of CCDX? New requests will need a sign-in [y/N]: ")).trim())) return { action, output: "Sign-out cancelled." }; }
122
+ finally { prompt.close(); }
123
+ }
124
+ await tools.logout({ confirmed: true });
125
+ return { action, output: "Signed out of CCDX. Other apps stay signed in." };
126
+ }
127
+ const controller = new AbortController();
128
+ let id;
129
+ const cancel = () => { controller.abort();if (id) void tools.cancel(id);else tools.dispose(); };
130
+ process.once("SIGINT", cancel);
131
+ try {
132
+ const started = await tools.start({ reauth: action === "reauth" || options.reauth === true, expectedLogin: options.expectedLogin });
133
+ id = started.operation?.id;
134
+ if (controller.signal.aborted && id) await tools.cancel(id);
135
+ if (started.operation?.state === "authorizing") output.write(`Open ${started.operation.verification_uri}\nCode: ${started.operation.user_code}\nWaiting for GitHub. Ctrl+C cancels; saved sign-in is kept.\n`);
136
+ const result = await tools.wait();
137
+ if (result.operation?.state === "failed") throw new Error(`Sign-in failed: ${safeCell(result.operation.reason)}. Saved sign-in kept.`);
138
+ return { action, output: result.operation?.state === "cancelled" ? "Sign-in cancelled. Saved sign-in kept."
139
+ : result.operation?.state === "complete" ? "Signed in and verified. Use a new conversation; restart CCDX to change accounts."
140
+ : "A sign-in is saved. Run ccdx auth check to verify it, or ccdx auth reauth to replace it." };
141
+ } finally { process.removeListener("SIGINT", cancel);tools.dispose(); }
142
+ }
106
143
  if (action !== "status") throw new Error(`Unsupported auth action: ${action}`);
107
144
  const snapshot = online ? await authStatusOnline(options) : authStatus(options);
108
145
  return { action, output: formatAuthStatus(snapshot, { commandName, format, output }), snapshot };