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/src/auth.mjs CHANGED
@@ -1,261 +1,22 @@
1
1
  import fs from "node:fs";
2
- import path from "node:path";
3
2
  import os from "node:os";
4
3
  import { spawn } from "node:child_process";
5
- import { atomicWriteFilePairSync, atomicWriteFileSync } from "./atomic-file.mjs";
6
- import {
7
- githubIdentityMatchesExpected,
8
- githubTokenFingerprint,
9
- normalizeGithubIdentity,
10
- } from "./github-identity.mjs";
4
+ import { githubIdentityMatchesExpected, normalizeGithubIdentity } from "./github-identity.mjs";
11
5
  import { parseSafePositiveInteger, parseTimerMs, RUNTIME_DEFAULTS } from "./runtime-config.mjs";
12
6
  import { status } from "./status.mjs";
13
7
  import { withFileLock } from "./lock.mjs";
8
+ import { githubTokenPath, githubTokenLockPath, readGithubTokenMetadata, readSavedGithubToken,
9
+ githubTokenSources, readGithubTokenSource, sourceDescription, writeGithubTokenMetadata, writeToken } from "./auth-credentials.mjs";
10
+ import { requestGithubDeviceCode, pollGithubDeviceFlow, awaitWithSignal, abortError, cancelResponseBody,
11
+ sleep, DEFAULT_DEVICE_CODE_TIMEOUT_MS } from "./auth-device-flow.mjs";
12
+ export { githubTokenPath, githubTokenLockPath, githubTokenMetadataPath, githubReauthMessage,
13
+ githubTokenSources, sourceDescription, extractGithubTokenFromAuthJson, readGithubTokenSource,
14
+ readGithubTokenMetadata, writeGithubTokenMetadata, writeToken } from "./auth-credentials.mjs";
15
+ export { interpretPoll, requestGithubDeviceCode, pollGithubDeviceFlow } from "./auth-device-flow.mjs";
14
16
 
15
- const CLIENT_ID = "Iv1.b507a08c87ecfe98"; // Public GitHub Copilot client ID.
16
- const SCOPE = "read:user";
17
17
  const GITHUB_API = "https://api.github.com";
18
18
  const COPILOT_TOKEN_URL = `${GITHUB_API}/copilot_internal/v2/token`;
19
- const ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
20
- const DEFAULT_DEVICE_INTERVAL_SECONDS = 5;
21
- const DEFAULT_DEVICE_EXPIRES_SECONDS = 900;
22
- const DEFAULT_DEVICE_CODE_TIMEOUT_MS = 30 * 1000;
23
19
  const DEFAULT_GITHUB_IDENTITY_TIMEOUT_MS = 30 * 1000;
24
- const MAX_DEVICE_FLOW_JSON_BYTES = 64 * 1024;
25
- const DISABLE_TOKEN_DISCOVERY_VALUES = new Set(["1", "true", "yes"]);
26
- const MAX_AUTH_JSON_BYTES = 1024 * 1024;
27
-
28
- export function githubTokenPath(home = os.homedir()) {
29
- return path.join(home, ".local", "share", "copilot-api", "github_token");
30
- }
31
-
32
- export function githubTokenLockPath(home = os.homedir()) {
33
- return `${githubTokenPath(home)}.lock`;
34
- }
35
-
36
- export function githubTokenMetadataPath(home = os.homedir()) {
37
- return `${githubTokenPath(home)}.account.json`;
38
- }
39
-
40
- export function githubReauthMessage(reason, home = os.homedir()) {
41
- const tokenPath = githubTokenPath(home);
42
- return `${reason}
43
- Delete the saved GitHub token, then run ccdx again to log in:
44
- rm '${tokenPath}'
45
- ccdx`;
46
- }
47
-
48
- // Map GitHub polling responses to a small local state machine.
49
- export function interpretPoll(data) {
50
- if (typeof data.access_token === "string" && data.access_token) return { state: "done", token: data.access_token };
51
- switch (data.error) {
52
- case "authorization_pending": return { state: "wait" };
53
- case "slow_down": return { state: "slow" };
54
- default: return { state: "fail", error: data.error || "unknown" };
55
- }
56
- }
57
-
58
- function abortError(signal) {
59
- if (signal?.reason instanceof Error) return signal.reason;
60
- const error = new Error("The operation was aborted");
61
- error.name = "AbortError";
62
- return error;
63
- }
64
-
65
- function sleep(ms, { signal } = {}) {
66
- if (signal?.aborted) return Promise.reject(abortError(signal));
67
- return new Promise((resolve, reject) => {
68
- const cleanup = () => signal?.removeEventListener("abort", onAbort);
69
- const onAbort = () => {
70
- clearTimeout(timer);
71
- cleanup();
72
- reject(abortError(signal));
73
- };
74
- const timer = setTimeout(() => {
75
- cleanup();
76
- resolve();
77
- }, ms);
78
- signal?.addEventListener("abort", onAbort, { once: true });
79
- });
80
- }
81
-
82
- function awaitWithSignal(operation, signal) {
83
- if (signal?.aborted) return Promise.reject(abortError(signal));
84
- return new Promise((resolve, reject) => {
85
- const cleanup = () => signal?.removeEventListener("abort", onAbort);
86
- const finish = (callback, value) => {
87
- cleanup();
88
- callback(value);
89
- };
90
- const onAbort = () => finish(reject, abortError(signal));
91
- signal?.addEventListener("abort", onAbort, { once: true });
92
- Promise.resolve()
93
- .then(operation)
94
- .then((value) => finish(resolve, value), (error) => finish(reject, error));
95
- });
96
- }
97
-
98
- async function discardBoundedResponseBody(response) {
99
- const transport = await import("./http-transport.mjs");
100
- return transport.discardBoundedResponseBody(response);
101
- }
102
-
103
- async function readDeviceFlowJson(response, signal, label) {
104
- if (typeof response?.body?.getReader === "function") {
105
- const transport = await import("./http-transport.mjs");
106
- const text = await awaitWithSignal(() => transport.readBoundedResponseText(response, {
107
- maxBytes: MAX_DEVICE_FLOW_JSON_BYTES,
108
- label,
109
- }), signal);
110
- return JSON.parse(text);
111
- }
112
- return awaitWithSignal(() => response.json(), signal);
113
- }
114
-
115
- function cancelResponseBody(response) {
116
- try { Promise.resolve(response?.body?.cancel?.()).catch(() => {}); } catch {}
117
- }
118
-
119
- function deviceCodeTimeoutError(timeoutMs) {
120
- const error = new Error(`Device code request timed out after ${timeoutMs}ms`);
121
- error.code = "CCDX_DEVICE_CODE_TIMEOUT";
122
- return error;
123
- }
124
-
125
- export async function requestGithubDeviceCode({
126
- fetchImpl = fetch,
127
- signal,
128
- timeoutMs = DEFAULT_DEVICE_CODE_TIMEOUT_MS,
129
- } = {}) {
130
- const parsedTimeout = Number(timeoutMs);
131
- const deadlineMs = Number.isFinite(parsedTimeout) && parsedTimeout > 0
132
- ? parsedTimeout
133
- : DEFAULT_DEVICE_CODE_TIMEOUT_MS;
134
- const controller = new AbortController();
135
- let response;
136
- const onCallerAbort = () => controller.abort(signal.reason);
137
- signal?.addEventListener("abort", onCallerAbort, { once: true });
138
- if (signal?.aborted) onCallerAbort();
139
- const timer = setTimeout(() => controller.abort(deviceCodeTimeoutError(deadlineMs)), deadlineMs);
140
- try {
141
- response = await awaitWithSignal(() => fetchImpl("https://github.com/login/device/code", {
142
- method: "POST",
143
- headers: { "Content-Type": "application/json", Accept: "application/json" },
144
- body: JSON.stringify({ client_id: CLIENT_ID, scope: SCOPE }),
145
- signal: controller.signal,
146
- }), controller.signal);
147
- if (!response.ok) {
148
- await awaitWithSignal(() => discardBoundedResponseBody(response), controller.signal);
149
- return { response, data: null, jsonError: null };
150
- }
151
- try {
152
- const data = await readDeviceFlowJson(response, controller.signal, "Device code response");
153
- return { response, data, jsonError: null };
154
- } catch (error) {
155
- if (controller.signal.aborted) throw error;
156
- return { response, data: null, jsonError: error };
157
- }
158
- } catch (error) {
159
- cancelResponseBody(response);
160
- if (signal?.aborted) throw abortError(signal);
161
- if (controller.signal.aborted) throw abortError(controller.signal);
162
- throw error;
163
- } finally {
164
- clearTimeout(timer);
165
- signal?.removeEventListener("abort", onCallerAbort);
166
- }
167
- }
168
-
169
- export async function pollGithubDeviceFlow({
170
- deviceCode,
171
- interval,
172
- expiresIn,
173
- fetchImpl = fetch,
174
- signal,
175
- sleepImpl = sleep,
176
- now = Date.now,
177
- } = {}) {
178
- const parsedInterval = Number(interval);
179
- const parsedExpires = Number(expiresIn);
180
- let waitMs = (Number.isFinite(parsedInterval) && parsedInterval > 0
181
- ? parsedInterval
182
- : DEFAULT_DEVICE_INTERVAL_SECONDS) * 1000;
183
- const expiresMs = (Number.isFinite(parsedExpires) && parsedExpires > 0
184
- ? parsedExpires
185
- : DEFAULT_DEVICE_EXPIRES_SECONDS) * 1000;
186
- const deadline = now() + expiresMs;
187
-
188
- while (true) {
189
- const remainingMs = deadline - now();
190
- if (remainingMs <= 0) return { state: "expired" };
191
- await sleepImpl(Math.min(waitMs, remainingMs), { signal });
192
- if (signal?.aborted) throw abortError(signal);
193
- if (now() >= deadline) return { state: "expired" };
194
-
195
- const pollController = new AbortController();
196
- let deadlineExpired = false;
197
- const onCallerAbort = () => pollController.abort(signal.reason);
198
- signal?.addEventListener("abort", onCallerAbort, { once: true });
199
- if (signal?.aborted) onCallerAbort();
200
- const deadlineTimer = setTimeout(() => {
201
- deadlineExpired = true;
202
- pollController.abort();
203
- }, Math.max(1, deadline - now()));
204
- let result;
205
- let pollResponse;
206
- try {
207
- pollResponse = await fetchImpl(ACCESS_TOKEN_URL, {
208
- method: "POST",
209
- headers: { "Content-Type": "application/json", Accept: "application/json" },
210
- body: JSON.stringify({
211
- client_id: CLIENT_ID,
212
- device_code: deviceCode,
213
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
214
- }),
215
- signal: pollController.signal,
216
- });
217
- if (now() >= deadline) {
218
- await awaitWithSignal(() => discardBoundedResponseBody(pollResponse), pollController.signal);
219
- return { state: "expired" };
220
- }
221
- if (!pollResponse.ok) {
222
- await awaitWithSignal(() => discardBoundedResponseBody(pollResponse), pollController.signal);
223
- if (now() >= deadline) return { state: "expired" };
224
- continue;
225
- }
226
- result = interpretPoll(await readDeviceFlowJson(
227
- pollResponse,
228
- pollController.signal,
229
- "Device Flow poll response",
230
- ));
231
- if (now() >= deadline) return { state: "expired" };
232
- } catch (error) {
233
- cancelResponseBody(pollResponse);
234
- if (signal?.aborted) throw abortError(signal);
235
- if (deadlineExpired || now() >= deadline) return { state: "expired" };
236
- throw error;
237
- } finally {
238
- clearTimeout(deadlineTimer);
239
- signal?.removeEventListener("abort", onCallerAbort);
240
- }
241
- if (result.state === "slow") {
242
- waitMs += 5000;
243
- continue;
244
- }
245
- if (result.state !== "wait") return result;
246
- }
247
- }
248
-
249
- function expandHome(filePath, home = os.homedir()) {
250
- if (!filePath) return "";
251
- if (filePath === "~") return home;
252
- if (filePath.startsWith("~/")) return path.join(home, filePath.slice(2));
253
- return filePath;
254
- }
255
-
256
- function isTokenDiscoveryDisabled(env = process.env) {
257
- return DISABLE_TOKEN_DISCOVERY_VALUES.has(String(env.CCDX_DISABLE_TOKEN_DISCOVERY || "").toLowerCase());
258
- }
259
20
 
260
21
  function tokenLockOptions(env = process.env) {
261
22
  return {
@@ -264,162 +25,6 @@ function tokenLockOptions(env = process.env) {
264
25
  };
265
26
  }
266
27
 
267
- function splitPathList(value) {
268
- return String(value || "")
269
- .split(path.delimiter)
270
- .map((item) => item.trim())
271
- .filter(Boolean);
272
- }
273
-
274
- function localAuthRoots(home, env = process.env) {
275
- const roots = [
276
- path.join(home, "Library", "Application Support"),
277
- env.APPDATA ? expandHome(env.APPDATA, home) : "",
278
- env.XDG_CONFIG_HOME ? expandHome(env.XDG_CONFIG_HOME, home) : path.join(home, ".config"),
279
- ].filter(Boolean);
280
- return [...new Set(roots)];
281
- }
282
-
283
- function addAuthJsonSource(sources, seen, filePath) {
284
- if (seen.has(filePath)) return;
285
- if (!fs.existsSync(filePath)) return;
286
- seen.add(filePath);
287
- sources.push({ type: "auth-json", path: filePath });
288
- }
289
-
290
- function localAuthJsonSources(home, env = process.env) {
291
- const sources = [];
292
- const seen = new Set();
293
-
294
- for (const root of localAuthRoots(home, env)) {
295
- let appDirs;
296
- try {
297
- appDirs = fs.readdirSync(root, { withFileTypes: true });
298
- } catch {
299
- continue;
300
- }
301
-
302
- for (const appDirent of appDirs) {
303
- if (!appDirent.isDirectory()) continue;
304
- const appDir = path.join(root, appDirent.name);
305
- addAuthJsonSource(sources, seen, path.join(appDir, "auth.json"));
306
-
307
- const profilesDir = path.join(appDir, "profiles");
308
- let profileDirs;
309
- try {
310
- profileDirs = fs.readdirSync(profilesDir, { withFileTypes: true });
311
- } catch {
312
- continue;
313
- }
314
-
315
- for (const profileDirent of profileDirs) {
316
- if (!profileDirent.isDirectory()) continue;
317
- addAuthJsonSource(sources, seen, path.join(profilesDir, profileDirent.name, "auth.json"));
318
- }
319
- }
320
- }
321
-
322
- return sources;
323
- }
324
-
325
- function explicitTokenFileSources(home, env = process.env) {
326
- const paths = [];
327
- if (typeof env.CCDX_GITHUB_TOKEN_PATH === "string" && env.CCDX_GITHUB_TOKEN_PATH.trim()) {
328
- paths.push(env.CCDX_GITHUB_TOKEN_PATH.trim());
329
- }
330
- paths.push(...splitPathList(env.CCDX_GITHUB_TOKEN_PATHS));
331
-
332
- const seen = new Set();
333
- return paths
334
- .map((filePath) => expandHome(filePath, home))
335
- .filter((filePath) => {
336
- if (seen.has(filePath)) return false;
337
- seen.add(filePath);
338
- return true;
339
- })
340
- .map((filePath) => ({
341
- type: "token-file",
342
- name: "configured token file",
343
- path: filePath,
344
- }));
345
- }
346
-
347
- function looksLikeCopilotAuthJson(json) {
348
- if (!json || typeof json !== "object") return false;
349
- if (json.ghcAuth || json.gitHubTokens || json.githubToken || json.githubCopilot || json.copilot) return true;
350
- return typeof json.access_token === "string" && Boolean(json.copilotAccess || json.copilotToken || json.copilot_token);
351
- }
352
-
353
- function readSmallJson(filePath) {
354
- const stat = fs.statSync(filePath);
355
- if (!stat.isFile() || stat.size > MAX_AUTH_JSON_BYTES) return null;
356
- return JSON.parse(fs.readFileSync(filePath, "utf8"));
357
- }
358
-
359
- export function githubTokenSources({
360
- home = os.homedir(),
361
- env = process.env,
362
- } = {}) {
363
- if (isTokenDiscoveryDisabled(env)) return [];
364
- const sources = [];
365
- if (typeof env.CCDX_GITHUB_TOKEN === "string" && env.CCDX_GITHUB_TOKEN.trim()) {
366
- sources.push({ type: "env", name: "CCDX_GITHUB_TOKEN", token: env.CCDX_GITHUB_TOKEN.trim() });
367
- }
368
- sources.push(...explicitTokenFileSources(home, env));
369
- sources.push(...localAuthJsonSources(home, env));
370
- return sources;
371
- }
372
-
373
- export function sourceDescription(source) {
374
- if (!source) return "unknown source";
375
- if (source.type === "env") return source.name;
376
- if (source.type === "token-file") return `${source.name} (${source.path})`;
377
- if (source.type === "auth-json") return `local auth file (${source.path})`;
378
- return source.path || source.name || "unknown source";
379
- }
380
-
381
- export function extractGithubTokenFromAuthJson(json) {
382
- const candidates = [
383
- json?.ghcAuth?.gitHubTokens?.access_token,
384
- json?.ghcAuth?.gitHubTokens?.accessToken,
385
- json?.ghcAuth?.githubToken,
386
- json?.gitHubTokens?.access_token,
387
- json?.gitHubTokens?.accessToken,
388
- json?.githubToken,
389
- json?.access_token,
390
- json?.accessToken,
391
- ];
392
- return candidates.find((value) => typeof value === "string" && value.trim())?.trim() || "";
393
- }
394
-
395
- export function readGithubTokenSource(source) {
396
- if (source?.type === "env") return source.token || "";
397
- if (source?.type === "token-file") return fs.readFileSync(source.path, "utf8").trim();
398
- if (source?.type === "auth-json") {
399
- const json = readSmallJson(source.path);
400
- if (!looksLikeCopilotAuthJson(json)) return "";
401
- return extractGithubTokenFromAuthJson(json);
402
- }
403
- return "";
404
- }
405
-
406
- function readSavedGithubToken(home = os.homedir()) {
407
- const filePath = githubTokenPath(home);
408
- if (!fs.existsSync(filePath)) return "";
409
- return fs.readFileSync(filePath, "utf8").trim();
410
- }
411
-
412
- export function readGithubTokenMetadata(home = os.homedir(), token = null) {
413
- try {
414
- const parsed = JSON.parse(fs.readFileSync(githubTokenMetadataPath(home), "utf8"));
415
- if (token && parsed.token_fingerprint !== githubTokenFingerprint(token)) return null;
416
- const identity = normalizeGithubIdentity(parsed);
417
- return identity ? { ...identity, token_fingerprint: parsed.token_fingerprint || "" } : null;
418
- } catch {
419
- return null;
420
- }
421
- }
422
-
423
28
  function expectedGithubIdentity(home, env, token) {
424
29
  const configuredLogin = String(env.CCDX_GITHUB_LOGIN || "").trim();
425
30
  if (configuredLogin) return { login: configuredLogin };
@@ -696,7 +301,7 @@ export async function ensureAuth({
696
301
  } = {}) {
697
302
  const GITHUB_TOKEN_PATH = githubTokenPath(home);
698
303
  if (fs.existsSync(GITHUB_TOKEN_PATH)) {
699
- const existing = fs.readFileSync(GITHUB_TOKEN_PATH, "utf8").trim();
304
+ const existing = readSavedGithubToken(home);
700
305
  if (existing) {
701
306
  log(status("ok", "GitHub token found"));
702
307
  return;
@@ -763,48 +368,3 @@ export async function ensureAuth({
763
368
  throw new Error(`Login failed: ${result.error}`);
764
369
  }, tokenLockOptions(env));
765
370
  }
766
-
767
- function githubTokenMetadataData(identity, token, now = () => new Date()) {
768
- const normalized = normalizeGithubIdentity(identity);
769
- if (!normalized) return null;
770
- const timestamp = now();
771
- const updatedAt = timestamp instanceof Date ? timestamp.toISOString() : new Date(timestamp).toISOString();
772
- return `${JSON.stringify({
773
- ...normalized,
774
- token_fingerprint: githubTokenFingerprint(token),
775
- updated_at: updatedAt,
776
- }, null, 2)}\n`;
777
- }
778
-
779
- export function writeGithubTokenMetadata(identity, home = os.homedir(), token = "", {
780
- now = () => new Date(),
781
- writeFile = atomicWriteFileSync,
782
- } = {}) {
783
- const metadata = githubTokenMetadataData(identity, token, now);
784
- if (metadata === null) return false;
785
- const filePath = githubTokenMetadataPath(home);
786
- const directory = path.dirname(filePath);
787
- fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
788
- fs.chmodSync(directory, 0o700);
789
- writeFile(filePath, metadata, { mode: 0o600, preserveMode: false });
790
- fs.chmodSync(filePath, 0o600);
791
- return true;
792
- }
793
-
794
- export function writeToken(token, home = os.homedir(), identity = null, {
795
- now = () => new Date(),
796
- writeFile = atomicWriteFileSync,
797
- unlinkFile = fs.unlinkSync,
798
- } = {}) {
799
- const GITHUB_TOKEN_PATH = githubTokenPath(home);
800
- const directory = path.dirname(GITHUB_TOKEN_PATH);
801
- fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
802
- fs.chmodSync(directory, 0o700);
803
- atomicWriteFilePairSync(
804
- GITHUB_TOKEN_PATH,
805
- token,
806
- githubTokenMetadataPath(home),
807
- githubTokenMetadataData(identity, token, now),
808
- { mode: 0o600, writeFile, unlinkFile },
809
- );
810
- }
@@ -0,0 +1,28 @@
1
+ import fs from "node:fs";
2
+
3
+ export const MAX_SETTINGS_FILE_BYTES = 1024 * 1024;
4
+ export const MAX_TOKEN_FILE_BYTES = 64 * 1024;
5
+ export const MAX_MODEL_CACHE_FILE_BYTES = 9 * 1024 * 1024;
6
+
7
+ // Read one regular-file snapshot. Symlinks retain existing configuration
8
+ // semantics; this is a byte boundary, not an ownership or path-policy change.
9
+ export function readBoundedFileSync(filePath, { maxBytes = MAX_SETTINGS_FILE_BYTES, encoding } = {}) {
10
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError("Invalid local file byte limit");
11
+ const fd = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0));
12
+ try {
13
+ const stat = fs.fstatSync(fd);
14
+ if (!stat.isFile() || stat.size > maxBytes) {
15
+ const error = new Error("Local configuration file exceeds its read limit or is not a regular file");
16
+ error.code = "ccdx_local_file_limit";throw error;
17
+ }
18
+ const buffer = Buffer.alloc(stat.size + 1);
19
+ let size = 0, count;
20
+ while (size < buffer.length && (count = fs.readSync(fd, buffer, size, buffer.length - size, size)) > 0) size += count;
21
+ if (size > stat.size) {
22
+ const error = new Error("Local configuration file grew during reading; retry after the write finishes");
23
+ error.code = "ccdx_local_file_changed";throw error;
24
+ }
25
+ const value = buffer.subarray(0, size);
26
+ return encoding ? value.toString(encoding) : value;
27
+ } finally { fs.closeSync(fd); }
28
+ }
@@ -373,7 +373,7 @@ function topicHelp(name, topic) {
373
373
  "auto-review-model": `Usage:\n ${name} auto-review-model\n\nSelect a Responses model, then an advertised reasoning effort. Enter keeps the default/current choice; q cancels both steps without saving. Effort 0 follows the client (low when omitted). Settings apply only to Auto-review on the next request; no client patch or restart is required for adapters running 0.9.13 or newer.`,
374
374
  "suggestion": `The CCDX prediction panel has been retired. Run ${name} suggestion off to safely remove unchanged CCDX registrations. This cleanup does not change native predictions; see ${name} prediction --help for that separate opt-in feature.`,
375
375
  prediction: `Usage:\n ${name} prediction [status|on|off]\n\nOptional native next-message predictions; off by default. macOS and Windows. Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup. Quit Codex before on/off, then restart ccdx. On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com. HTTPS on those hosts is decrypted locally; only prediction configuration is changed. No client program files, OS trust, account permissions, MCP or Hooks are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved. Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD and CIDR bypass rules are reported as unsupported. The bridge port persists across restarts/updates; a busy saved port disables only predictions. Launch/reuse checks the App's actual route; an older random or missing route may require one full App quit. Official prediction configuration is preserved; the conversation's model is used. App updates require another compatibility check. Status distinguishes saved preference and observed config traffic from unverified candidate visibility.`,
376
- update: `Usage:\n ${name} update [npm|github]\n\nUpdates the global package from the configured npm registry or the latest stable GitHub release. With no source, an interactive terminal prompts for one.`,
376
+ update: `Usage:\n ${name} update [npm|github]\n\nUpdates the global package from the configured npm registry or the latest stable GitHub release. With no source, an interactive terminal prompts for one. Windows uses system cmd.exe to run npm.cmd without changing PowerShell policy; use the .cmd entrypoint if scripts are blocked. GitHub installs require Git on PATH and dependencies may still use the configured npm registry. Restart the running adapter after installation.`,
377
377
  version: `Usage:\n ${name} --version`,
378
378
  };
379
379
  return sections[topic];
@@ -187,6 +187,7 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
187
187
  lines.push(status("warn", ` ${model} ${code}: ${message}${failure.retried ? ` [retried:${retryPolicy}]` : ""}`));
188
188
  }
189
189
  }
190
+ if (data.http_errors) lines.push(status("info", `HTTP failures: ${count(data.http_errors.total)} observed (separate from model terminal events)`));
190
191
  lines.push(status("info", `Models: ${count(models.models)} total; Copilot token ${copilot.token_cached ? `cached (${duration(copilot.token_expires_in_ms)} remaining)` : "not cached"}`));
191
192
  const prediction = data.client_integrations?.prediction;
192
193
  if (prediction) {
@@ -0,0 +1,21 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { execFileSync } from "node:child_process";
4
+
5
+ // Explicit doctor-only evidence. Never rewrites ACLs or blocks service startup.
6
+ export function inspectCredentialPermissions(file, { platform = process.platform, env = process.env, exec = execFileSync } = {}) {
7
+ try {
8
+ const stat = fs.statSync(file);
9
+ if (!stat.isFile()) return "review";
10
+ if (platform !== "win32") return stat.mode & 0o077 ? "review" : "private";
11
+ const root = env.SystemRoot || env.WINDIR || "C:\\Windows";
12
+ const command = path.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
13
+ const script = "$ErrorActionPreference='Stop';$a=Get-Acl -LiteralPath $env:CCDX_PERMISSION_FILE;$me=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value;$trusted=@($me,'S-1-5-18','S-1-5-32-544');$b=@($a.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])|Where-Object {$_.AccessControlType -eq 'Allow' -and (($_.PropagationFlags -band 2) -eq 0) -and (($_.FileSystemRights -band 851975) -ne 0) -and ($trusted -notcontains $_.IdentityReference.Value)});@{review=($b.Count -gt 0)}|ConvertTo-Json -Compress";
14
+ const result = JSON.parse(exec(command, ["-NoProfile", "-NonInteractive", "-Command", script], {
15
+ env: { ...env, CCDX_PERMISSION_FILE: file, PSModulePath: path.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "Modules")
16
+ + (env.PSModulePath ? `;${env.PSModulePath}` : "") },
17
+ encoding: "utf8", shell: false, windowsHide: true, timeout: 3000, maxBuffer: 32 * 1024,
18
+ }));
19
+ return typeof result.review === "boolean" ? result.review ? "review" : "private" : "unavailable";
20
+ } catch (error) { return error.code === "ENOENT" ? "missing" : "unavailable"; }
21
+ }
@@ -9,6 +9,8 @@
9
9
  <script src="/theme.js"></script>
10
10
  <link rel="stylesheet" href="/ui.css">
11
11
  <script src="/refresh.js" defer></script>
12
+ <script src="/status.js" defer></script>
13
+ <script src="/usage.js" defer></script>
12
14
  <script src="/ui.js" defer></script>
13
15
  <title data-i18n>CCDX · Local dashboard</title>
14
16
  </head>
@@ -157,6 +157,8 @@
157
157
  "request_id": ["Local request ID", "本机编号"],
158
158
  "outcome": ["Result", "处理结果"],
159
159
  "origin": ["Reported by", "结果来源"],
160
+ "route": ["Request route", "请求入口"],
161
+ "HTTP request failed; original response was preserved.": ["HTTP request failed. The original error was returned.", "请求失败,已返回原始错误。"],
160
162
  "phase": ["Last step", "最后步骤"],
161
163
  "http_status": ["HTTP status", "返回状态"],
162
164
  "upstream_attempts": ["Send attempts", "发送次数"],