codex-copilot-dx 0.9.31 → 0.9.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +8 -8
  2. package/bin/cli.mjs +37 -29
  3. package/docs/ARCHITECTURE.md +50 -2
  4. package/docs/REFERENCE.md +77 -8
  5. package/package.json +3 -2
  6. package/src/adapter.mjs +14 -7
  7. package/src/auth-credentials.mjs +242 -0
  8. package/src/auth-device-flow.mjs +210 -0
  9. package/src/auth-profile.mjs +2 -2
  10. package/src/auth.mjs +10 -450
  11. package/src/bounded-file.mjs +28 -0
  12. package/src/cli-status.mjs +2 -0
  13. package/src/client-integration.mjs +10 -3
  14. package/src/config.mjs +3 -2
  15. package/src/copilot.mjs +1 -1
  16. package/src/credential-permissions.mjs +21 -0
  17. package/src/dashboard/index.html +2 -0
  18. package/src/dashboard/language.js +3 -0
  19. package/src/dashboard/status.js +192 -0
  20. package/src/dashboard/ui.js +6 -343
  21. package/src/dashboard/usage.js +161 -0
  22. package/src/dashboard-api.mjs +5 -4
  23. package/src/dashboard.mjs +2 -0
  24. package/src/doctor.mjs +20 -0
  25. package/src/http-transport.mjs +7 -0
  26. package/src/image-provider-config.mjs +2 -2
  27. package/src/launcher.mjs +26 -16
  28. package/src/live-models.mjs +16 -0
  29. package/src/model-cache.mjs +2 -1
  30. package/src/native-prediction-profile.mjs +2 -1
  31. package/src/native-prediction-recovery.mjs +39 -0
  32. package/src/native-prediction-route.mjs +94 -0
  33. package/src/native-prediction-state.mjs +7 -1
  34. package/src/native-prediction-transport.mjs +6 -0
  35. package/src/native-prediction.mjs +42 -4
  36. package/src/package-update.mjs +44 -7
  37. package/src/profile-model-runtime.mjs +1 -1
  38. package/src/response-failures.mjs +7 -0
  39. package/src/startup-ui.mjs +54 -0
  40. package/src/status.mjs +1 -1
  41. package/src/stream-performance.mjs +4 -0
  42. package/src/user-settings.mjs +2 -2
  43. package/src/windows-prediction-network.mjs +1 -1
@@ -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
+
@@ -0,0 +1,210 @@
1
+ const CLIENT_ID = "Iv1.b507a08c87ecfe98"; // Public GitHub Copilot client ID.
2
+ const SCOPE = "read:user";
3
+ const ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
4
+ const DEFAULT_DEVICE_INTERVAL_SECONDS = 5;
5
+ const DEFAULT_DEVICE_EXPIRES_SECONDS = 900;
6
+ export const DEFAULT_DEVICE_CODE_TIMEOUT_MS = 30 * 1000;
7
+ const MAX_DEVICE_FLOW_JSON_BYTES = 64 * 1024;
8
+
9
+ // Map GitHub polling responses to a small local state machine.
10
+ export function interpretPoll(data) {
11
+ if (typeof data.access_token === "string" && data.access_token) return { state: "done", token: data.access_token };
12
+ switch (data.error) {
13
+ case "authorization_pending": return { state: "wait" };
14
+ case "slow_down": return { state: "slow" };
15
+ default: return { state: "fail", error: data.error || "unknown" };
16
+ }
17
+ }
18
+
19
+ export function abortError(signal) {
20
+ if (signal?.reason instanceof Error) return signal.reason;
21
+ const error = new Error("The operation was aborted");
22
+ error.name = "AbortError";
23
+ return error;
24
+ }
25
+
26
+ export function sleep(ms, { signal } = {}) {
27
+ if (signal?.aborted) return Promise.reject(abortError(signal));
28
+ return new Promise((resolve, reject) => {
29
+ const cleanup = () => signal?.removeEventListener("abort", onAbort);
30
+ const onAbort = () => {
31
+ clearTimeout(timer);
32
+ cleanup();
33
+ reject(abortError(signal));
34
+ };
35
+ const timer = setTimeout(() => {
36
+ cleanup();
37
+ resolve();
38
+ }, ms);
39
+ signal?.addEventListener("abort", onAbort, { once: true });
40
+ });
41
+ }
42
+
43
+ export function awaitWithSignal(operation, signal) {
44
+ if (signal?.aborted) return Promise.reject(abortError(signal));
45
+ return new Promise((resolve, reject) => {
46
+ const cleanup = () => signal?.removeEventListener("abort", onAbort);
47
+ const finish = (callback, value) => {
48
+ cleanup();
49
+ callback(value);
50
+ };
51
+ const onAbort = () => finish(reject, abortError(signal));
52
+ signal?.addEventListener("abort", onAbort, { once: true });
53
+ Promise.resolve()
54
+ .then(operation)
55
+ .then((value) => finish(resolve, value), (error) => finish(reject, error));
56
+ });
57
+ }
58
+
59
+ async function discardBoundedResponseBody(response) {
60
+ const transport = await import("./http-transport.mjs");
61
+ return transport.discardBoundedResponseBody(response);
62
+ }
63
+
64
+ async function readDeviceFlowJson(response, signal, label) {
65
+ if (typeof response?.body?.getReader === "function") {
66
+ const transport = await import("./http-transport.mjs");
67
+ const text = await awaitWithSignal(() => transport.readBoundedResponseText(response, {
68
+ maxBytes: MAX_DEVICE_FLOW_JSON_BYTES,
69
+ label,
70
+ }), signal);
71
+ return JSON.parse(text);
72
+ }
73
+ return awaitWithSignal(() => response.json(), signal);
74
+ }
75
+
76
+ export function cancelResponseBody(response) {
77
+ try { Promise.resolve(response?.body?.cancel?.()).catch(() => {}); } catch {}
78
+ }
79
+
80
+ function deviceCodeTimeoutError(timeoutMs) {
81
+ const error = new Error(`Device code request timed out after ${timeoutMs}ms`);
82
+ error.code = "CCDX_DEVICE_CODE_TIMEOUT";
83
+ return error;
84
+ }
85
+
86
+ export async function requestGithubDeviceCode({
87
+ fetchImpl = fetch,
88
+ signal,
89
+ timeoutMs = DEFAULT_DEVICE_CODE_TIMEOUT_MS,
90
+ } = {}) {
91
+ const parsedTimeout = Number(timeoutMs);
92
+ const deadlineMs = Number.isFinite(parsedTimeout) && parsedTimeout > 0
93
+ ? parsedTimeout
94
+ : DEFAULT_DEVICE_CODE_TIMEOUT_MS;
95
+ const controller = new AbortController();
96
+ let response;
97
+ const onCallerAbort = () => controller.abort(signal.reason);
98
+ signal?.addEventListener("abort", onCallerAbort, { once: true });
99
+ if (signal?.aborted) onCallerAbort();
100
+ const timer = setTimeout(() => controller.abort(deviceCodeTimeoutError(deadlineMs)), deadlineMs);
101
+ try {
102
+ response = await awaitWithSignal(() => fetchImpl("https://github.com/login/device/code", {
103
+ method: "POST",
104
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
105
+ body: JSON.stringify({ client_id: CLIENT_ID, scope: SCOPE }),
106
+ signal: controller.signal,
107
+ }), controller.signal);
108
+ if (!response.ok) {
109
+ await awaitWithSignal(() => discardBoundedResponseBody(response), controller.signal);
110
+ return { response, data: null, jsonError: null };
111
+ }
112
+ try {
113
+ const data = await readDeviceFlowJson(response, controller.signal, "Device code response");
114
+ return { response, data, jsonError: null };
115
+ } catch (error) {
116
+ if (controller.signal.aborted) throw error;
117
+ return { response, data: null, jsonError: error };
118
+ }
119
+ } catch (error) {
120
+ cancelResponseBody(response);
121
+ if (signal?.aborted) throw abortError(signal);
122
+ if (controller.signal.aborted) throw abortError(controller.signal);
123
+ throw error;
124
+ } finally {
125
+ clearTimeout(timer);
126
+ signal?.removeEventListener("abort", onCallerAbort);
127
+ }
128
+ }
129
+
130
+ export async function pollGithubDeviceFlow({
131
+ deviceCode,
132
+ interval,
133
+ expiresIn,
134
+ fetchImpl = fetch,
135
+ signal,
136
+ sleepImpl = sleep,
137
+ now = Date.now,
138
+ } = {}) {
139
+ const parsedInterval = Number(interval);
140
+ const parsedExpires = Number(expiresIn);
141
+ let waitMs = (Number.isFinite(parsedInterval) && parsedInterval > 0
142
+ ? parsedInterval
143
+ : DEFAULT_DEVICE_INTERVAL_SECONDS) * 1000;
144
+ const expiresMs = (Number.isFinite(parsedExpires) && parsedExpires > 0
145
+ ? parsedExpires
146
+ : DEFAULT_DEVICE_EXPIRES_SECONDS) * 1000;
147
+ const deadline = now() + expiresMs;
148
+
149
+ while (true) {
150
+ const remainingMs = deadline - now();
151
+ if (remainingMs <= 0) return { state: "expired" };
152
+ await sleepImpl(Math.min(waitMs, remainingMs), { signal });
153
+ if (signal?.aborted) throw abortError(signal);
154
+ if (now() >= deadline) return { state: "expired" };
155
+
156
+ const pollController = new AbortController();
157
+ let deadlineExpired = false;
158
+ const onCallerAbort = () => pollController.abort(signal.reason);
159
+ signal?.addEventListener("abort", onCallerAbort, { once: true });
160
+ if (signal?.aborted) onCallerAbort();
161
+ const deadlineTimer = setTimeout(() => {
162
+ deadlineExpired = true;
163
+ pollController.abort();
164
+ }, Math.max(1, deadline - now()));
165
+ let result;
166
+ let pollResponse;
167
+ try {
168
+ pollResponse = await fetchImpl(ACCESS_TOKEN_URL, {
169
+ method: "POST",
170
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
171
+ body: JSON.stringify({
172
+ client_id: CLIENT_ID,
173
+ device_code: deviceCode,
174
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
175
+ }),
176
+ signal: pollController.signal,
177
+ });
178
+ if (now() >= deadline) {
179
+ await awaitWithSignal(() => discardBoundedResponseBody(pollResponse), pollController.signal);
180
+ return { state: "expired" };
181
+ }
182
+ if (!pollResponse.ok) {
183
+ await awaitWithSignal(() => discardBoundedResponseBody(pollResponse), pollController.signal);
184
+ if (now() >= deadline) return { state: "expired" };
185
+ continue;
186
+ }
187
+ result = interpretPoll(await readDeviceFlowJson(
188
+ pollResponse,
189
+ pollController.signal,
190
+ "Device Flow poll response",
191
+ ));
192
+ if (now() >= deadline) return { state: "expired" };
193
+ } catch (error) {
194
+ cancelResponseBody(pollResponse);
195
+ if (signal?.aborted) throw abortError(signal);
196
+ if (deadlineExpired || now() >= deadline) return { state: "expired" };
197
+ throw error;
198
+ } finally {
199
+ clearTimeout(deadlineTimer);
200
+ signal?.removeEventListener("abort", onCallerAbort);
201
+ }
202
+ if (result.state === "slow") {
203
+ waitMs += 5000;
204
+ continue;
205
+ }
206
+ if (result.state !== "wait") return result;
207
+ }
208
+ }
209
+
210
+
@@ -1,5 +1,5 @@
1
- import fs from "node:fs";
2
1
  import os from "node:os";
2
+ import { readBoundedFileSync, MAX_TOKEN_FILE_BYTES } from "./bounded-file.mjs";
3
3
  import {
4
4
  githubTokenLockPath,
5
5
  githubTokenMetadataPath,
@@ -32,7 +32,7 @@ export function authProfilePaths(profile, { home = os.homedir() } = {}) {
32
32
 
33
33
  function readOptionalFile(filePath) {
34
34
  try {
35
- return { exists: true, data: fs.readFileSync(filePath) };
35
+ return { exists: true, data: readBoundedFileSync(filePath, { maxBytes: filePath.endsWith(".account.json") ? undefined : MAX_TOKEN_FILE_BYTES }) };
36
36
  } catch (error) {
37
37
  if (error?.code === "ENOENT") return { exists: false, data: null };
38
38
  throw error;