codex-copilot-dx 0.9.38 → 0.9.40

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
@@ -18,11 +18,11 @@ ccdx
18
18
  CCDX reuses a compatible local credential or starts GitHub Device Flow, listens
19
19
  on `127.0.0.1:2026`, configures Codex, and opens the App. No client binary patch
20
20
  is needed. On Windows, open the App manually unless native prediction setup is
21
- enabled. If PowerShell blocks scripts, use `npm.cmd` / `ccdx.cmd`; do not change company policy. The configured `dummy` API key is a placeholder, not a credential.
21
+ 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`. No install script, alias or policy change is added; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
22
22
 
23
23
  Open [the local dashboard](http://127.0.0.1:2026/) for status, model discovery,
24
24
  usage, cache/limits, recent failures, request context and animation settings.
25
- Auto refresh runs every 30 minutes while visible and can be switched off. Hidden pages pause; opening sections and manual refresh still work. Startup uses an atom icon and aligned checks; `Ready` refers to the core service. Narrow/non-color terminals use a plain title.
25
+ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden pages pause; opening sections and manual refresh still work. The atom rotates once on page load and manual refresh, respecting reduced motion. Startup uses a compact six-line atom and aligned checks; `Ready` refers to the core service. Narrow/non-color terminals use a plain title.
26
26
 
27
27
  ## Commands
28
28
 
@@ -32,6 +32,8 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
32
32
  | `ccdx start` | Start or reuse the adapter and open Codex when auto-launch is enabled |
33
33
  | `ccdx status` | Runtime, limits and bounded request diagnostics |
34
34
  | `ccdx doctor` | Configuration, adapter and read-only App/catalog diagnostics |
35
+ | `ccdx doctor --fix` | Repair owned launchers/config, recover existing auth and enabled prediction routing once |
36
+ | `ccdx doctor --json` | Redacted structured diagnostics; combines with `--fix` |
35
37
  | `ccdx doctor config` | Read-only configuration check |
36
38
  | `ccdx doctor --compat` | Online inference/continuation compatibility probes |
37
39
  | `ccdx auth status` | Saved account; add `--online` to verify access |
@@ -64,10 +66,8 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
64
66
  break continuations. Generated images and Codex transcripts are not deleted.
65
67
  - Optional image setup/maintenance never blocks the primary service. Disabled
66
68
  users get no CCDX image skill or MCP installation.
67
- - The manual prediction MCP, background hook and dashboard panel are retired.
68
- Startup removes only unchanged CCDX registrations and disables saved prediction
69
- settings. The optional image MCP remains unchanged. Modified old registrations
70
- can use inert compatibility entrypoints; they no longer generate suggestions.
69
+ - Missing-token discovery includes legacy OpenCode Copilot OAuth and GitHub CLI. Reads are bounded and account-matched; incomplete/network-failed or HTTP-403-blocked discovery does not start another login. The default saved credential is preserved; Copilot 401/403 alone is not proof that it expired. Other apps' credentials stay read-only.
70
+ - `doctor --fix` does not start login, enable optional features, change company policy or force-restart Apps. It backs up changed config; missing-token repair can contact GitHub. Partial repairs exit 1. See the reference for exact scope.
71
71
  - Native predictions are a separate, opt-in compatibility feature. Quit Codex,
72
72
  run `ccdx prediction on`, then restart CCDX. This adds App-profile certificate
73
73
  trust and an App-only route for `chatgpt.com` and `ab.chatgpt.com`; HTTPS on those
@@ -75,7 +75,7 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
75
75
  Other domains and the CCDX model endpoint stay on their existing routes.
76
76
  No program files or OS trust are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are retained.
77
77
  Windows supports company PAC/WPAD; macOS dynamic routing remains unsupported. Windows setup needs the official MSIX App, Windows PowerShell and .NET Framework 4.7.2+—not Git/OpenSSL. See the reference for limits.
78
- Bridge checks allow three same-port recovery attempts per process, without App restart/replay. Only closed, initialized Apps in direct environments receive an owned persistent route; user/company proxies are preserved. Missing routes in running Apps are not hot-attached.
78
+ Bridge checks allow three same-port recovery attempts per process. The revised PAC adds a loopback retry endpoint after the unchanged primary, preserving company fallback. Quit Codex once to load this route revision; later CCDX upgrades retain it. App prediction failures can remain cached for five minutes, so network recovery is not proof of an immediate suggestion. Only closed, initialized Apps in direct environments receive an owned persistent route; missing routes in running Apps are not hot-attached.
79
79
  - CCDX adds experimental local history compression only when installed App
80
80
  runtimes support it and report it off. Existing choices are preserved; an
81
81
  already-enabled default, unavailable runtime or failed check is skipped.
package/bin/cli.mjs CHANGED
@@ -344,9 +344,11 @@ if (CLI.command === "doctor") {
344
344
  host: ADAPTER_HOST,
345
345
  online: CLI.online,
346
346
  compat: CLI.compat,
347
+ fix: CLI.fix,
348
+ json: CLI.json,
347
349
  });
348
350
  await LOGGING.cleanup();
349
- process.exit(checks.some((check) => check.kind === "err") ? 1 : 0);
351
+ process.exit(checks.some((check) => check.kind === "err" || (CLI.fix && check.result && check.kind === "warn")) ? 1 : 0);
350
352
  }
351
353
 
352
354
  console.log(`\n${startupBanner({ commandName: CLI_NAME, version: LOCAL_VERSION })}\n`);
@@ -364,6 +366,14 @@ async function printUpdateNotice() {
364
366
 
365
367
  try {
366
368
  assertSafeAdapterHost(ADAPTER_HOST, process.env);
369
+ if (process.platform === "win32") {
370
+ try {
371
+ const { inspectWindowsCommand } = await import("../src/windows-command.mjs");
372
+ const command = inspectWindowsCommand({ repair: true });
373
+ if (command.changed) console.log(startupCheck("ok", "Command", "Windows command entry updated; use ccdx next time"));
374
+ else if (command.status === "preserved") console.warn(startupCheck("warn", "Command", "Existing launcher preserved; use ccdx.cmd doctor to inspect it"));
375
+ } catch { console.warn(startupCheck("warn", "Command", "Optional command setup skipped; core startup will continue")); }
376
+ }
367
377
  const updateNotice = runInBackground(printUpdateNotice);
368
378
  if (await reuseRunningAdapterIfAvailable()) {
369
379
  // Ready is already displayed; finish the bounded check before this short-lived CLI exits.
@@ -372,6 +382,11 @@ try {
372
382
  process.exit(0);
373
383
  }
374
384
 
385
+ // Restore the opted-in listener alongside authentication/model initialization;
386
+ // a slow company-proxy setup must not delay the core listener.
387
+ const earlyIntegration = await clientIntegrations();
388
+ const predictionSetup = runInBackground(() => earlyIntegration.start());
389
+
375
390
  // Ensure GitHub login, using device flow if no token exists.
376
391
  await ensureAuth({ log: startupLogger("Auth") });
377
392
 
@@ -420,7 +435,7 @@ try {
420
435
  const { compressionSetup, imageEnabled, imageMcpSkipped } = await configureCodexClient();
421
436
 
422
437
  // Optional native prediction setup must never prevent the core adapter from running.
423
- nativePrediction = await (await clientIntegrations()).start();
438
+ nativePrediction = await predictionSetup;
424
439
  const persistentRoute = await nativePrediction?.prepareRoute();
425
440
 
426
441
  // Launch Codex when available. A running App is never forcibly restarted.
@@ -50,8 +50,31 @@ Authentication keeps its public facade in `auth.mjs`. Device-code polling and
50
50
  cancellation live in `auth-device-flow.mjs`; local discovery and transactional
51
51
  credential storage live in `auth-credentials.mjs`. These modules do not depend
52
52
  on the CLI, dashboard or service composition root.
53
+ `auth-sources.mjs` isolates known external credential contracts: legacy OpenCode
54
+ Copilot OAuth and noninteractive GitHub CLI token retrieval. Provider-specific
55
+ readers do not validate or write credentials. The auth facade enforces bounded
56
+ GitHub/Copilot validation, account matching and ambiguity handling. Saved-token
57
+ startup does not scan sources or make new validation calls.
58
+
59
+ `windows-command.mjs` owns exact npm-generated CCDX PowerShell launcher cleanup.
60
+ Best-effort Windows startup, the verified updater target and explicit doctor
61
+ repair share it. No install-time lifecycle script is added. It never edits
62
+ profiles, aliases, execution policy or npm's own shim.
63
+ Custom launchers and unverifiable installations are preserved.
64
+
65
+ Doctor composition stays in `doctor.mjs`; inference probes live in
66
+ `doctor-compat.mjs` and explicit bounded repairs in `doctor-repair.mjs`.
67
+ Repairs reuse the startup config transformation and prediction management API;
68
+ they do not start another adapter or implement a second prediction lifecycle.
69
+ Configuration repair takes the existing lock and commits the previous-file
70
+ backup transactionally. Disabled optional features stay disabled. JSON reports
71
+ separate before checks from final repair evidence; HTTP 200 alone is not success.
53
72
 
54
73
  Native prediction has a separate loopback transport and an isolated HTTPS agent.
74
+ The opted-in listener starts in parallel with auth/model initialization,
75
+ independently of Copilot credentials. A slow optional start cannot block core
76
+ listener setup, and fatal
77
+ startup cleanup closes any optional listener that was already started.
55
78
  Only its two selected hosts use the App-specific route. Non-configuration requests
56
79
  on those hosts are forwarded unchanged. The bridge does not replace Copilot or
57
80
  image-provider networking, modify client program files, or install system trust.
@@ -98,6 +121,16 @@ of certificates, networking and the CLI. It accepts multiple named hashed chunks
98
121
  without assuming the first general-settings chunk is the implementation. Signature
99
122
  and profile checks remain in the existing platform boundary.
100
123
 
124
+ `prediction-pac.mjs` is the pure shared format boundary for direct, static and
125
+ Windows company-PAC composition. Its stable revision URL makes a one-time old-PAC
126
+ migration observable without coupling routes to package versions. The unchanged
127
+ primary endpoint comes first; a clock-bucketed `.localhost` secondary lets
128
+ Chromium retry the same restored listener despite its per-endpoint failure cache.
129
+ The original company/direct fallback remains afterward. This adds no Node DNS
130
+ lookup, timer, listener, process or inference-path work. Browser route recovery
131
+ and the client's independently cached prediction configuration remain distinct;
132
+ neither is a visibility guarantee.
133
+
101
134
  Explicit `prediction fix` uses the optional integration's serialized lifecycle,
102
135
  not a second adapter or detached predictor. Startup, repair and shutdown cannot
103
136
  create overlapping owned listeners. Healthy/current bridges are retained; explicit
package/docs/REFERENCE.md CHANGED
@@ -31,6 +31,27 @@ feature uses the App's existing composer UI and the conversation's
31
31
  selected model through CCDX. Suggestions are not sent automatically. Native
32
32
  eligibility rules still apply; availability is not promised for every thread type.
33
33
 
34
+ The `0.9.40` routing revision uses the stable local PAC URL
35
+ `/proxy.pac?v=2`, independent of the package version. The primary proxy remains
36
+ `127.0.0.1` on the saved port. A secondary, time-bucketed `.localhost` name points
37
+ Chromium back to that same loopback listener after a cached proxy failure. Its
38
+ name changes every ten seconds when the PAC is evaluated, without a Node timer,
39
+ new listener, dependency, port, or background App watcher. Healthy traffic keeps
40
+ the original primary connection path. Direct/static/company-PAC fallbacks remain
41
+ after the two local entries, and unrelated hosts retain their original route.
42
+ The optional listener starts alongside GitHub auth and model initialization;
43
+ slow proxy setup does not delay the core adapter listener.
44
+
45
+ An App that loaded the old PAC must normally quit once to load this revision;
46
+ CCDX never force-restarts it or hot-writes an open profile. Subsequent upgrades
47
+ keep the revision URL, saved port and trust unchanged. An occupied saved port or
48
+ missing App route is not repaired by this retry mechanism. The installed App may
49
+ cache a failed prediction configuration for five minutes, and a subsequent
50
+ eligible turn may be needed to request another prediction. Returning configuration
51
+ traffic is not proof that native gray text is visible. Cross-platform browser
52
+ routing is tested separately from the user's native end-to-end acceptance;
53
+ the investigation report records these evidence levels without equating them.
54
+
34
55
  Version `0.9.26` adds Windows platform adapters. Native gray suggestions,
35
56
  adoption/sending and switching predictions off were verified on Windows with the
36
57
  `.4` candidate. Windows setup
@@ -728,6 +749,45 @@ If a configured npm mirror has not synchronized the current release yet, use the
728
749
 
729
750
  ## Diagnostics
730
751
 
752
+ `ccdx doctor` is read-only by default and makes no inference request. It checks
753
+ local credentials/configuration, Node/platform, installation target, Windows
754
+ command launchers, enabled optional feature settings and the running adapter.
755
+ Disabled image/prediction features do not trigger provider or routing setup.
756
+ `--online` checks GitHub/Copilot access and a nonempty model directory; `--compat`
757
+ explicitly consumes model usage and requires completed Responses/SSE, not just
758
+ HTTP 200. Probe bodies are bounded to 4 MiB.
759
+
760
+ `ccdx doctor --fix` makes one repair attempt per supported area and verifies its
761
+ result: exact owned Windows command shims, startup-managed Codex settings, a
762
+ verified existing GitHub credential when none is saved, and the already-enabled
763
+ prediction bridge through its existing management API. Credential recovery can
764
+ contact GitHub without `--online`, but never starts Device Flow. Existing tokens,
765
+ user-modified/invalid configuration, unrelated MCPs/hooks and company routing or
766
+ security policy are not replaced. Existing changed config is transactionally
767
+ backed up to `config.toml.ccdx-doctor.bak` (the latest repair backup only). Repairs
768
+ do not install optional image tools, enable prediction, renew certificates or
769
+ force-restart Apps. A required normal App/service restart remains an explicit
770
+ partial result. Partial repairs exit 1; no automatic retry loop is added.
771
+
772
+ `ccdx doctor --json` emits one redacted JSON report; combine with `--fix` to
773
+ include `before_checks` and final per-operation repair results. Inspect these
774
+ results rather than equating a configured bridge with a visible gray suggestion.
775
+
776
+ Windows adds no install-time lifecycle script, so npm 12's script-approval policy
777
+ is not expanded. In restricted PowerShell, install with `npm.cmd`, then first run
778
+ `ccdx.cmd` or `ccdx.cmd doctor --fix`. Startup recognizes only the exact npm
779
+ PowerShell shims for the two CCDX commands, checks their matching `.cmd` targets
780
+ and package identity, then removes those `.ps1` shims. Subsequent calls can use
781
+ bare `ccdx` without changing policy or profiles. The updater applies the same
782
+ check only after verifying its installed target/version. Customized, symlinked,
783
+ unexpected or unreadable shims are preserved; optional setup failures do not
784
+ block core startup or turn a verified update into failure. Direct npm reinstalls
785
+ can recreate the shims; a first `.cmd` invocation repairs them again. Read-only
786
+ commands such as version/help/status do not repair them. Aliases/functions and
787
+ another installation earlier in PATH can still override resolution. npm's own
788
+ `.ps1` shim is untouched, so `npm.cmd` may still be needed. macOS/Linux and source
789
+ checkouts are no-ops.
790
+
731
791
  `ccdx status` and the dashboard show the sample count beside each timing. First
732
792
  output is observed at the gateway from generated deltas, hidden-reasoning/tool
733
793
  announcements or content snapshots; a runtime-only result is marked separately.
@@ -873,6 +933,31 @@ scan are retained. Rows render when opened, without another API call.
873
933
 
874
934
  When the saved token is missing, `ccdx` looks for compatible local Copilot GitHub tokens, validates them with GitHub and Copilot, and imports a valid one before starting Device Flow. It checks explicit token sources (`CCDX_GITHUB_TOKEN`, `CCDX_GITHUB_TOKEN_PATH`, and `CCDX_GITHUB_TOKEN_PATHS`) plus common local `auth.json` layouts. Generic discovery refuses to choose silently when valid credentials for multiple GitHub accounts are found.
875
935
 
936
+ Discovery also reads legacy OpenCode's `$XDG_DATA_HOME/opencode/auth.json`
937
+ (otherwise `~/.local/share/opencode/auth.json`), specifically `github-copilot`
938
+ OAuth `refresh`, and an installed GitHub CLI's noninteractive
939
+ `gh auth token --hostname github.com`. It does not import unrelated API keys,
940
+ enterprise-host OAuth, browser cookies, subscription credentials or a newer
941
+ OpenCode database format. `APPDATA` and `LOCALAPPDATA` auth.json roots are included
942
+ where present. GitHub CLI is optional, not a runtime dependency; its output/time
943
+ are bounded and no login prompt is started. Other apps' files remain read-only.
944
+ Source reads are bounded, discovery validates at most 24 distinct tokens within
945
+ a 12-second overall validation budget, and each candidate has a 4-second budget.
946
+ Directory/profile scans have explicit caps; hitting a cap or a network failure
947
+ reports incomplete discovery rather than silently selecting an account or
948
+ starting another login. Set an explicit source/account to resolve ambiguity.
949
+ An existing saved-token startup path performs no extra discovery/network calls.
950
+ Package reinstallation does not clear that user-owned credential. Copilot's short-lived
951
+ access token is obtained again when needed; it is not the saved GitHub credential.
952
+ For the default credential store, Copilot HTTP 403 preserves the credential and
953
+ reports access/network policy rather than recommending deletion. Copilot HTTP 401
954
+ performs a bounded GitHub identity check only if compatible local recovery did not
955
+ succeed. Only an identity HTTP 401 permits reauthorization guidance; an unavailable
956
+ check does not establish expiry. Neither case automatically deletes the credential
957
+ or starts Device Flow. Denials are not hidden by a cached Copilot token. A discovery
958
+ HTTP 403 also stops before Device Flow, preserving external sources and account
959
+ selection. Isolated/custom credential clients retain their own recovery contract.
960
+
876
961
  After an account is selected, automatic `401`/`403` recovery and in-process token rotation accept only that same GitHub account. Concurrent callers share token refresh work without sharing cancellation, and a still-valid Copilot token may be used briefly after a transient refresh failure. Explicit token variables remain the intentional way to select another account.
877
962
 
878
963
  If refresh still fails with `401` or `403`, the saved GitHub OAuth credential may be expired, revoked, or missing Copilot access. After stopping the adapter, remove that exact saved token and start again to rerun authentication recovery:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "0.9.38",
3
+ "version": "0.9.40",
4
4
  "description": "Use Codex App with GitHub Copilot",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -4,9 +4,11 @@ import os from "node:os";
4
4
  import { atomicWriteFilePairSync, atomicWriteFileSync } from "./atomic-file.mjs";
5
5
  import { githubTokenFingerprint, normalizeGithubIdentity } from "./github-identity.mjs";
6
6
  import { readBoundedFileSync, MAX_TOKEN_FILE_BYTES } from "./bounded-file.mjs";
7
+ import { additionalGithubSources, readAdditionalGithubSource } from "./auth-sources.mjs";
7
8
 
8
9
  const DISABLE_TOKEN_DISCOVERY_VALUES = new Set(["1", "true", "yes"]);
9
10
  const MAX_AUTH_JSON_BYTES = 1024 * 1024;
11
+ const pathKey = value => process.platform === "win32" ? path.resolve(value).toLowerCase() : path.resolve(value);
10
12
 
11
13
  export function githubTokenPath(home = os.homedir()) {
12
14
  return path.join(home, ".local", "share", "copilot-api", "github_token");
@@ -50,15 +52,17 @@ function localAuthRoots(home, env = process.env) {
50
52
  const roots = [
51
53
  path.join(home, "Library", "Application Support"),
52
54
  env.APPDATA ? expandHome(env.APPDATA, home) : "",
55
+ env.LOCALAPPDATA ? expandHome(env.LOCALAPPDATA, home) : "",
53
56
  env.XDG_CONFIG_HOME ? expandHome(env.XDG_CONFIG_HOME, home) : path.join(home, ".config"),
54
57
  ].filter(Boolean);
55
- return [...new Set(roots)];
58
+ const seen = new Set();
59
+ return roots.filter(root => { const key = pathKey(root);if (seen.has(key)) return false;seen.add(key);return true; });
56
60
  }
57
61
 
58
62
  function addAuthJsonSource(sources, seen, filePath) {
59
- if (seen.has(filePath)) return;
63
+ if (seen.has(pathKey(filePath))) return;
60
64
  if (!fs.existsSync(filePath)) return;
61
- seen.add(filePath);
65
+ seen.add(pathKey(filePath));
62
66
  sources.push({ type: "auth-json", path: filePath });
63
67
  }
64
68
 
@@ -74,7 +78,11 @@ function localAuthJsonSources(home, env = process.env) {
74
78
  continue;
75
79
  }
76
80
 
77
- for (const appDirent of appDirs) {
81
+ if (appDirs.length > 256) Object.defineProperty(sources, "incomplete", { value: true, configurable: true });
82
+ for (const appDirent of appDirs.slice(0, 256)) {
83
+ if (sources.length >= 128) {
84
+ Object.defineProperty(sources, "incomplete", { value: true, configurable: true });return sources;
85
+ }
78
86
  if (!appDirent.isDirectory()) continue;
79
87
  const appDir = path.join(root, appDirent.name);
80
88
  addAuthJsonSource(sources, seen, path.join(appDir, "auth.json"));
@@ -87,7 +95,11 @@ function localAuthJsonSources(home, env = process.env) {
87
95
  continue;
88
96
  }
89
97
 
90
- for (const profileDirent of profileDirs) {
98
+ if (profileDirs.length > 64) Object.defineProperty(sources, "incomplete", { value: true, configurable: true });
99
+ for (const profileDirent of profileDirs.slice(0, 64)) {
100
+ if (sources.length >= 128) {
101
+ Object.defineProperty(sources, "incomplete", { value: true, configurable: true });return sources;
102
+ }
91
103
  if (!profileDirent.isDirectory()) continue;
92
104
  addAuthJsonSource(sources, seen, path.join(profilesDir, profileDirent.name, "auth.json"));
93
105
  }
@@ -108,8 +120,8 @@ function explicitTokenFileSources(home, env = process.env) {
108
120
  return paths
109
121
  .map((filePath) => expandHome(filePath, home))
110
122
  .filter((filePath) => {
111
- if (seen.has(filePath)) return false;
112
- seen.add(filePath);
123
+ if (seen.has(pathKey(filePath))) return false;
124
+ seen.add(pathKey(filePath));
113
125
  return true;
114
126
  })
115
127
  .map((filePath) => ({
@@ -141,7 +153,10 @@ export function githubTokenSources({
141
153
  sources.push({ type: "env", name: "CCDX_GITHUB_TOKEN", token: env.CCDX_GITHUB_TOKEN.trim() });
142
154
  }
143
155
  sources.push(...explicitTokenFileSources(home, env));
144
- sources.push(...localAuthJsonSources(home, env));
156
+ const local = localAuthJsonSources(home, env);
157
+ sources.push(...local);
158
+ sources.push(...additionalGithubSources(home, env));
159
+ if (local.incomplete) Object.defineProperty(sources, "incomplete", { value: true });
145
160
  return sources;
146
161
  }
147
162
 
@@ -150,6 +165,8 @@ export function sourceDescription(source) {
150
165
  if (source.type === "env") return source.name;
151
166
  if (source.type === "token-file") return `${source.name} (${source.path})`;
152
167
  if (source.type === "auth-json") return `local auth file (${source.path})`;
168
+ if (source.type === "opencode-auth") return `OpenCode Copilot auth (${source.path})`;
169
+ if (source.type === "github-cli") return "GitHub CLI (github.com)";
153
170
  return source.path || source.name || "unknown source";
154
171
  }
155
172
 
@@ -167,7 +184,7 @@ export function extractGithubTokenFromAuthJson(json) {
167
184
  return candidates.find((value) => typeof value === "string" && value.trim())?.trim() || "";
168
185
  }
169
186
 
170
- export function readGithubTokenSource(source) {
187
+ export function readGithubTokenSource(source, options = {}) {
171
188
  if (source?.type === "env") return source.token || "";
172
189
  if (source?.type === "token-file") return readBoundedFileSync(source.path, { encoding: "utf8", maxBytes: MAX_TOKEN_FILE_BYTES }).trim();
173
190
  if (source?.type === "auth-json") {
@@ -175,7 +192,7 @@ export function readGithubTokenSource(source) {
175
192
  if (!looksLikeCopilotAuthJson(json)) return "";
176
193
  return extractGithubTokenFromAuthJson(json);
177
194
  }
178
- return "";
195
+ return readAdditionalGithubSource(source, { readJson: readSmallJson, ...options });
179
196
  }
180
197
 
181
198
  export function readSavedGithubToken(home = os.homedir()) {
@@ -0,0 +1,42 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { execFileSync } from "node:child_process";
4
+
5
+ // Known provider contracts only; never treat unrelated API keys as GitHub tokens.
6
+ export function additionalGithubSources(home, env) {
7
+ const data = env.XDG_DATA_HOME || path.join(home, ".local", "share");
8
+ const sources = [];
9
+ const auth = path.join(data, "opencode", "auth.json");
10
+ if (fs.existsSync(auth)) sources.push({ type: "opencode-auth", path: auth });
11
+ const search = Object.entries(env).find(([key]) => key.toLowerCase() === "path")?.[1] || "";
12
+ const seen = new Set();
13
+ for (const item of search.split(path.delimiter)) {
14
+ const directory = item.trim().replace(/^"|"$/g, "");
15
+ if (!directory || !path.isAbsolute(directory)) continue;
16
+ const key = process.platform === "win32" ? directory.toLowerCase() : directory;
17
+ if (seen.has(key)) continue;
18
+ seen.add(key);
19
+ const command = path.join(directory, process.platform === "win32" ? "gh.exe" : "gh");
20
+ try {
21
+ if (fs.statSync(command).isFile()) { sources.push({ type: "github-cli", path: command });break; }
22
+ } catch {}
23
+ }
24
+ return sources;
25
+ }
26
+
27
+ export function readAdditionalGithubSource(source, { readJson, env = process.env, exec = execFileSync } = {}) {
28
+ if (source.type === "opencode-auth") {
29
+ const credential = readJson(source.path)?.["github-copilot"];
30
+ // Legacy OpenCode auth.json stores GitHub's OAuth token in refresh, not the
31
+ // short-lived Copilot service token. Enterprise credentials have another audience.
32
+ if (credential?.type !== "oauth" || credential.enterpriseUrl || credential.enterprise_url) return "";
33
+ return typeof credential.refresh === "string" ? credential.refresh.trim() : "";
34
+ }
35
+ if (source.type === "github-cli") {
36
+ return exec(source.path, ["auth", "token", "--hostname", "github.com"], {
37
+ env: { ...env, GH_PROMPT_DISABLED: "1" }, encoding: "utf8", shell: false,
38
+ windowsHide: true, timeout: 1000, maxBuffer: 16 * 1024, stdio: ["ignore", "pipe", "pipe"],
39
+ }).trim();
40
+ }
41
+ return "";
42
+ }
package/src/auth.mjs CHANGED
@@ -55,7 +55,10 @@ export async function fetchGithubIdentity(token, {
55
55
  headers: { Authorization: `token ${token.trim()}`, Accept: "application/json" },
56
56
  signal: controller.signal,
57
57
  }), controller.signal);
58
- if (!resp.ok) return { ok: false, status: resp.status, reason: "github_user_failed" };
58
+ if (!resp.ok) {
59
+ cancelResponseBody(resp);
60
+ return { ok: false, status: resp.status, reason: "github_user_failed" };
61
+ }
59
62
  const data = await awaitWithSignal(() => resp.json(), controller.signal);
60
63
  const identity = normalizeGithubIdentity(data);
61
64
  return identity ? { ok: true, ...identity } : { ok: false, reason: "github_identity_missing" };
@@ -91,7 +94,18 @@ export async function ensureGithubTokenMetadata(token, {
91
94
  export async function validateGithubToken(token, {
92
95
  fetchImpl = fetch,
93
96
  signal,
97
+ timeoutMs = 10000,
94
98
  } = {}) {
99
+ const deadline = AbortSignal.timeout(parseTimerMs(timeoutMs, 10000));
100
+ const combined = signal ? AbortSignal.any([signal, deadline]) : deadline;
101
+ try {
102
+ return await awaitWithSignal(() => validateGithubTokenRequest(token, { fetchImpl, signal: combined }), combined);
103
+ } catch {
104
+ return { ok: false, transient: true, reason: signal?.aborted ? "validation_cancelled" : "validation_timeout" };
105
+ }
106
+ }
107
+
108
+ async function validateGithubTokenRequest(token, { fetchImpl, signal }) {
95
109
  if (typeof token !== "string" || !token.trim()) {
96
110
  return { ok: false, reason: "empty_token" };
97
111
  }
@@ -99,37 +113,44 @@ export async function validateGithubToken(token, {
99
113
  const headers = { Authorization: `token ${token.trim()}`, Accept: "application/json" };
100
114
  let userResp;
101
115
  try {
102
- userResp = await fetchImpl(`${GITHUB_API}/user`, { headers, signal });
116
+ userResp = await awaitWithSignal(() => fetchImpl(`${GITHUB_API}/user`, { headers, signal, redirect: "error" }), signal);
103
117
  } catch (e) {
104
118
  return { ok: false, transient: true, reason: "github_user_request_failed", error: e };
105
119
  }
106
120
 
107
121
  if (!userResp.ok) {
122
+ cancelResponseBody(userResp);
108
123
  return {
109
124
  ok: false,
110
125
  status: userResp.status,
111
- reason: userResp.status === 401 || userResp.status === 403 ? "github_token_invalid" : "github_user_failed",
126
+ accessDenied: userResp.status === 403,
127
+ transient: userResp.status === 429 || userResp.status >= 500 || userResp.headers?.get?.("x-ratelimit-remaining") === "0",
128
+ reason: userResp.status === 401 ? "github_token_invalid" : userResp.status === 403 ? "github_access_denied" : "github_user_failed",
112
129
  };
113
130
  }
114
131
 
115
132
  let userData = {};
116
133
  try {
117
- userData = await userResp.json();
134
+ userData = await awaitWithSignal(() => userResp.json(), signal);
118
135
  } catch {}
119
136
  const login = typeof userData.login === "string" ? userData.login : "";
120
137
  const id = userData.id === undefined || userData.id === null ? "" : String(userData.id);
138
+ if (!login && !id) return { ok: false, transient: true, reason: "github_identity_missing" };
121
139
 
122
140
  let copilotResp;
123
141
  try {
124
- copilotResp = await fetchImpl(COPILOT_TOKEN_URL, { headers, signal });
142
+ copilotResp = await awaitWithSignal(() => fetchImpl(COPILOT_TOKEN_URL, { headers, signal, redirect: "error" }), signal);
125
143
  } catch (e) {
126
144
  return { ok: false, transient: true, reason: "copilot_token_request_failed", login, error: e };
127
145
  }
128
146
 
129
147
  if (!copilotResp.ok) {
148
+ cancelResponseBody(copilotResp);
130
149
  return {
131
150
  ok: false,
132
151
  status: copilotResp.status,
152
+ accessDenied: copilotResp.status === 403,
153
+ transient: copilotResp.status === 429 || copilotResp.status >= 500,
133
154
  reason: copilotResp.status === 401 || copilotResp.status === 403 ? "copilot_access_denied" : "copilot_token_failed",
134
155
  login,
135
156
  };
@@ -137,13 +158,13 @@ export async function validateGithubToken(token, {
137
158
 
138
159
  let copilotTokenData = {};
139
160
  try {
140
- copilotTokenData = await copilotResp.json();
161
+ copilotTokenData = await awaitWithSignal(() => copilotResp.json(), signal);
141
162
  } catch (e) {
142
- return { ok: false, reason: "copilot_token_parse_failed", login, error: e };
163
+ return { ok: false, transient: true, reason: "copilot_token_parse_failed", login, error: e };
143
164
  }
144
165
 
145
- if (!copilotTokenData.token) {
146
- return { ok: false, reason: "copilot_token_missing", login };
166
+ if (typeof copilotTokenData.token !== "string" || !copilotTokenData.token.trim()) {
167
+ return { ok: false, transient: true, reason: "copilot_token_missing", login };
147
168
  }
148
169
 
149
170
  return { ok: true, login, id, copilotTokenData };
@@ -158,25 +179,35 @@ export async function discoverGithubToken({
158
179
  excludeIdentities = [],
159
180
  expectedIdentity,
160
181
  strictExpectedIdentity = false,
182
+ timeoutMs = 12000,
183
+ maxCandidates = 24,
184
+ sources = githubTokenSources({ home, env }),
185
+ readSource = readGithubTokenSource,
161
186
  } = {}) {
187
+ const deadline = AbortSignal.timeout(parseTimerMs(timeoutMs, 12000));
188
+ const boundedSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
162
189
  const excluded = new Set(excludeTokens);
163
190
  const seen = new Set(excluded);
164
191
  const failures = [];
165
192
  const candidates = [];
166
193
 
167
- for (const source of githubTokenSources({ home, env })) {
194
+ for (const source of sources) {
195
+ if (boundedSignal.aborted || seen.size - excluded.size >= maxCandidates) {
196
+ return { ok: false, incomplete: true, transient: true, failures };
197
+ }
168
198
  let token = "";
169
199
  try {
170
- token = readGithubTokenSource(source).trim();
200
+ token = readSource(source, { env }).trim();
171
201
  } catch (e) {
172
- failures.push({ source, reason: "read_failed", error: e });
202
+ // Child-process errors may carry stdout containing a credential.
203
+ failures.push({ source: { type: source.type, path: source.path }, reason: "read_failed" });
173
204
  continue;
174
205
  }
175
206
 
176
207
  if (!token || seen.has(token)) continue;
177
208
  seen.add(token);
178
209
 
179
- const validation = await validateGithubToken(token, { fetchImpl, signal });
210
+ const validation = await validateGithubToken(token, { fetchImpl, signal: boundedSignal, timeoutMs: 4000 });
180
211
  if (validation.ok) {
181
212
  if (excludeIdentities.some((identity) => githubIdentityMatchesExpected(validation, identity))) {
182
213
  failures.push({ source, validation, reason: "github_account_excluded" });
@@ -196,6 +227,9 @@ export async function discoverGithubToken({
196
227
  failures.push({ source, validation });
197
228
  }
198
229
 
230
+ if (sources.incomplete || boundedSignal.aborted || failures.some(item => item.validation?.transient)) {
231
+ return { ok: false, incomplete: true, transient: true, failures };
232
+ }
199
233
  if (candidates.length) {
200
234
  const identities = new Set(candidates.map(({ validation, token }) => {
201
235
  if (validation.id) return `id:${validation.id}`;
@@ -215,6 +249,9 @@ export async function discoverGithubToken({
215
249
  };
216
250
  }
217
251
 
252
+ if (failures.some(item => item.validation?.accessDenied)) {
253
+ return { ok: false, accessDenied: true, failures };
254
+ }
218
255
  return { ok: false, failures };
219
256
  }
220
257
 
@@ -238,6 +275,7 @@ export async function importDiscoveredGithubToken({
238
275
  return { ok: true, token: savedToken, source: { type: "saved-token" }, imported: false };
239
276
  }
240
277
  const validation = await validateGithubToken(savedToken, { fetchImpl, signal });
278
+ if (validation.transient) throw new Error("GitHub access could not be checked. The saved credential was preserved; check your network and retry.");
241
279
  if (validation.ok && githubIdentityMatchesExpected(validation, expectedIdentity)) {
242
280
  writeGithubTokenMetadata(validation, home, savedToken);
243
281
  return { ok: true, token: savedToken, source: { type: "saved-token" }, validation, imported: false };
@@ -257,6 +295,8 @@ export async function importDiscoveredGithubToken({
257
295
  const logins = [...new Set(discovered.candidates.map((candidate) => candidate.login || candidate.id || "unknown"))];
258
296
  throw new Error(`Multiple GitHub Copilot accounts were found (${logins.join(", ")}). Set CCDX_GITHUB_LOGIN or CCDX_GITHUB_TOKEN_PATH to select one explicitly.`);
259
297
  }
298
+ if (discovered.accessDenied) throw new Error("GitHub or Copilot denied access to an existing credential. Check account access and network policy; credentials were preserved and no new login was started.");
299
+ if (discovered.transient) throw new Error("Local GitHub credentials could not be fully checked. Check network access and retry; no new login was started.");
260
300
  if (!discovered.ok) return null;
261
301
  writeToken(discovered.token, home, discovered.validation);
262
302
  const login = discovered.validation.login ? ` for ${discovered.validation.login}` : "";
@@ -295,6 +295,8 @@ export function parseCliArgs(args = []) {
295
295
  const options = parseOptions(rest, new Map([
296
296
  ["--online", "flag"],
297
297
  ["--compat", "flag"],
298
+ ["--fix", "flag"],
299
+ ["--json", "flag"],
298
300
  ["--profile", "value"],
299
301
  ]));
300
302
  const profile = options["--profile"];
@@ -306,6 +308,8 @@ export function parseCliArgs(args = []) {
306
308
  ...baseCommand("doctor"),
307
309
  online: Boolean(options["--online"]),
308
310
  compat: Boolean(options["--compat"]),
311
+ ...(options["--fix"] ? { fix: true } : {}),
312
+ ...(options["--json"] ? { json: true } : {}),
309
313
  };
310
314
  }
311
315
  if (RETIRED_CLAUDE_OPTIONS.has(command)) {
@@ -363,7 +367,7 @@ function topicHelp(name, topic) {
363
367
  start: `Usage:\n ${name} [start] [--show-request-id]\n\nStarts or reuses the local adapter, updates Codex configuration, and attempts to open Codex App when auto-launch is enabled and supported.`,
364
368
  auth: `Usage:\n ${name} auth status [--online] [--format table|plain]\n\nShows the saved GitHub Copilot account without exposing credentials. --online also verifies its entitlement and model catalog.`,
365
369
  "auth status": `Usage:\n ${name} auth status [--online] [--format table|plain]\n\nShows the saved GitHub Copilot account without exposing credentials. --online also verifies its entitlement and model catalog. Interactive terminals use a table by default.`,
366
- doctor: `Usage:\n ${name} doctor [--online] [--compat]\n ${name} doctor config\n\nChecks the local credential, Codex configuration, adapter, installed App version, running App identities and observed client catalog. App-internal cache is not externally verified. No processes are killed or client files changed. --online validates account entitlement; --compat sends minimal inference requests and consumes a small amount of Copilot usage. The config subcommand checks only the local file and previews startup changes, without network, authentication, file writes or process inspection.`,
370
+ doctor: `Usage:\n ${name} doctor [--online] [--compat] [--fix] [--json]\n ${name} doctor config\n\nChecks credentials, managed configuration, command launchers, adapter, enabled optional features and observed client catalog. Default is read-only; no inference requests. --online validates account entitlement; --compat sends minimal inference requests and consumes a small amount of Copilot usage, requiring successful model completion rather than HTTP 200 alone. --fix repairs owned Windows launchers and managed config, imports a verified existing credential only if none is saved, and asks the running adapter to repair enabled predictions once. No interactive login, client program edits, forced App restarts, policy changes or optional feature activation. Missing-credential repair can contact GitHub without --online. Changed existing config is backed up to config.toml.ccdx-doctor.bak. Partial repairs exit 1. --json emits a redacted report, including before_checks for repairs. App-internal cache and visible predictions are not externally verified. The config subcommand remains strictly read-only.`,
367
371
  "doctor config": `Usage:\n ${name} doctor config\n\nReads ~/.codex/config.toml, checks TOML syntax and CCDX-managed settings, and previews the existing startup writer's changes. Does not merge Codex profiles or validate the complete installed Codex schema. No authentication, network requests, file writes, or adapter/GUI startup. Existing context_management=false is valid. Exit 1 for errors, 0 for OK/warnings; unsupported arguments exit 2.`,
368
372
  status: `Usage:\n ${name} status\n\nShows bounded runtime, routing, performance, queue, and cache metrics from a running adapter.`,
369
373
  models: `Usage:\n ${name} models [--format table|plain]\n\nPerforms a fresh, read-only Copilot model-directory lookup for the saved account. Interactive terminals use a table by default.`,
@@ -390,7 +394,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
390
394
  return `Usage:
391
395
  ${name} [start] [--show-request-id]
392
396
  ${name} auth status [--online] [--format table|plain]
393
- ${name} doctor [--online] [--compat]
397
+ ${name} doctor [--online] [--compat] [--fix] [--json]
394
398
  ${name} doctor config
395
399
  ${name} status
396
400
  ${name} models [--format table|plain]
@@ -49,10 +49,8 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
49
49
  async configure() {
50
50
  try {
51
51
  const { retirePredictionIntegration } = await import("./prediction-retirement.mjs");
52
- const result = retirePredictionIntegration();
53
- if (result.changed) info("Removed the retired CCDX prediction integration");
54
- if (result.preserved) warning("Modified prediction settings were preserved");
55
- } catch (error) { warning(`${error.message}. Core startup will continue.`); }
52
+ retirePredictionIntegration();
53
+ } catch { /* Legacy cleanup is optional; never interrupt or clutter core startup. */ }
56
54
  const enabled = Boolean(readImageProviderConfig());
57
55
  const { imageMcpSkipped } = ensureCodexConfig(port, { host, imageProviderEnabled: enabled, ...(configLog ? { log: configLog } : {}) });
58
56
  if (enabled && !imageMcpSkipped) {