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.
@@ -5,6 +5,8 @@ import { isDeepStrictEqual } from "node:util";
5
5
  import { parse } from "smol-toml";
6
6
  import { computeUpdatedCodexConfig, initialCodexConfig } from "./config.mjs";
7
7
  import { adapterBaseUrl } from "./running-adapter.mjs";
8
+ import { withFileLockSync } from "./lock.mjs";
9
+ import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-file.mjs";
8
10
 
9
11
  const MANAGED_KEYS = [
10
12
  "openai_base_url",
@@ -165,3 +167,27 @@ export function inspectCodexConfig({ home = os.homedir(), env: processEnv = proc
165
167
  checks.push(startupPreview(content, config, host, port));
166
168
  return checks;
167
169
  }
170
+
171
+ export function repairCodexConfig(options = {}) {
172
+ const { host = "127.0.0.1", port = 2026 } = options;
173
+ const file = codexPaths(options).config;
174
+ return withFileLockSync(`${file}.ccdx.lock`, () => {
175
+ if (inspectCodexConfig(options).some(check => check.kind === "err")) {
176
+ return { status: "preserved", changed: false };
177
+ }
178
+ let content = null;
179
+ try { content = fs.readFileSync(file, "utf8"); } catch (error) { if (error.code !== "ENOENT") throw error; }
180
+ const next = content === null ? { content: initialCodexConfig(port, host), changed: true }
181
+ : computeUpdatedCodexConfig(content, port, host);
182
+ if (!next.changed) return { status: "unchanged", changed: false };
183
+ const before = content === null ? {} : parseConfig(content);
184
+ if (!isDeepStrictEqual(unmanagedSettings(before), unmanagedSettings(parseConfig(next.content)))) {
185
+ return { status: "preserved", changed: false };
186
+ }
187
+ if (content === null) atomicWriteFileIfChangedSync(file, next.content, { mode: 0o600 });
188
+ else atomicWriteFilePairSync(file, next.content, `${file}.ccdx-doctor.bak`, content, { mode: 0o600 });
189
+ const verified = !inspectCodexConfig(options).some(check => check.kind === "err"
190
+ || check.message.startsWith("Next startup would"));
191
+ return { status: verified ? "verified" : "needs_review", changed: true };
192
+ });
193
+ }
@@ -15,6 +15,7 @@ import {
15
15
  normalizeGithubIdentity,
16
16
  } from "./github-identity.mjs";
17
17
  import { status } from "./status.mjs";
18
+ import { cancelResponseBody } from "./auth-device-flow.mjs";
18
19
 
19
20
  const GITHUB_API = "https://api.github.com";
20
21
 
@@ -251,6 +252,7 @@ export function createCopilotTokenSession({
251
252
  throw error;
252
253
  }
253
254
  if (!response.ok) {
255
+ cancelResponseBody(response);
254
256
  if ((response.status === 401 || response.status === 403) && allowTokenDiscovery) {
255
257
  const imported = await importDiscoveredGithubToken({
256
258
  home: resolvedHome,
@@ -272,9 +274,23 @@ export function createCopilotTokenSession({
272
274
  }
273
275
  if (response.status === 401 || response.status === 403) {
274
276
  const prefix = profile === "codex" ? "Failed to get Copilot token" : `Failed to get Copilot token for ${profile} profile`;
275
- throw refreshError(formatReauth(`${prefix}: ${response.status}. The saved GitHub token may be expired, revoked, or missing Copilot access.`, resolvedHome), {
276
- statusCode: response.status,
277
- });
277
+ const reason = `${prefix}: ${response.status}.`;
278
+ if (!usesDefaultTokenStore || typeof reauthMessage === "function") {
279
+ throw refreshError(formatReauth(`${reason} The saved GitHub token may be expired, revoked, or missing Copilot access.`, resolvedHome), {
280
+ statusCode: response.status,
281
+ });
282
+ }
283
+ // A Copilot denial is not proof that the underlying GitHub credential
284
+ // expired. Only GitHub's own 401 can justify reauthorization guidance.
285
+ const identity = response.status === 401
286
+ ? await fetchGithubIdentity(credentials.token, { fetchImpl, signal, timeoutMs: 4000 }) : null;
287
+ if (signal?.aborted) throw abortError(signal);
288
+ const message = identity?.status === 401
289
+ ? formatReauth(`${reason} GitHub also rejected the saved credential.`, resolvedHome)
290
+ : `${reason} The saved GitHub credential was preserved. ${response.status === 403 || identity?.ok
291
+ ? "Check Copilot account access and network policy; this response does not establish that a new login is needed."
292
+ : "GitHub credential validity could not be confirmed; check network access before changing authentication."}`;
293
+ throw refreshError(message, { statusCode: response.status });
278
294
  }
279
295
  const prefix = profile === "codex" ? "Failed to get Copilot token" : `Failed to get Copilot token for ${profile} profile`;
280
296
  throw refreshError(`${prefix}: ${response.status}`, {
@@ -23,7 +23,7 @@
23
23
 
24
24
  <main>
25
25
  <section class="intro">
26
- <h1><svg class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg> ccdx status</h1>
26
+ <h1><svg id="status-icon" class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg> ccdx status</h1>
27
27
  <div class="snapshot-meta"><p id="auth-account" role="status" data-i18n data-i18n-title title="Saved GitHub Copilot account / local credentials only; not an online entitlement check.">GitHub / READING</p><p id="updated" data-i18n>Reading status…</p></div>
28
28
  </section>
29
29
 
@@ -2,7 +2,7 @@
2
2
  const interval = 30 * 60 * 1000;
3
3
  const freshness = 30 * 1000;
4
4
 
5
- function createController({ resources, visible, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
5
+ function createController({ resources, visible, onState = () => {}, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
6
6
  const states = new Map(Object.keys(resources).map(key => [key, {
7
7
  value: undefined, signature: undefined, variant: undefined, pending: null,
8
8
  updatedAt: null, attemptedAt: null, error: null, generation: 0, abort: null,
@@ -12,7 +12,11 @@
12
12
  let automatic = true;
13
13
  const state = key => states.get(key);
14
14
  const stopTimer = () => { if (timer !== null) clearTimer(timer); timer = null; };
15
- const notify = key => resources[key].state?.(state(key));
15
+ const notify = key => {
16
+ resources[key].state?.(state(key));
17
+ const pendingKeys = [...states.keys()].filter(name => state(name).pending);
18
+ onState({ pending: pendingKeys.length > 0, pendingKeys });
19
+ };
16
20
 
17
21
  function schedule() {
18
22
  stopTimer();
@@ -44,7 +48,6 @@
44
48
  entry.attemptedAt = now();
45
49
  entry.attemptVariant = variant;
46
50
  entry.pendingVariant = variant;
47
- entry.error = null;
48
51
  entry.pending = Promise.resolve().then(async () => {
49
52
  try {
50
53
  const value = await resource.load({ variant, signal: abort.signal });
@@ -56,6 +59,7 @@
56
59
  entry.signature = signature;
57
60
  entry.variant = variant;
58
61
  entry.updatedAt = now();
62
+ entry.error = null;
59
63
  return value;
60
64
  } catch (error) {
61
65
  if (active && generation === entry.generation) entry.error = error;
@@ -23,7 +23,17 @@ const loadAuth = () => dashboardRefresh.refresh("auth", { force: true });
23
23
 
24
24
  const refresh = () => dashboardRefresh.refresh("status", { force: true });
25
25
 
26
- element("refresh").addEventListener("click", () => dashboardRefresh.refreshVisible({ force: true }));
26
+ function animateRefresh() {
27
+ const icon = element("status-icon");
28
+ if (!icon || reducedMotion.matches || !icon.animate) return;
29
+ for (const animation of icon.getAnimations?.() || []) animation.cancel();
30
+ icon.animate([{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
31
+ { duration: 450, easing: "cubic-bezier(0.25, 1, 0.5, 1)" });
32
+ }
33
+ element("refresh").addEventListener("click", () => {
34
+ animateRefresh();
35
+ dashboardRefresh.refreshVisible({ force: true });
36
+ });
27
37
 
28
38
  const animationRows = new Map();
29
39
  let animationTimelines = [];
@@ -267,6 +277,12 @@ for (const [key, ids] of [["status", ["client-features", "request-context", "rec
267
277
 
268
278
  const dashboardRefresh = globalThis.ccdxRefresh.createController({
269
279
  visible: () => document.visibilityState === "visible",
280
+ onState: ({ pendingKeys }) => {
281
+ // The account read remains independent; it must not block dashboard data.
282
+ const busy = pendingKeys.some(key => key !== "auth");
283
+ element("refresh").disabled = busy;
284
+ element("refresh").setAttribute("aria-busy", String(busy));
285
+ },
270
286
  resources: {
271
287
  status: {
272
288
  visible: () => true,
@@ -277,7 +293,6 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
277
293
  },
278
294
  apply: render,
279
295
  state: state => {
280
- element("refresh").disabled = Boolean(state.pending);
281
296
  text("connection", state.pending || (!state.value && !state.error) ? "READING" : state.error ? "UNAVAILABLE" : "LOCAL OK");
282
297
  element("connection").className = `badge ${state.pending ? "neutral" : state.error ? "bad" : "good"}`;
283
298
  if (state.error) refreshTime(element("updated"), state);
@@ -407,3 +422,4 @@ loadModels();
407
422
  loadUsage();
408
423
  refresh();
409
424
  loadAuth();
425
+ animateRefresh();
@@ -0,0 +1,160 @@
1
+ import { CODEX_AUTO_REVIEW_MODEL } from "./models.mjs";
2
+ import { readBoundedResponseText } from "./upstream-body.mjs";
3
+
4
+ function localGatewayBaseUrl(host, port) {
5
+ const normalized = host === "0.0.0.0" ? "127.0.0.1" : host === "::" ? "::1" : host;
6
+ const address = normalized.includes(":") && !normalized.startsWith("[") ? `[${normalized}]` : normalized;
7
+ return `http://${address}:${port}`;
8
+ }
9
+
10
+ function copilotModelData(models) {
11
+ const data = Array.isArray(models) ? models : models?.data;
12
+ return Array.isArray(data) ? data : [];
13
+ }
14
+
15
+ function modelEndpoints(model) {
16
+ return Array.isArray(model?.supported_endpoints) ? model.supported_endpoints : [];
17
+ }
18
+
19
+ export function selectCompatibilityModels(models) {
20
+ const candidates = copilotModelData(models)
21
+ .filter((model) => model?.model_picker_enabled !== false)
22
+ .filter((model) => {
23
+ const id = String(model?.id || "");
24
+ const endpoints = modelEndpoints(model);
25
+ return id.startsWith("gpt-")
26
+ && (endpoints.includes("/responses") || endpoints.includes("/v1/responses"));
27
+ });
28
+ const responsesOnly = [...candidates].reverse()
29
+ .find((model) => !modelEndpoints(model).includes("/chat/completions"));
30
+ return { responsesModel: String((responsesOnly || candidates[0])?.id || "") };
31
+ }
32
+
33
+ async function fetchTextWithTimeout(fetchImpl, url, init, timeoutMs) {
34
+ const controller = new AbortController();
35
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
36
+ try {
37
+ const resp = await fetchImpl(url, { ...init, signal: controller.signal });
38
+ return { resp, text: await readBoundedResponseText(resp, { maxBytes: 4 * 1024 * 1024, signal: controller.signal, label: "Doctor response" }) };
39
+ } finally {
40
+ clearTimeout(timer);
41
+ }
42
+ }
43
+
44
+ function responseFailure(resp, text) {
45
+ const detail = String(text || "").replace(/\s+/g, " ").trim().slice(0, 240);
46
+ return new Error(`HTTP ${resp.status}${detail ? `: ${detail}` : ""}`);
47
+ }
48
+
49
+ async function compatibilityRequest(fetchImpl, url, body, timeoutMs) {
50
+ const { resp, text } = await fetchTextWithTimeout(fetchImpl, url, {
51
+ method: "POST",
52
+ headers: { "Content-Type": "application/json", Accept: body.stream ? "text/event-stream" : "application/json" },
53
+ body: JSON.stringify(body),
54
+ }, timeoutMs);
55
+ if (!resp.ok) throw responseFailure(resp, text);
56
+ return text;
57
+ }
58
+
59
+ async function runCompatibilityCheck(checks, label, task) {
60
+ const started = Date.now();
61
+ try {
62
+ const value = await task();
63
+ checks.push({ kind: "ok", message: `${label} passed (${Date.now() - started}ms)` });
64
+ return value;
65
+ } catch (error) {
66
+ const reason = error?.name === "AbortError" ? "timed out" : error?.message || "unknown error";
67
+ checks.push({ kind: "err", message: `${label} failed: ${reason}` });
68
+ return null;
69
+ }
70
+ }
71
+
72
+ function parseResponseObject(text) {
73
+ const response = JSON.parse(text);
74
+ if (!response?.id || !Array.isArray(response.output)) throw new Error("response body is missing id or output");
75
+ if (response.object !== "response.compaction" && response.status !== "completed") {
76
+ throw new Error("model response did not complete successfully");
77
+ }
78
+ return response;
79
+ }
80
+
81
+ function parseCompactionResponse(text) {
82
+ const response = parseResponseObject(text);
83
+ if (response.object !== "response.compaction"
84
+ || !response.output.some((item) => item?.type === "compaction")) {
85
+ throw new Error("response body is missing valid compaction state");
86
+ }
87
+ return response;
88
+ }
89
+
90
+ export async function inspectAdapterCompatibility({
91
+ host = "127.0.0.1",
92
+ port = 2026,
93
+ fetchImpl = fetch,
94
+ timeoutMs = 120000,
95
+ } = {}) {
96
+ const baseUrl = localGatewayBaseUrl(host, port);
97
+ const checks = [];
98
+ const models = await runCompatibilityCheck(checks, "Compatibility model discovery", async () => {
99
+ const { resp, text } = await fetchTextWithTimeout(fetchImpl, `${baseUrl}/v1/models`, { headers: { Accept: "application/json" } }, timeoutMs);
100
+ if (!resp.ok) throw responseFailure(resp, text);
101
+ const parsed = JSON.parse(text);
102
+ if (!copilotModelData(parsed).length) throw new Error("model list is empty");
103
+ return parsed;
104
+ });
105
+ if (!models) return checks;
106
+
107
+ const { responsesModel } = selectCompatibilityModels(models);
108
+ if (!responsesModel) {
109
+ checks.push({ kind: "err", message: "Compatibility Responses check failed: no GPT model advertises /responses" });
110
+ return checks;
111
+ }
112
+
113
+ await runCompatibilityCheck(checks, "Codex Auto-review", async () => {
114
+ const text = await compatibilityRequest(fetchImpl, `${baseUrl}/v1/responses`, {
115
+ model: CODEX_AUTO_REVIEW_MODEL,
116
+ stream: false,
117
+ input: "Reply with OK only.",
118
+ }, timeoutMs);
119
+ parseResponseObject(text);
120
+ });
121
+
122
+ const firstResponse = await runCompatibilityCheck(checks, `Native Responses (${responsesModel})`, async () => {
123
+ const text = await compatibilityRequest(fetchImpl, `${baseUrl}/v1/responses`, {
124
+ model: responsesModel,
125
+ stream: false,
126
+ input: "Reply with OK only.",
127
+ }, timeoutMs);
128
+ return parseResponseObject(text);
129
+ });
130
+
131
+ if (firstResponse) {
132
+ await runCompatibilityCheck(checks, "Responses stream and history compatibility", async () => {
133
+ const text = await compatibilityRequest(fetchImpl, `${baseUrl}/v1/responses`, {
134
+ model: responsesModel,
135
+ stream: true,
136
+ previous_response_id: firstResponse.id,
137
+ input: "Reply with OK again.",
138
+ }, timeoutMs);
139
+ const events = text.split(/\r?\n\r?\n/).map(block => {
140
+ const data = block.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).trim()).join("\n");
141
+ try { return JSON.parse(data); } catch { return null; }
142
+ }).filter(Boolean);
143
+ const terminals = events.filter(event => ["response.completed", "response.failed", "response.incomplete", "response.cancelled", "error"].includes(event.type));
144
+ if (terminals.length !== 1 || terminals[0].type !== "response.completed"
145
+ || terminals[0].response?.status !== "completed") throw new Error("stream did not finish with one valid response.completed");
146
+ parseResponseObject(JSON.stringify(terminals[0].response));
147
+ });
148
+ }
149
+
150
+ await runCompatibilityCheck(checks, "Responses compact", async () => {
151
+ const text = await compatibilityRequest(fetchImpl, `${baseUrl}/v1/responses/compact`, {
152
+ model: responsesModel,
153
+ stream: false,
154
+ input: "Compact this short context.",
155
+ }, timeoutMs);
156
+ parseCompactionResponse(text);
157
+ });
158
+
159
+ return checks;
160
+ }
@@ -0,0 +1,47 @@
1
+ import { inspectWindowsCommand } from "./windows-command.mjs";
2
+ import { inspectCodexConfig, repairCodexConfig } from "./codex-config-doctor.mjs";
3
+ import { readSavedGithubToken } from "./auth-credentials.mjs";
4
+ import { importDiscoveredGithubToken } from "./auth.mjs";
5
+ import { readPredictionSettings } from "./native-prediction-profile.mjs";
6
+ import { requestPredictionFix } from "./native-prediction-fix.mjs";
7
+
8
+ // Explicit invocation only. One repair and one affected recheck per operation.
9
+ export async function repairDoctor({ home, env = process.env, host, port, platform = process.platform, fetchImpl = fetch,
10
+ command = inspectWindowsCommand, config = repairCodexConfig, inspectConfig = inspectCodexConfig,
11
+ savedToken = readSavedGithubToken, importToken = importDiscoveredGithubToken,
12
+ predictionSettings = readPredictionSettings, fixPrediction = requestPredictionFix } = {}) {
13
+ const checks = [];
14
+ const run = async (id, task) => {
15
+ try { checks.push({ id, ...await task() }); }
16
+ catch { checks.push({ id, kind: "warn", result: "needs_review", message: `${id}: repair could not be verified; no retry or forced restart was performed` }); }
17
+ };
18
+ await run("windows-command", () => {
19
+ const result = command({ platform, repair: true });
20
+ if (["not_applicable", "checkout"].includes(result.status)) return { kind: "info", result: "not_applicable", message: "Command launcher: no repair required on this installation" };
21
+ const verified = command({ platform }).status === "ready";
22
+ return { kind: verified ? "ok" : "warn", result: verified ? result.changed ? "fixed_verified" : "unchanged" : "preserved",
23
+ message: verified ? "Command launcher verified; PowerShell policy unchanged" : "Custom or unavailable command launchers preserved; use ccdx.cmd and review PATH" };
24
+ });
25
+ await run("codex-config", () => {
26
+ const result = config({ home, env, host, port });
27
+ const verified = ["verified", "unchanged"].includes(result.status)
28
+ && !inspectConfig({ home, env, host, port }).some(check => check.kind === "err");
29
+ return { kind: verified ? "ok" : "warn", result: verified ? result.changed ? "fixed_verified" : "unchanged" : "preserved",
30
+ message: verified ? `Codex configuration ${result.changed ? "repaired and verified; previous file saved as config.toml.ccdx-doctor.bak when present" : "unchanged and verified"}`
31
+ : "Codex configuration preserved; review invalid or custom settings manually" };
32
+ });
33
+ await run("github-auth", async () => {
34
+ if (savedToken(home)) return { kind: "info", result: "preserved_existing", message: "Saved GitHub credential retained; use doctor --online to verify access" };
35
+ const imported = await importToken({ home, env, fetchImpl, log: () => {} });
36
+ const verified = imported?.ok && Boolean(savedToken(home));
37
+ return { kind: verified ? "ok" : "warn", result: verified ? "fixed_verified" : "needs_login",
38
+ message: verified ? "Existing GitHub Copilot credential imported and verified" : "No usable existing credential found; run ccdx to log in" };
39
+ });
40
+ await run("prediction", async () => {
41
+ if (!predictionSettings({ home, env }).enabled) return { kind: "info", result: "disabled", message: "Predictions are off; no optional feature was enabled" };
42
+ const result = await fixPrediction({ host, port, fetchImpl });
43
+ return { kind: ["ready", "disabled"].includes(result.status) ? "ok" : "warn", result: result.status,
44
+ message: `Prediction repair: ${result.status}; suggestion visibility is not verified; no App was restarted` };
45
+ });
46
+ return checks;
47
+ }
package/src/doctor.mjs CHANGED
@@ -10,12 +10,19 @@ import {
10
10
  import { status } from "./status.mjs";
11
11
  import { buildHeaders, FALLBACK_VSCODE_VERSION, parseApiBase } from "./copilot.mjs";
12
12
  import { adapterBaseUrl, checkRunningAdapter } from "./running-adapter.mjs";
13
- import { CODEX_AUTO_REVIEW_MODEL } from "./models.mjs";
14
13
  import { inspectCodexConfig } from "./codex-config-doctor.mjs";
15
14
  import { inspectPackageUpdateEnvironment } from "./package-update.mjs";
16
15
  import { inspectCredentialPermissions } from "./credential-permissions.mjs";
17
16
  import { imageProviderConfigPath } from "./image-provider-config.mjs";
18
17
  import { terminalCell } from "./terminal-text.mjs";
18
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
19
+ import { inspectWindowsCommand } from "./windows-command.mjs";
20
+ import { readPredictionSettings } from "./native-prediction-profile.mjs";
21
+ import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
22
+ import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
23
+ import { readImageProviderConfig } from "./image-provider-config.mjs";
24
+ import { inspectAdapterCompatibility } from "./doctor-compat.mjs";
25
+ export { selectCompatibilityModels, inspectAdapterCompatibility } from "./doctor-compat.mjs";
19
26
 
20
27
  export { inspectCodexConfig };
21
28
 
@@ -39,147 +46,6 @@ function displayPath(home, filePath) {
39
46
  return filePath;
40
47
  }
41
48
 
42
- function copilotModelData(models) {
43
- const data = Array.isArray(models) ? models : models?.data;
44
- return Array.isArray(data) ? data : [];
45
- }
46
-
47
- function modelEndpoints(model) {
48
- return Array.isArray(model?.supported_endpoints) ? model.supported_endpoints : [];
49
- }
50
-
51
- export function selectCompatibilityModels(models) {
52
- const candidates = copilotModelData(models)
53
- .filter((model) => model?.model_picker_enabled !== false)
54
- .filter((model) => {
55
- const id = String(model?.id || "");
56
- const endpoints = modelEndpoints(model);
57
- return id.startsWith("gpt-")
58
- && (endpoints.includes("/responses") || endpoints.includes("/v1/responses"));
59
- });
60
- const responsesOnly = [...candidates].reverse()
61
- .find((model) => !modelEndpoints(model).includes("/chat/completions"));
62
- return { responsesModel: String((responsesOnly || candidates[0])?.id || "") };
63
- }
64
-
65
- async function fetchTextWithTimeout(fetchImpl, url, init, timeoutMs) {
66
- const controller = new AbortController();
67
- const timer = setTimeout(() => controller.abort(), timeoutMs);
68
- try {
69
- const resp = await fetchImpl(url, { ...init, signal: controller.signal });
70
- return { resp, text: await resp.text() };
71
- } finally {
72
- clearTimeout(timer);
73
- }
74
- }
75
-
76
- function responseFailure(resp, text) {
77
- const detail = String(text || "").replace(/\s+/g, " ").trim().slice(0, 240);
78
- return new Error(`HTTP ${resp.status}${detail ? `: ${detail}` : ""}`);
79
- }
80
-
81
- async function compatibilityRequest(fetchImpl, url, body, timeoutMs) {
82
- const { resp, text } = await fetchTextWithTimeout(fetchImpl, url, {
83
- method: "POST",
84
- headers: { "Content-Type": "application/json", Accept: body.stream ? "text/event-stream" : "application/json" },
85
- body: JSON.stringify(body),
86
- }, timeoutMs);
87
- if (!resp.ok) throw responseFailure(resp, text);
88
- return text;
89
- }
90
-
91
- async function runCompatibilityCheck(checks, label, task) {
92
- const started = Date.now();
93
- try {
94
- const value = await task();
95
- checks.push({ kind: "ok", message: `${label} passed (${Date.now() - started}ms)` });
96
- return value;
97
- } catch (error) {
98
- const reason = error?.name === "AbortError" ? "timed out" : error?.message || "unknown error";
99
- checks.push({ kind: "err", message: `${label} failed: ${reason}` });
100
- return null;
101
- }
102
- }
103
-
104
- function parseResponseObject(text) {
105
- const response = JSON.parse(text);
106
- if (!response?.id || !Array.isArray(response.output)) throw new Error("response body is missing id or output");
107
- return response;
108
- }
109
-
110
- function parseCompactionResponse(text) {
111
- const response = parseResponseObject(text);
112
- if (response.object !== "response.compaction"
113
- || !response.output.some((item) => item?.type === "compaction")) {
114
- throw new Error("response body is missing valid compaction state");
115
- }
116
- return response;
117
- }
118
-
119
- export async function inspectAdapterCompatibility({
120
- host = "127.0.0.1",
121
- port = 2026,
122
- fetchImpl = fetch,
123
- timeoutMs = 120000,
124
- } = {}) {
125
- const baseUrl = localGatewayBaseUrl(connectHost(host), port);
126
- const checks = [];
127
- const models = await runCompatibilityCheck(checks, "Compatibility model discovery", async () => {
128
- const { resp, text } = await fetchTextWithTimeout(fetchImpl, `${baseUrl}/v1/models`, { headers: { Accept: "application/json" } }, timeoutMs);
129
- if (!resp.ok) throw responseFailure(resp, text);
130
- const parsed = JSON.parse(text);
131
- if (!copilotModelData(parsed).length) throw new Error("model list is empty");
132
- return parsed;
133
- });
134
- if (!models) return checks;
135
-
136
- const { responsesModel } = selectCompatibilityModels(models);
137
- if (!responsesModel) {
138
- checks.push({ kind: "err", message: "Compatibility Responses check failed: no GPT model advertises /responses" });
139
- return checks;
140
- }
141
-
142
- await runCompatibilityCheck(checks, "Codex Auto-review", async () => {
143
- const text = await compatibilityRequest(fetchImpl, `${baseUrl}/v1/responses`, {
144
- model: CODEX_AUTO_REVIEW_MODEL,
145
- stream: false,
146
- input: "Reply with OK only.",
147
- }, timeoutMs);
148
- parseResponseObject(text);
149
- });
150
-
151
- const firstResponse = await runCompatibilityCheck(checks, `Native Responses (${responsesModel})`, async () => {
152
- const text = await compatibilityRequest(fetchImpl, `${baseUrl}/v1/responses`, {
153
- model: responsesModel,
154
- stream: false,
155
- input: "Reply with OK only.",
156
- }, timeoutMs);
157
- return parseResponseObject(text);
158
- });
159
-
160
- if (firstResponse) {
161
- await runCompatibilityCheck(checks, "Responses stream and history compatibility", async () => {
162
- const text = await compatibilityRequest(fetchImpl, `${baseUrl}/v1/responses`, {
163
- model: responsesModel,
164
- stream: true,
165
- previous_response_id: firstResponse.id,
166
- input: "Reply with OK again.",
167
- }, timeoutMs);
168
- if (!/^event:\s*response\.completed\s*$/m.test(text)) throw new Error("stream did not contain response.completed");
169
- });
170
- }
171
-
172
- await runCompatibilityCheck(checks, "Responses compact", async () => {
173
- const text = await compatibilityRequest(fetchImpl, `${baseUrl}/v1/responses/compact`, {
174
- model: responsesModel,
175
- stream: false,
176
- input: "Compact this short context.",
177
- }, timeoutMs);
178
- parseCompactionResponse(text);
179
- });
180
-
181
- return checks;
182
- }
183
49
 
184
50
  export function inspectGitHubToken({ home = os.homedir() } = {}) {
185
51
  const filePath = githubTokenPath(home);
@@ -260,9 +126,14 @@ export async function inspectGitHubTokenOnline({
260
126
  }
261
127
  const models = await modelResp.json();
262
128
  const data = Array.isArray(models) ? models : models?.data;
129
+ const validModels = Array.isArray(data) ? data.filter(model => typeof model?.id === "string" && model.id.trim()) : [];
130
+ if (!validModels.length) return [
131
+ { kind: "ok", message: `GitHub Copilot access verified for ${validation.login || "current account"}` },
132
+ { kind: "err", message: "Copilot models endpoint returned no valid model directory despite HTTP 200" },
133
+ ];
263
134
  return [
264
135
  { kind: "ok", message: `GitHub Copilot access verified for ${validation.login || "current account"}` },
265
- { kind: "ok", message: `Copilot models endpoint returned ${Array.isArray(data) ? data.length : 0} models` },
136
+ { kind: "ok", message: `Copilot models endpoint returned ${validModels.length} models` },
266
137
  ];
267
138
  } catch (error) {
268
139
  const errorCode = error?.cause?.code || error?.code || "";
@@ -319,13 +190,37 @@ export async function collectDoctorChecks({
319
190
  inspectCodexClientFn,
320
191
  inspectUpdateEnvironmentFn = inspectPackageUpdateEnvironment,
321
192
  inspectCredentialPermissionsFn = inspectCredentialPermissions,
193
+ env = process.env,
194
+ platform = process.platform,
195
+ inspectWindowsCommandFn = inspectWindowsCommand,
196
+ readPredictionSettingsFn = readPredictionSettings,
197
+ inspectPredictionEnvironmentFn = inspectPredictionEnvironment,
198
+ readImageProviderConfigFn = readImageProviderConfig,
322
199
  } = {}) {
323
- if (configOnly) return inspectCodexConfig({ home, host, port });
200
+ if (configOnly) return inspectCodexConfig({ home, env, host, port });
324
201
  checkedDoctorProfile(profile);
325
202
  const checks = [
326
- ...inspectAuthProfiles({ home }),
327
- ...inspectCodexConfig({ home, host, port }),
203
+ ...inspectAuthProfiles({ home }).map(check => ({ ...check, id: "github-auth" })),
204
+ ...inspectCodexConfig({ home, env, host, port }).map(check => ({ ...check, id: "codex-config" })),
205
+ { kind: "info", message: `Runtime: Node ${process.version}, ${platform}/${process.arch}` },
328
206
  ];
207
+ if (platform === "win32") {
208
+ const command = inspectWindowsCommandFn({ platform });
209
+ checks.push({ kind: command.status === "ready" ? "ok" : ["checkout", "not_applicable"].includes(command.status) ? "info" : "warn", id: "windows-command",
210
+ message: `Windows command launcher: ${command.status}; PowerShell policy unchanged`, fix: command.status === "repairable" ? "ccdx.cmd doctor --fix" : undefined });
211
+ }
212
+ try {
213
+ const prediction = readPredictionSettingsFn({ home, env });
214
+ if (!prediction.enabled) checks.push({ kind: "info", message: "Predictions are off; optional routing checks skipped" });
215
+ else if (["darwin", "win32"].includes(platform)) {
216
+ const environment = inspectPredictionEnvironmentFn({ env, platform });
217
+ checks.push({ kind: environment.summary.tls.extra_ca === "unreadable_or_invalid" ? "warn" : "info", message: formatPredictionEnvironment(environment.summary) });
218
+ } else checks.push({ kind: "warn", message: "Native predictions require macOS or Windows; existing settings preserved" });
219
+ } catch { checks.push({ kind: "warn", message: "Prediction environment could not be verified; existing routing and trust settings preserved", fix: "ccdx prediction status" }); }
220
+ try {
221
+ const image = readImageProviderConfigFn({ home, env, strict: true });
222
+ checks.push({ kind: "info", message: image ? "Image generation configured; no provider request was made" : "Image generation is off; optional checks skipped" });
223
+ } catch { checks.push({ kind: "warn", message: "Image provider configuration is invalid; core service is unaffected", fix: "ccdx image-status" }); }
329
224
  const updateEnvironment = inspectUpdateEnvironmentFn();
330
225
  const updateMessage = updateEnvironment.state === "different" ? "npm update target differs from this CCDX installation; review PATH/prefix before updating"
331
226
  : updateEnvironment.state === "unavailable" ? "npm update environment could not be verified; installer settings were not changed"
@@ -400,9 +295,24 @@ export async function runDoctor(options = {}) {
400
295
  const flags = [
401
296
  options.online ? "--online" : "",
402
297
  options.compat ? "--compat" : "",
298
+ options.fix ? "--fix" : "",
403
299
  ].filter(Boolean);
404
- log(`${options.commandName || "ccdx"} doctor${options.configOnly ? " config" : flags.length ? ` ${flags.join(" ")}` : ""}`);
405
- const checks = await collectDoctorChecks(options);
300
+ if (!options.json) log(`${options.commandName || "ccdx"} doctor${options.configOnly ? " config" : flags.length ? ` ${flags.join(" ")}` : ""}`);
301
+ let checks = await collectDoctorChecks(options);
302
+ const before = options.fix ? checks : undefined;
303
+ if (options.fix && !options.configOnly) {
304
+ const repair = options.repairDoctorFn || (await import("./doctor-repair.mjs")).repairDoctor;
305
+ const repairs = await repair(options);
306
+ const verified = new Set(repairs.filter(check => ["fixed_verified", "unchanged"].includes(check.result)
307
+ && check.kind !== "warn" && check.kind !== "err").map(check => check.id));
308
+ checks = checks.filter(check => !verified.has(check.id)).concat(repairs);
309
+ }
310
+ for (const check of checks) check.message = terminalCell(redactDiagnosticText(check.message));
311
+ for (const check of before || []) check.message = terminalCell(redactDiagnosticText(check.message));
312
+ if (options.json) {
313
+ log(JSON.stringify({ command: "doctor", repair_requested: options.fix === true, checks, ...(before ? { before_checks: before } : {}) }));
314
+ return checks;
315
+ }
406
316
  for (const check of checks) log(status(check.kind, check.message));
407
317
  const totals = { ok: 0, warn: 0, err: 0 };
408
318
  for (const check of checks) totals[check.kind] = (totals[check.kind] || 0) + 1;