codex-copilot-dx 0.9.30 → 0.9.33

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
@@ -19,7 +19,7 @@ ccdx
19
19
  CCDX reuses a compatible local credential or starts GitHub Device Flow, listens
20
20
  on `127.0.0.1:2026`, configures Codex, and opens the App. No client binary patch
21
21
  is needed. On Windows, open the App manually unless native prediction setup is
22
- enabled. The configured `dummy` API key is a placeholder, not a credential.
22
+ 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.
23
23
 
24
24
  Open [the local dashboard](http://127.0.0.1:2026/) for status, model discovery,
25
25
  usage, cache/limits, recent failures, request context and animation settings.
@@ -86,13 +86,13 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
86
86
 
87
87
  Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`.
88
88
  Updates install the exact stable tag; dependencies still use npm's configured registry. Lookup errors identify HTTP refusal, timeout, network failure or invalid redirects.
89
+ Updates warn about mismatched npm targets without changing PATH/prefix. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
90
+ Recent errors separate HTTP and model failures. HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged.
89
91
 
90
92
  The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown.
91
93
  Inference, client integration, optional images and management have separate ownership. See [architecture boundaries](docs/ARCHITECTURE.md).
92
94
 
93
- See the [complete command/configuration reference](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/REFERENCE.md)
94
- for authentication recovery, configuration safety, limits, logging, images and client compatibility.
95
- The same reference is included as `docs/REFERENCE.md` in the installed npm package.
95
+ See the [complete reference](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/REFERENCE.md) for authentication, configuration, limits, logging, images and compatibility. It is also included as `docs/REFERENCE.md` in the npm package.
96
96
 
97
97
  ## Development
98
98
 
@@ -102,7 +102,7 @@ npm run verify
102
102
  node scripts/config-startup-replay.mjs
103
103
  ```
104
104
 
105
- Verification covers unit tests, isolated HTTP/idle-stream replay, performance
106
- and resource gates, and package contents. These are not an upstream service SLA.
105
+ Verification covers unit tests, isolated HTTP/idle-stream replay, performance/resource gates and package contents—not an upstream service SLA.
106
+ CI also tests Node 22.15/24 on Linux, Windows and macOS, temporary-prefix installation/upgrade and installed image processing.
107
107
 
108
108
  License: MIT.
@@ -18,6 +18,23 @@ The CLI composes the service. Client integration owns its `configure`, `start`,
18
18
  render the dashboard. The adapter exposes integration snapshots and keeps
19
19
  management/MCP routes separate from the Responses path.
20
20
 
21
+ Package installation is an explicit management operation in `package-update.mjs`,
22
+ not part of inference or optional client integration. Windows uses the system
23
+ command interpreter only for the fixed `npm.cmd` installer command; stable-tag
24
+ validation remains upstream of launch. macOS/Linux use direct npm argv. There
25
+ is no generic shell runner or package-manager framework, and npm's configured
26
+ registry/proxy environment remains owned by the user.
27
+ Readonly update preflight reports Node/npm, the running package and npm's selected
28
+ global target. A different target warns, but never changes PATH or prefix. Its
29
+ bounded npm probe is limited to explicit update and full doctor commands.
30
+ Its stdout/stderr are captured separately; npm configuration warnings do not
31
+ leak into doctor output. The real installer's inherited streams are unchanged.
32
+
33
+ Authentication keeps its public facade in `auth.mjs`. Device-code polling and
34
+ cancellation live in `auth-device-flow.mjs`; local discovery and transactional
35
+ credential storage live in `auth-credentials.mjs`. These modules do not depend
36
+ on the CLI, dashboard or service composition root.
37
+
21
38
  Native prediction has a separate loopback transport and an isolated HTTPS agent.
22
39
  Only its two selected hosts use the App-specific route. Non-configuration requests
23
40
  on those hosts are forwarded unchanged. The bridge does not replace Copilot or
@@ -68,13 +85,19 @@ and referenced/split histories do not gain filesystem recovery access.
68
85
 
69
86
  `dashboard/refresh.js` owns the browser-only read lifecycle: one visible-page
70
87
  timer, per-group in-flight deduplication, attempt freshness, cancellation and
71
- last-good snapshots. `ui.js` owns rendering and user selections. Models, usage,
88
+ last-good snapshots. `ui.js` composes the controls and refresh resources;
89
+ `status.js` owns status/failure rendering, and `usage.js` owns usage rendering
90
+ and date selection. Their state stays page-local. Models, usage,
72
91
  status/account and animation metadata remain independent resources; no timer
73
92
  or data watcher is added to the Node service. Animation frames load once per
74
93
  page when opened, and read refresh does not overwrite an unsaved choice.
75
94
  `upstream-body.mjs` is the shared bounded response reader. The transport retains
76
95
  its existing exports; live model lookup uses the same 8 MiB catalog limit as
77
96
  core model discovery, without importing the request lifecycle or UI layer.
97
+ Overlapping live queries with the same credential fingerprint, home, fetch
98
+ implementation and lookup parameters share one in-flight lookup. A waiter can
99
+ cancel independently; the last cancellation aborts the lookup. Completed results
100
+ are not cached as live, and each waiter receives its own snapshot.
78
101
 
79
102
  ## Configuration ownership
80
103
 
@@ -83,6 +106,12 @@ selection and are not inferred from that directory. CCDX writers use a shared
83
106
  per-file lock, reread current contents and preserve unrelated values. Locks do
84
107
  not coordinate editors or other applications that ignore them. Read-only status
85
108
  and doctor commands do not write configuration.
109
+ Small local reads use one open file descriptor with byte limits: 1 MiB for
110
+ settings/auth metadata, 64 KiB for token files, and 9 MiB for cached model data
111
+ (including metadata). This does not change session/history limits or symlink
112
+ semantics. Full doctor checks credential permissions without reading secrets:
113
+ POSIX mode bits or Windows allow entries are review evidence, not a complete
114
+ effective-access calculation. It never rewrites ACLs or blocks startup.
86
115
 
87
116
  Core inference interfaces remain unchanged. This change adds a concrete
88
117
  composition boundary; it does not relocate every file or add speculative APIs.
@@ -93,9 +122,20 @@ Prediction preference, bridge readiness and observed configuration responses are
93
122
  different states. None proves that a candidate appeared in the App. The dashboard
94
123
  keeps that result unknown. Integration diagnostics retain bounded, redacted
95
124
  metadata, not conversation or image contents.
125
+ HTTP failures have a separate 20-entry metadata ring (`http_errors`): status,
126
+ safe technical code, model when observed, route, source and request IDs. Original
127
+ HTTP error bodies are returned unchanged but not saved in that ring. Model
128
+ terminal diagnostics and their counters retain their existing meaning. The
129
+ dashboard merges recent HTTP, model and request-timeline failures for display.
96
130
 
97
131
  Tests cover module dependency direction, default-off behavior, concurrent writers,
98
132
  proxy handshakes, TLS validation, streaming, history isolation and release lookup.
99
133
  Performance measurements distinguish request preparation from model latency.
100
134
  Release reports describe a specific environment, not an SLA or a guarantee of
101
135
  compatibility with every future client or corporate network policy.
136
+ CI runs Node 22.15 and 24 on Linux, Windows and macOS. The owned temporary-prefix
137
+ package smoke installs 0.9.31, upgrades to the packed candidate and exercises
138
+ installed sharp without provider calls. It does not claim a live Codex UI test
139
+ or the GitHub updater's network installation; the Windows command chain has a
140
+ separate actual-process fixture. Direct runtime dependencies are exact versions;
141
+ the lockfile fixes CI transitives, not consumers' future transitive resolution.
package/docs/README.md CHANGED
@@ -17,6 +17,7 @@ These reports record a specific release and test environment. Their version,
17
17
  test counts, timings, live-provider observations, and limitations remain
18
18
  historical facts rather than current guarantees.
19
19
 
20
+ - [0.9.31: verified Windows package-update process launch](RELEASE_0.9.31.md)
20
21
  - [0.9.30: persistent prediction routes and verified macOS launch](RELEASE_0.9.30.md)
21
22
  - [0.9.29: visible-page refresh, atom favicon and safe reasoning declarations](RELEASE_0.9.29.md)
22
23
  - [0.9.28: verified local plaintext recovery and validation boundaries](RELEASE_0.9.28.md)
package/docs/REFERENCE.md CHANGED
@@ -207,6 +207,16 @@ Contention fails with a retry message instead of stealing a live lock. Other
207
207
  applications do not participate in these locks, so snapshot conflict checks still
208
208
  apply; the locks do not claim a global filesystem transaction.
209
209
 
210
+ Since `0.9.33`, local settings/auth metadata reads are capped at 1 MiB, token
211
+ files at 64 KiB, and saved model catalog files at 9 MiB including metadata.
212
+ Oversized files remain untouched. Existing strict readers reject them; optional
213
+ cache readers treat them as unusable. Conversation files, HTTP request limits
214
+ and runtime history/cache limits are unchanged.
215
+ Full `ccdx doctor` reports npm's global installation target and readonly credential
216
+ permission evidence. Windows checks existing NTFS allow entries for other
217
+ identities, without changing ACLs. This is not a full effective-access audit;
218
+ unavailable checks warn. `doctor config` performs neither npm nor ACL probes.
219
+
210
220
  ### Core adapter
211
221
 
212
222
  One in-process adapter listens on `127.0.0.1:2026` by default and exposes:
@@ -311,7 +321,7 @@ npm exec --yes --package=codex-copilot-dx@latest -- ccdx
311
321
 
312
322
  On a normal launch, CCDX:
313
323
 
314
- 1. Prints the installed package version and checks for a newer npm release in the background.
324
+ 1. Prints the installed package version and checks GitHub's latest stable release in the background (not npm).
315
325
  2. Reuses a compatible running adapter when available; otherwise it reuses a compatible local Copilot credential or starts GitHub Device Flow when authentication is required.
316
326
  3. Loads a usable model cache or attempts a live refresh, then starts listening. A cache older than two hours refreshes in the background; a fresh cache can be used immediately. A failed refresh retains the last-known-good list when one is available.
317
327
  4. Checks the startup-managed settings in `CODEX_HOME/config.toml` (default `~/.codex/config.toml`), including the local `/v1` endpoint.
@@ -366,6 +376,10 @@ ccdx models
366
376
 
367
377
  This performs a fresh, read-only GitHub Copilot model-directory lookup without starting the adapter, opening Device Flow, reading the local model cache, or consuming an inference request. It lists selectable GPT model IDs, providers, advertised APIs, and preview status. Catalog availability does not guarantee that a later inference request will avoid quota, rate-limit, or policy enforcement.
368
378
 
379
+ Concurrent identical live lookups share only the active request. Caller
380
+ cancellation is independent; results are not retained as a fresh catalog after
381
+ completion. The dashboard cancels its waiter when the read is abandoned.
382
+
369
383
  Interactive terminals use aligned tables for `models`, `auth status`, and `usage`. Redirected or piped output retains the plain-text layout for scripts; use `--format table` or `--format plain` when a command offers an explicit format override.
370
384
 
371
385
  `ccdx usage` and the dashboard Model Usage table show token cache hit rate for each model and the aggregate: recorded cached input tokens divided by recorded input tokens, weighted by token count rather than averaging request percentages. This describes the upstream prompt cache; the local history and image-transform caches are separate. Incomplete historical records do not hide a computable ratio: `~` marks a rate derived from incomplete counts. A rate is `—` when input tokens are zero, usable totals are missing, or token counts are invalid. Older logs may omit explicit zero cache counts; new Responses usage records retain reported zeros. CLI tables keep existing token columns on narrow terminals and show rates below the table when the extra column does not fit.
@@ -491,6 +505,29 @@ ccdx update npm
491
505
  ccdx update github
492
506
  ```
493
507
 
508
+ In Windows PowerShell, use `ccdx.cmd update github` (or `ccdx.cmd update npm`)
509
+ when script policy blocks npm's `.ps1` shim. Since `0.9.31`, the updater runs
510
+ `npm.cmd` through the system `cmd.exe`, with AutoRun and delayed expansion
511
+ disabled, fixed installer arguments and a validated stable release tag.
512
+ It does not enable Node's generic `shell` option, change PowerShell policy,
513
+ rewrite npm configuration or add an external dependency. The caller's PATH,
514
+ registry, proxy, prefix/cache settings and terminal streams are preserved.
515
+ macOS/Linux retain direct `npm` execution and separate argument arrays.
516
+
517
+ Versions through `0.9.30` can fail with `spawn EINVAL` before the Windows
518
+ installer starts. To bootstrap this fix, run the installer directly:
519
+
520
+ ```powershell
521
+ npm.cmd install -g --allow-git=all 'github:DaleXiao/codex-copilot-dx#v0.9.33'
522
+ ccdx.cmd version
523
+ ```
524
+
525
+ This GitHub installation still requires Git on PATH. Stop/restart the running
526
+ adapter after installation; installation alone does not update a running process.
527
+ Installer errors and nonzero exits fail the update without a success message or
528
+ automatic retry. Missing Git, blocked dependency downloads or npm cache-only
529
+ settings remain npm/environment errors, not fixed by changing the launcher.
530
+
494
531
  Normal startup checks the official GitHub `releases/latest` web endpoint once in
495
532
  the background, without accessing the npm registry or REST API. The anonymous
496
533
  check requires no PAT or Copilot credentials, has a two-second deadline, validates
@@ -620,6 +657,15 @@ The status endpoint is restricted to the socket's real loopback address even whe
620
657
 
621
658
  `stream_performance.recent_requests` retains at most 20 finished Responses/compact requests. Each entry contains a CCDX-owned request ID, start timestamp, bounded model/route labels, HTTP status, final model outcome, known error origin, last observed phase and provider-call count. `timings_ms` includes cumulative preparation durations and offsets from adapter entry for the first upstream dispatch, latest upstream headers, first output, latest observed upstream activity, terminal and finish. Null means not observed, not zero. Stage durations can overlap and should not be added into a total. Provider-call counts include compatibility attempts but exclude OAuth exchanges and low-level connection retries. Streams update a single activity timestamp per read; no content, headers, opaque state or unbounded event list is retained. Entries are process-local and reset on restart; normal status refresh reads them without new upstream calls or background polling.
622
659
 
660
+ `http_errors` separately counts HTTP failures on tracked API routes and retains
661
+ the latest 20. Entries contain HTTP status, technical code when safe, observed
662
+ model, route/source and request IDs; the message is a fixed local explanation.
663
+ They never retain the original body, prompt, URL query or headers. Original
664
+ errors are still returned unchanged. Management/dashboard reads are excluded.
665
+ The recent-error panel merges these entries with model failures and request
666
+ timelines, retaining at most ten visible items. HTTP counts do not change model
667
+ terminal counts; unknown sources/models remain unknown.
668
+
623
669
  Every API response includes a safe `X-Request-Id` for correlation. To include the same ID in related terminal and file log lines, start with:
624
670
 
625
671
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "0.9.30",
3
+ "version": "0.9.33",
4
4
  "description": "Use Codex App with GitHub Copilot",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -41,6 +41,7 @@
41
41
  "scripts": {
42
42
  "test": "node --test",
43
43
  "test:smoke": "node scripts/offline-smoke.mjs && node scripts/sse-idle-replay.mjs",
44
+ "test:package": "node scripts/package-lifecycle-smoke.mjs",
44
45
  "test:e2e": "bash test/e2e.sh",
45
46
  "bench": "node scripts/benchmark.mjs",
46
47
  "bench:payload": "node scripts/benchmark.mjs --large-payload",
@@ -50,7 +51,7 @@
50
51
  "prepublishOnly": "npm run verify"
51
52
  },
52
53
  "dependencies": {
53
- "sharp": "^0.35.3",
54
+ "sharp": "0.35.3",
54
55
  "smol-toml": "1.8.0"
55
56
  }
56
57
  }
package/src/adapter.mjs CHANGED
@@ -15,7 +15,7 @@ import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
15
15
  import { ADAPTER_HEALTH_PATH, adapterHealthPayload } from "./running-adapter.mjs";
16
16
  import { createResponsesCompactHandler, createResponsesHandler } from "./responses-handler.mjs";
17
17
  import { createResponsesImagePressureController } from "./responses-image-pressure.mjs";
18
- import { createResponseFailureDiagnostics } from "./response-failures.mjs";
18
+ import { createResponseFailureDiagnostics, buildHttpFailureDetails } from "./response-failures.mjs";
19
19
  import {
20
20
  ADAPTER_CACHE_PATH,
21
21
  cacheRuntimeSnapshot,
@@ -63,7 +63,7 @@ export {
63
63
  } from "./responses-request.mjs";
64
64
 
65
65
  const ADAPTER_RUNTIME_CONFIG = loadRuntimeConfig();
66
- const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/ui.js"]);
66
+ const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js"]);
67
67
  const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth"]);
68
68
 
69
69
  export function requestPath(reqUrl) {
@@ -170,6 +170,7 @@ export function createAdapterHandler(options = {}) {
170
170
  const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics();
171
171
  const imagePressure = options.imagePressure || createResponsesImagePressureController();
172
172
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
173
+ const httpErrors = createResponseFailureDiagnostics({ maxEntries: 20 });
173
174
  let imageMcpHandler = options.imageMcpHandler || null;
174
175
  const responsesHandler = createResponsesHandler({
175
176
  acquireRequest,
@@ -225,7 +226,7 @@ export function createAdapterHandler(options = {}) {
225
226
  return;
226
227
  }
227
228
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
228
- res.end(JSON.stringify(runtimeStatusPayload({
229
+ res.end(JSON.stringify({ ...runtimeStatusPayload({
229
230
  metrics: requestMetrics,
230
231
  streamPerformance: streamPerformanceMetrics,
231
232
  admission: acquireRequest,
@@ -237,7 +238,7 @@ export function createAdapterHandler(options = {}) {
237
238
  codexModelRegistry,
238
239
  codexModelCatalog,
239
240
  clientIntegrations: options.clientIntegrationSnapshot?.(),
240
- })));
241
+ }), http_errors: httpErrors.snapshot() }));
241
242
  return;
242
243
  }
243
244
 
@@ -402,9 +403,13 @@ export function createAdapterHandler(options = {}) {
402
403
  } catch {}
403
404
  }
404
405
  let requestFinished = false;
406
+ let httpEvidence = {}, context;
405
407
  const finishRequest = ({ statusCode = 0, aborted = false } = {}) => {
406
408
  if (requestFinished) return;
407
409
  requestFinished = true;
410
+ if (trackRequest && statusCode >= 400) {
411
+ try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model })); } catch {}
412
+ }
408
413
  try { complete({ statusCode, aborted }); } catch {}
409
414
  try { streamPerformance?.finish({ failed: aborted || statusCode >= 400, aborted, statusCode }); } catch {}
410
415
  try { finishTerminalActivity(); } catch {}
@@ -436,12 +441,14 @@ export function createAdapterHandler(options = {}) {
436
441
  }
437
442
 
438
443
  try {
439
- const result = runWithRequestContext({
444
+ context = {
440
445
  requestId,
441
446
  pathname,
442
447
  showRequestId: options.showRequestId === true,
443
448
  streamPerformance,
444
- }, () => dispatchRequest(req, res, pathname));
449
+ onHttpError: evidence => { httpEvidence = evidence; },
450
+ };
451
+ const result = runWithRequestContext(context, () => dispatchRequest(req, res, pathname));
445
452
  if (result && typeof result.then === "function") {
446
453
  return result.catch((error) => {
447
454
  containUnexpectedError(error);
@@ -0,0 +1,242 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { atomicWriteFilePairSync, atomicWriteFileSync } from "./atomic-file.mjs";
5
+ import { githubTokenFingerprint, normalizeGithubIdentity } from "./github-identity.mjs";
6
+ import { readBoundedFileSync, MAX_TOKEN_FILE_BYTES } from "./bounded-file.mjs";
7
+
8
+ const DISABLE_TOKEN_DISCOVERY_VALUES = new Set(["1", "true", "yes"]);
9
+ const MAX_AUTH_JSON_BYTES = 1024 * 1024;
10
+
11
+ export function githubTokenPath(home = os.homedir()) {
12
+ return path.join(home, ".local", "share", "copilot-api", "github_token");
13
+ }
14
+
15
+ export function githubTokenLockPath(home = os.homedir()) {
16
+ return `${githubTokenPath(home)}.lock`;
17
+ }
18
+
19
+ export function githubTokenMetadataPath(home = os.homedir()) {
20
+ return `${githubTokenPath(home)}.account.json`;
21
+ }
22
+
23
+ export function githubReauthMessage(reason, home = os.homedir()) {
24
+ const tokenPath = githubTokenPath(home);
25
+ return `${reason}
26
+ Delete the saved GitHub token, then run ccdx again to log in:
27
+ rm '${tokenPath}'
28
+ ccdx`;
29
+ }
30
+
31
+ function expandHome(filePath, home = os.homedir()) {
32
+ if (!filePath) return "";
33
+ if (filePath === "~") return home;
34
+ if (filePath.startsWith("~/")) return path.join(home, filePath.slice(2));
35
+ return filePath;
36
+ }
37
+
38
+ function isTokenDiscoveryDisabled(env = process.env) {
39
+ return DISABLE_TOKEN_DISCOVERY_VALUES.has(String(env.CCDX_DISABLE_TOKEN_DISCOVERY || "").toLowerCase());
40
+ }
41
+
42
+ function splitPathList(value) {
43
+ return String(value || "")
44
+ .split(path.delimiter)
45
+ .map((item) => item.trim())
46
+ .filter(Boolean);
47
+ }
48
+
49
+ function localAuthRoots(home, env = process.env) {
50
+ const roots = [
51
+ path.join(home, "Library", "Application Support"),
52
+ env.APPDATA ? expandHome(env.APPDATA, home) : "",
53
+ env.XDG_CONFIG_HOME ? expandHome(env.XDG_CONFIG_HOME, home) : path.join(home, ".config"),
54
+ ].filter(Boolean);
55
+ return [...new Set(roots)];
56
+ }
57
+
58
+ function addAuthJsonSource(sources, seen, filePath) {
59
+ if (seen.has(filePath)) return;
60
+ if (!fs.existsSync(filePath)) return;
61
+ seen.add(filePath);
62
+ sources.push({ type: "auth-json", path: filePath });
63
+ }
64
+
65
+ function localAuthJsonSources(home, env = process.env) {
66
+ const sources = [];
67
+ const seen = new Set();
68
+
69
+ for (const root of localAuthRoots(home, env)) {
70
+ let appDirs;
71
+ try {
72
+ appDirs = fs.readdirSync(root, { withFileTypes: true });
73
+ } catch {
74
+ continue;
75
+ }
76
+
77
+ for (const appDirent of appDirs) {
78
+ if (!appDirent.isDirectory()) continue;
79
+ const appDir = path.join(root, appDirent.name);
80
+ addAuthJsonSource(sources, seen, path.join(appDir, "auth.json"));
81
+
82
+ const profilesDir = path.join(appDir, "profiles");
83
+ let profileDirs;
84
+ try {
85
+ profileDirs = fs.readdirSync(profilesDir, { withFileTypes: true });
86
+ } catch {
87
+ continue;
88
+ }
89
+
90
+ for (const profileDirent of profileDirs) {
91
+ if (!profileDirent.isDirectory()) continue;
92
+ addAuthJsonSource(sources, seen, path.join(profilesDir, profileDirent.name, "auth.json"));
93
+ }
94
+ }
95
+ }
96
+
97
+ return sources;
98
+ }
99
+
100
+ function explicitTokenFileSources(home, env = process.env) {
101
+ const paths = [];
102
+ if (typeof env.CCDX_GITHUB_TOKEN_PATH === "string" && env.CCDX_GITHUB_TOKEN_PATH.trim()) {
103
+ paths.push(env.CCDX_GITHUB_TOKEN_PATH.trim());
104
+ }
105
+ paths.push(...splitPathList(env.CCDX_GITHUB_TOKEN_PATHS));
106
+
107
+ const seen = new Set();
108
+ return paths
109
+ .map((filePath) => expandHome(filePath, home))
110
+ .filter((filePath) => {
111
+ if (seen.has(filePath)) return false;
112
+ seen.add(filePath);
113
+ return true;
114
+ })
115
+ .map((filePath) => ({
116
+ type: "token-file",
117
+ name: "configured token file",
118
+ path: filePath,
119
+ }));
120
+ }
121
+
122
+ function looksLikeCopilotAuthJson(json) {
123
+ if (!json || typeof json !== "object") return false;
124
+ if (json.ghcAuth || json.gitHubTokens || json.githubToken || json.githubCopilot || json.copilot) return true;
125
+ return typeof json.access_token === "string" && Boolean(json.copilotAccess || json.copilotToken || json.copilot_token);
126
+ }
127
+
128
+ function readSmallJson(filePath) {
129
+ const stat = fs.statSync(filePath);
130
+ if (!stat.isFile() || stat.size > MAX_AUTH_JSON_BYTES) return null;
131
+ return JSON.parse(readBoundedFileSync(filePath, { encoding: "utf8", maxBytes: MAX_AUTH_JSON_BYTES }));
132
+ }
133
+
134
+ export function githubTokenSources({
135
+ home = os.homedir(),
136
+ env = process.env,
137
+ } = {}) {
138
+ if (isTokenDiscoveryDisabled(env)) return [];
139
+ const sources = [];
140
+ if (typeof env.CCDX_GITHUB_TOKEN === "string" && env.CCDX_GITHUB_TOKEN.trim()) {
141
+ sources.push({ type: "env", name: "CCDX_GITHUB_TOKEN", token: env.CCDX_GITHUB_TOKEN.trim() });
142
+ }
143
+ sources.push(...explicitTokenFileSources(home, env));
144
+ sources.push(...localAuthJsonSources(home, env));
145
+ return sources;
146
+ }
147
+
148
+ export function sourceDescription(source) {
149
+ if (!source) return "unknown source";
150
+ if (source.type === "env") return source.name;
151
+ if (source.type === "token-file") return `${source.name} (${source.path})`;
152
+ if (source.type === "auth-json") return `local auth file (${source.path})`;
153
+ return source.path || source.name || "unknown source";
154
+ }
155
+
156
+ export function extractGithubTokenFromAuthJson(json) {
157
+ const candidates = [
158
+ json?.ghcAuth?.gitHubTokens?.access_token,
159
+ json?.ghcAuth?.gitHubTokens?.accessToken,
160
+ json?.ghcAuth?.githubToken,
161
+ json?.gitHubTokens?.access_token,
162
+ json?.gitHubTokens?.accessToken,
163
+ json?.githubToken,
164
+ json?.access_token,
165
+ json?.accessToken,
166
+ ];
167
+ return candidates.find((value) => typeof value === "string" && value.trim())?.trim() || "";
168
+ }
169
+
170
+ export function readGithubTokenSource(source) {
171
+ if (source?.type === "env") return source.token || "";
172
+ if (source?.type === "token-file") return readBoundedFileSync(source.path, { encoding: "utf8", maxBytes: MAX_TOKEN_FILE_BYTES }).trim();
173
+ if (source?.type === "auth-json") {
174
+ const json = readSmallJson(source.path);
175
+ if (!looksLikeCopilotAuthJson(json)) return "";
176
+ return extractGithubTokenFromAuthJson(json);
177
+ }
178
+ return "";
179
+ }
180
+
181
+ export function readSavedGithubToken(home = os.homedir()) {
182
+ const filePath = githubTokenPath(home);
183
+ if (!fs.existsSync(filePath)) return "";
184
+ return readBoundedFileSync(filePath, { encoding: "utf8", maxBytes: MAX_TOKEN_FILE_BYTES }).trim();
185
+ }
186
+
187
+ export function readGithubTokenMetadata(home = os.homedir(), token = null) {
188
+ try {
189
+ const parsed = JSON.parse(readBoundedFileSync(githubTokenMetadataPath(home), { encoding: "utf8" }));
190
+ if (token && parsed.token_fingerprint !== githubTokenFingerprint(token)) return null;
191
+ const identity = normalizeGithubIdentity(parsed);
192
+ return identity ? { ...identity, token_fingerprint: parsed.token_fingerprint || "" } : null;
193
+ } catch {
194
+ return null;
195
+ }
196
+ }
197
+
198
+ function githubTokenMetadataData(identity, token, now = () => new Date()) {
199
+ const normalized = normalizeGithubIdentity(identity);
200
+ if (!normalized) return null;
201
+ const timestamp = now();
202
+ const updatedAt = timestamp instanceof Date ? timestamp.toISOString() : new Date(timestamp).toISOString();
203
+ return `${JSON.stringify({
204
+ ...normalized,
205
+ token_fingerprint: githubTokenFingerprint(token),
206
+ updated_at: updatedAt,
207
+ }, null, 2)}\n`;
208
+ }
209
+
210
+ export function writeGithubTokenMetadata(identity, home = os.homedir(), token = "", {
211
+ now = () => new Date(),
212
+ writeFile = atomicWriteFileSync,
213
+ } = {}) {
214
+ const metadata = githubTokenMetadataData(identity, token, now);
215
+ if (metadata === null) return false;
216
+ const filePath = githubTokenMetadataPath(home);
217
+ const directory = path.dirname(filePath);
218
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
219
+ fs.chmodSync(directory, 0o700);
220
+ writeFile(filePath, metadata, { mode: 0o600, preserveMode: false });
221
+ fs.chmodSync(filePath, 0o600);
222
+ return true;
223
+ }
224
+
225
+ export function writeToken(token, home = os.homedir(), identity = null, {
226
+ now = () => new Date(),
227
+ writeFile = atomicWriteFileSync,
228
+ unlinkFile = fs.unlinkSync,
229
+ } = {}) {
230
+ const GITHUB_TOKEN_PATH = githubTokenPath(home);
231
+ const directory = path.dirname(GITHUB_TOKEN_PATH);
232
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
233
+ fs.chmodSync(directory, 0o700);
234
+ atomicWriteFilePairSync(
235
+ GITHUB_TOKEN_PATH,
236
+ token,
237
+ githubTokenMetadataPath(home),
238
+ githubTokenMetadataData(identity, token, now),
239
+ { mode: 0o600, writeFile, unlinkFile },
240
+ );
241
+ }
242
+