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,161 @@
1
+ (() => {
2
+ function create({ element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator }) {
3
+ function usageValues(row) {
4
+ const rate = Number.isFinite(row.cache_hit_rate) && row.cache_hit_rate >= 0 && row.cache_hit_rate <= 1
5
+ ? `${row.cache_hit_rate_partial ? "~" : ""}${(row.cache_hit_rate * 100).toFixed(1)}%` : "—";
6
+ return [row.model, number(row.requests), number(row.input_tokens), number(row.cache_read_tokens), number(row.output_tokens), number(row.total_tokens), rate];
7
+ }
8
+
9
+ let usageData = null;
10
+ let analyticsSignature;
11
+ let selectedUsageDate = "";
12
+
13
+ function renderUsageTable() {
14
+ const day = selectedUsageDate && usageData.analytics?.days.find((entry) => entry.date === selectedUsageDate);
15
+ const model = element("analytics-model").value;
16
+ const total = day ? { ...analyticsPoint(day, model), model: "TOTAL" } : usageData.total;
17
+ const rows = day ? day.models.filter((row) => !model || row.model === model).sort((a, b) => b.total_tokens - a.total_tokens || a.model.localeCompare(b.model)) : usageData.rows;
18
+ const body = element("usage-body");
19
+ body.replaceChildren();
20
+ if (total.requests > 0) {
21
+ body.append(tableRow(usageValues(total), { total: true }));
22
+ for (const row of rows) body.append(tableRow(usageValues(row)));
23
+ } else { emptyTable("usage-body", 7, "No usage records."); }
24
+ element("clear-usage-day").hidden = !day;
25
+ text("usage-state", day ? day.date : "LOCAL LOG");
26
+ text("usage-note", "{records} records / {shown} of {models} models shown{day}", {
27
+ records: number(total.requests), shown: number(rows.length), models: number(day ? rows.length : usageData.model_count),
28
+ day: day ? phrase(" / {zone} / {model}", { zone: usageData.analytics.time_zone, model: model || phrase("All models") }) : "",
29
+ });
30
+ }
31
+
32
+ function renderUsageState() {
33
+ text("usage-state", selectedUsageDate && usageData.analytics?.days.some(day => day.date === selectedUsageDate) ? selectedUsageDate : "LOCAL LOG");
34
+ }
35
+
36
+ function analyticsPoint(day, model) {
37
+ return model ? day.models.find((row) => row.model === model) || { requests: 0, input_tokens: 0, output_tokens: 0 } : day;
38
+ }
39
+
40
+ function selectUsageDay(date) {
41
+ selectedUsageDate = date;
42
+ renderUsageTable();
43
+ renderAnalytics();
44
+ }
45
+
46
+ function dayButton(day, point) {
47
+ const button = document.createElement("button");
48
+ button.type = "button";
49
+ button.disabled = !day.available;
50
+ button.setAttribute("aria-pressed", String(day.date === selectedUsageDate));
51
+ const description = !day.available ? phrase("no retained history")
52
+ : phrase("{calls} recorded calls / input {input} / output {output} / cached {cached} (included in input){partial}", {
53
+ calls: number(point.requests), input: number(point.input_tokens), output: number(point.output_tokens), cached: number(point.cache_read_tokens), partial: point.tokens_partial ? phrase(" / partial token counts") : "",
54
+ });
55
+ for (const attribute of ["title", "aria-label"]) localize(button, "{date} / {description}", { date: day.date, description }, attribute);
56
+ button.addEventListener("click", () => selectUsageDay(day.date));
57
+ return button;
58
+ }
59
+
60
+ function renderAnalytics() {
61
+ const analytics = usageData?.analytics;
62
+ if (!analytics) return;
63
+ const model = element("analytics-model").value;
64
+ const signature = JSON.stringify([analytics, model, element("analytics-range").value, element("analytics-metric").value, selectedUsageDate]);
65
+ if (signature === analyticsSignature) return;
66
+ analyticsSignature = signature;
67
+ const days = analytics.days;
68
+ const daily = days.slice(-Number(element("analytics-range").value));
69
+ const maximum = Math.max(1, ...daily.map((day) => {
70
+ const point = analyticsPoint(day, model);
71
+ return point.input_tokens + point.output_tokens;
72
+ }));
73
+ const bars = element("daily-bars");
74
+ bars.replaceChildren();
75
+ for (const day of daily) {
76
+ const point = analyticsPoint(day, model);
77
+ const button = dayButton(day, point);
78
+ button.className = "daily-bar";
79
+ for (const key of ["output_tokens", "input_tokens"]) {
80
+ const segment = document.createElement("span");
81
+ segment.className = key === "input_tokens" ? "bar-input" : "bar-output";
82
+ segment.style.height = `${point[key] / maximum * 100}%`;
83
+ button.append(segment);
84
+ }
85
+ bars.append(button);
86
+ }
87
+ text("daily-from", daily[0].date);
88
+ text("daily-to", analytics.to);
89
+ const metric = element("analytics-metric").value;
90
+ const value = (day) => {
91
+ const point = analyticsPoint(day, model);
92
+ return metric === "tokens" ? point.input_tokens + point.output_tokens : point.requests;
93
+ };
94
+ const peak = Math.max(1, ...days.map(value));
95
+ text("activity-scale", "{metric} / PEAK {peak}", { metric: phrase(metric === "tokens" ? "INPUT + OUTPUT" : "RECORDED CALLS"), peak: number(peak === 1 && days.every((day) => value(day) === 0) ? 0 : peak) });
96
+ const calendar = element("activity-calendar");
97
+ calendar.replaceChildren();
98
+ const offset = (new Date(`${days[0].date}T00:00:00Z`).getUTCDay() + 6) % 7;
99
+ const months = element("calendar-months");
100
+ months.replaceChildren();
101
+ const columns = Math.ceil((offset + days.length) / 7);
102
+ let previousColumn = -4;
103
+ days.forEach((day, index) => {
104
+ if (index !== 0 && !day.date.endsWith("-01")) return;
105
+ const column = Math.floor((offset + index) / 7);
106
+ if (column - previousColumn < 4 || column + 4 > columns) return;
107
+ previousColumn = column;
108
+ const label = document.createElement("span");
109
+ label.textContent = day.date.slice(0, 7);
110
+ label.style.gridColumn = `${column + 1} / span 4`;
111
+ months.append(label);
112
+ });
113
+ for (let index = 0; index < offset; index += 1) {
114
+ const spacer = document.createElement("span");
115
+ spacer.setAttribute("aria-hidden", "true");
116
+ calendar.append(spacer);
117
+ }
118
+ for (const day of days) {
119
+ const button = dayButton(day, analyticsPoint(day, model));
120
+ button.className = "calendar-day";
121
+ const count = value(day);
122
+ button.dataset.level = String(count > 0 ? Math.min(4, Math.ceil(count / peak * 4)) : 0);
123
+ calendar.append(button);
124
+ }
125
+ text("analytics-note", "{zone} / {from} — {to} / retained history starts {first}; oldest day may be partial.{excluded}{limit}", {
126
+ zone: analytics.time_zone, from: daily[0].date, to: analytics.to, first: analytics.first_date || phrase("unknown"),
127
+ excluded: analytics.undated_records ? phrase(" {count} records with invalid/future timestamps excluded.", { count: number(analytics.undated_records) }) : "",
128
+ limit: analytics.models_truncated ? phrase(" Model filters limited to 100; all-model totals include the remainder.") : "",
129
+ });
130
+ text("analytics-selection", selectedUsageDate ? "Selected {date} / {model}: totals in the Usage table above / All history resets the table." : "Select a day for model totals. Calls are usage records, not messages or time. Hatched cells: no retained history; empty cells: zero recorded calls.", { date: selectedUsageDate, model: model || phrase("All models") });
131
+ }
132
+
133
+ function updateAnalyticsModels() {
134
+ const select = element("analytics-model");
135
+ const previous = select.value;
136
+ select.replaceChildren();
137
+ for (const model of [...new Set(["", ...usageData.analytics.models, ...(previous ? [previous] : [])])]) {
138
+ const option = document.createElement("option");
139
+ option.value = model;
140
+ if (model) option.textContent = model;
141
+ else localize(option, "All models");
142
+ select.append(option);
143
+ }
144
+ select.value = previous;
145
+ }
146
+
147
+ function applyUsage(data, { changed }) {
148
+ usageData = { ...data, ...(!data.analytics && usageData?.analytics ? { analytics: usageData.analytics } : {}) };
149
+ if (changed) {
150
+ if (data.analytics) updateAnalyticsModels();
151
+ renderUsageTable();
152
+ if (data.analytics) renderAnalytics();
153
+ }
154
+ if (data.analytics) {
155
+ text("analytics-updated", "Updated {time}", { time: new Date().toLocaleTimeString() });
156
+ }
157
+ }
158
+ return { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay, usageValues, get data() { return usageData; }, get selectedDate() { return selectedUsageDate; } };
159
+ }
160
+ globalThis.ccdxDashboardUsage = { create };
161
+ })();
@@ -111,7 +111,7 @@ function usageTable(summary) {
111
111
  export async function handleDashboardApi(req, res, pathname, {
112
112
  env = process.env,
113
113
  home = os.homedir(),
114
- liveModelsFn = () => fetchLiveCopilotModels({ home }),
114
+ liveModelsFn = options => fetchLiveCopilotModels({ home, ...options }),
115
115
  usageSummaryFn,
116
116
  authStatusFn = () => authStatus({ home }),
117
117
  } = {}) {
@@ -191,8 +191,9 @@ export async function handleDashboardApi(req, res, pathname, {
191
191
  }
192
192
 
193
193
  if (pathname === MODELS_PATH && req.method === "GET") {
194
+ const abort = createRequestAbort(req, res);
194
195
  try {
195
- const catalog = await liveModelsFn();
196
+ const catalog = await liveModelsFn({ signal: abort.signal });
196
197
  if (!Array.isArray(catalog?.models) || !Number.isFinite(catalog?.advertised)) {
197
198
  throw new Error("Invalid live model catalog");
198
199
  }
@@ -211,8 +212,8 @@ export async function handleDashboardApi(req, res, pathname, {
211
212
  })),
212
213
  });
213
214
  } catch (error) {
214
- sendJson(res, 502, { error: liveModelError(error) });
215
- }
215
+ if (!res.destroyed && !res.writableEnded) sendJson(res, 502, { error: liveModelError(error) });
216
+ } finally { abort.cleanup(); }
216
217
  return;
217
218
  }
218
219
 
package/src/dashboard.mjs CHANGED
@@ -7,6 +7,8 @@ const ASSETS = new Map([
7
7
  ["/theme.js", ["./dashboard/theme.js", "text/javascript; charset=utf-8"]],
8
8
  ["/language.js", ["./dashboard/language.js", "text/javascript; charset=utf-8"]],
9
9
  ["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
10
+ ["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
11
+ ["/usage.js", ["./dashboard/usage.js", "text/javascript; charset=utf-8"]],
10
12
  ["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
11
13
  ]);
12
14
 
package/src/doctor.mjs CHANGED
@@ -12,6 +12,10 @@ import { buildHeaders, FALLBACK_VSCODE_VERSION, parseApiBase } from "./copilot.m
12
12
  import { adapterBaseUrl, checkRunningAdapter } from "./running-adapter.mjs";
13
13
  import { CODEX_AUTO_REVIEW_MODEL } from "./models.mjs";
14
14
  import { inspectCodexConfig } from "./codex-config-doctor.mjs";
15
+ import { inspectPackageUpdateEnvironment } from "./package-update.mjs";
16
+ import { inspectCredentialPermissions } from "./credential-permissions.mjs";
17
+ import { imageProviderConfigPath } from "./image-provider-config.mjs";
18
+ import { terminalCell } from "./terminal-text.mjs";
15
19
 
16
20
  export { inspectCodexConfig };
17
21
 
@@ -313,6 +317,8 @@ export async function collectDoctorChecks({
313
317
  compatTimeoutMs = 120000,
314
318
  inspectAdapterCompatibilityFn = inspectAdapterCompatibility,
315
319
  inspectCodexClientFn,
320
+ inspectUpdateEnvironmentFn = inspectPackageUpdateEnvironment,
321
+ inspectCredentialPermissionsFn = inspectCredentialPermissions,
316
322
  } = {}) {
317
323
  if (configOnly) return inspectCodexConfig({ home, host, port });
318
324
  checkedDoctorProfile(profile);
@@ -320,6 +326,20 @@ export async function collectDoctorChecks({
320
326
  ...inspectAuthProfiles({ home }),
321
327
  ...inspectCodexConfig({ home, host, port }),
322
328
  ];
329
+ const updateEnvironment = inspectUpdateEnvironmentFn();
330
+ const updateMessage = updateEnvironment.state === "different" ? "npm update target differs from this CCDX installation; review PATH/prefix before updating"
331
+ : updateEnvironment.state === "unavailable" ? "npm update environment could not be verified; installer settings were not changed"
332
+ : "npm update environment checked (source checkout or matching installation)";
333
+ const updatePaths = ["node", "npm", "package_root", "prefix", "target"]
334
+ .filter(key => updateEnvironment[key]).map(key => `${key}=${terminalCell(updateEnvironment[key])}`).join(" / ");
335
+ checks.push({ kind: updateEnvironment.state === "different" || updateEnvironment.state === "unavailable" ? "warn" : "ok",
336
+ message: `${updateMessage}${updatePaths ? ` / ${updatePaths}` : ""}` });
337
+ for (const [label, file] of [["GitHub token", githubTokenPath(home)], ["Image API key", imageProviderConfigPath({ home })]]) {
338
+ const permissions = inspectCredentialPermissionsFn(file);
339
+ if (permissions === "missing") continue;
340
+ checks.push({ kind: permissions === "review" || permissions === "unavailable" ? "warn" : "ok",
341
+ message: `${label} file permissions: ${permissions}${permissions === "review" ? " (broader access detected; review manually, no ACL was changed)" : ""}` });
342
+ }
323
343
 
324
344
  if (online) {
325
345
  checks.push(...await inspectAuthProfilesOnline({
@@ -7,6 +7,7 @@ import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
7
7
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
8
8
  import { httpError } from "./http-errors.mjs";
9
9
  import { admissionAbortError, contentEncodings, requestContentLength } from "./request-admission.mjs";
10
+ import { currentRequestContext } from "./request-context.mjs";
10
11
 
11
12
  export { httpError } from "./http-errors.mjs";
12
13
  export { createRequestAdmission } from "./request-admission.mjs";
@@ -264,6 +265,9 @@ export function sendJsonError(res, err, fallbackStatus = 400) {
264
265
  return;
265
266
  }
266
267
  const statusCode = err?.statusCode || fallbackStatus;
268
+ const context = currentRequestContext();
269
+ context?.onHttpError?.({ code: err?.code || err?.jsonBody?.error?.code,
270
+ origin: context.errorOrigin || (statusCode < 500 ? "client_validation" : "local_transport") });
267
271
  const headers = { "Content-Type": "application/json" };
268
272
  if (statusCode === 408 || statusCode === 413) headers.Connection = "close";
269
273
  res.writeHead(statusCode, headers);
@@ -271,6 +275,9 @@ export function sendJsonError(res, err, fallbackStatus = 400) {
271
275
  }
272
276
 
273
277
  export function sendUpstreamError(res, response, text) {
278
+ let code;
279
+ try { code = JSON.parse(text)?.error?.code; } catch {}
280
+ currentRequestContext()?.onHttpError?.({ code, origin: "upstream_http", headers: response.headers });
274
281
  if (!res.headersSent) {
275
282
  res.writeHead(response.status || 502, safeUpstreamResponseHeaders(response.headers, {
276
283
  defaultContentType: "application/json",
@@ -1,4 +1,4 @@
1
- import fs from "node:fs";
1
+ import { readBoundedFileSync } from "./bounded-file.mjs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { atomicWriteFileSync } from "./atomic-file.mjs";
@@ -77,7 +77,7 @@ export function validateImageProviderConfig(value, { filePath = "image-provider.
77
77
  export function readImageProviderConfig({ env = process.env, home = os.homedir(), strict = false } = {}) {
78
78
  const filePath = imageProviderConfigPath({ env, home });
79
79
  try {
80
- return validateImageProviderConfig(JSON.parse(fs.readFileSync(filePath, "utf8")), { filePath });
80
+ return validateImageProviderConfig(JSON.parse(readBoundedFileSync(filePath, { encoding: "utf8" })), { filePath });
81
81
  } catch (error) {
82
82
  if (error?.code === "ENOENT") return null;
83
83
  if (strict) {
package/src/launcher.mjs CHANGED
@@ -61,6 +61,7 @@ export function macPredictionAppProcesses(app, { exec = execFileSync } = {}) {
61
61
  }
62
62
 
63
63
  export async function openCodex({ env = process.env, spawnImpl = spawn, platform = process.platform, predictionPacUrl = null, predictionApp = null, predictionProfile = null,
64
+ preparePredictionRoute, persistedPredictionRoute = false, onPredictionRoute = () => {}, log = console.log,
64
65
  resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses,
65
66
  macAppProcesses = macPredictionAppProcesses } = {}) {
66
67
  if (platform === "win32" && autoLaunchEnabled(env) && typeof predictionPacUrl === "string"
@@ -82,10 +83,14 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
82
83
  const running = windowsAppProcesses(current.app, { env });
83
84
  if (running.length) {
84
85
  if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
85
- console.log(status("ok", "Running Codex App uses the current prediction route"));return true;
86
+ onPredictionRoute("verified");log(status("ok", "Running Codex App uses the current prediction route"));return true;
87
+ }
88
+ if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
89
+ onPredictionRoute("persisted");log(status("info", "App route preference is saved; waiting for configuration traffic to confirm it"));return true;
86
90
  }
87
91
  throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then run ccdx again; no process was stopped");
88
92
  }
93
+ await preparePredictionRoute?.();
89
94
  const launched = await new Promise(resolve => {
90
95
  const child = spawnImpl(current.app, [`--user-data-dir=${predictionProfile}`, `--proxy-pac-url=${predictionPacUrl}`], {
91
96
  cwd: path.win32.dirname(current.app), env: { ...env, CODEX_ELECTRON_USER_DATA_PATH: predictionProfile },
@@ -94,27 +99,28 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
94
99
  child.once("error", () => resolve(false));
95
100
  child.once("spawn", () => { child.unref(); resolve(true); });
96
101
  });
97
- if (!launched) { console.log(status("warn", "Could not launch the registered Windows Codex App"));return false; }
102
+ if (!launched) { onPredictionRoute("unverified");log(status("warn", "Could not launch the registered Windows Codex App"));return false; }
98
103
  await new Promise(resolve => setTimeout(resolve, 300));
99
104
  const actual = windowsAppProcesses(current.app, { env });
100
105
  const routeRetained = actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl;
101
- console.log(status(routeRetained ? "info" : "warn", routeRetained
106
+ onPredictionRoute(routeRetained ? "verified" : "unverified");
107
+ log(status(routeRetained ? "info" : "warn", routeRetained
102
108
  ? "Codex launch route verified; prediction status will show when configuration traffic is observed"
103
109
  : "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
104
110
  return routeRetained;
105
111
  } catch (error) {
106
- console.log(status("warn", `Optional Windows prediction launch skipped: ${error.message}`));
112
+ onPredictionRoute("unverified");log(status("warn", `Optional Windows prediction launch skipped: ${error.message}`));
107
113
  return false;
108
114
  }
109
115
  }
110
116
  if (platform !== "darwin") {
111
- console.log(status("warn", "Automatic launch requires macOS or an enabled Windows prediction setup"));
112
- console.log(status("info", "Open Codex App manually; it will connect to the adapter."));
117
+ log(status("warn", "Automatic launch requires macOS or an enabled Windows prediction setup"));
118
+ log(status("info", "Open Codex App manually; it will connect to the adapter."));
113
119
  return false;
114
120
  }
115
121
 
116
122
  if (!autoLaunchEnabled(env)) {
117
- console.log(status("info", "Auto-launch disabled (CCDX_AUTO_LAUNCH=0); open Codex App manually."));
123
+ log(status("info", "Auto-launch disabled (CCDX_AUTO_LAUNCH=0); open Codex App manually."));
118
124
  return false;
119
125
  }
120
126
 
@@ -126,38 +132,42 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
126
132
  const running = macAppProcesses(predictionApp);
127
133
  if (running.length) {
128
134
  if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
129
- console.log(status("ok", "Running Codex App uses the current prediction route"));return true;
135
+ onPredictionRoute("verified");log(status("ok", "Running Codex App uses the current prediction route"));return true;
136
+ }
137
+ if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
138
+ onPredictionRoute("persisted");log(status("info", "App route preference is saved; waiting for configuration traffic to confirm it"));return true;
130
139
  }
131
140
  throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then run ccdx again; no process was stopped");
132
141
  }
142
+ await preparePredictionRoute?.();
133
143
  if (!await tryOpen([predictionApp, ...extraArgs], { spawnImpl })) {
134
- console.log(status("warn", "Could not launch the verified macOS Codex App"));return false;
144
+ onPredictionRoute("unverified");log(status("warn", "Could not launch the verified macOS Codex App"));return false;
135
145
  }
136
146
  for (let attempt = 0; attempt < 10; attempt++) {
137
147
  const actual = macAppProcesses(predictionApp);
138
148
  if (actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl) {
139
- console.log(status("info", "Codex launch route verified; prediction status will show when configuration traffic is observed"));return true;
149
+ onPredictionRoute("verified");log(status("info", "Codex launch route verified; prediction status will show when configuration traffic is observed"));return true;
140
150
  }
141
151
  if (actual.length) break;
142
152
  if (attempt < 9) await new Promise(resolve => setTimeout(resolve, 100));
143
153
  }
144
- console.log(status("warn", "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
154
+ onPredictionRoute("unverified");log(status("warn", "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
145
155
  return false;
146
156
  } catch (error) {
147
- console.log(status("warn", `Optional macOS prediction launch skipped: ${error.message}`));return false;
157
+ onPredictionRoute("unverified");log(status("warn", `Optional macOS prediction launch skipped: ${error.message}`));return false;
148
158
  }
149
159
  }
150
160
  const attempts = launchAttempts();
151
161
  for (const attempt of attempts) {
152
162
  const args = [...attempt, ...extraArgs];
153
163
  if (await tryOpen(args, { spawnImpl })) {
154
- console.log(status("ok", "Codex app launched"));
164
+ log(status("ok", "Codex app launched"));
155
165
  return true;
156
166
  }
157
167
  }
158
168
 
159
- console.log(status("warn", "Could not launch the Codex app (checked com.openai.codex, Codex.app, ChatGPT.app)"));
160
- console.log(status("info", "Open Codex App manually; it will connect to the adapter."));
161
- console.log(status("info", "Download it from https://openai.com/codex"));
169
+ log(status("warn", "Could not launch the Codex app (checked com.openai.codex, Codex.app, ChatGPT.app)"));
170
+ log(status("info", "Open Codex App manually; it will connect to the adapter."));
171
+ log(status("info", "Download it from https://openai.com/codex"));
162
172
  return false;
163
173
  }
@@ -1,10 +1,13 @@
1
1
  import os from "node:os";
2
+ import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
3
+ import { githubTokenFingerprint } from "./github-identity.mjs";
2
4
  import { validateGithubToken } from "./auth.mjs";
3
5
  import { AUTH_PROFILE_CODEX, readAuthProfileCredentials } from "./auth-profile.mjs";
4
6
  import { buildHeaders, FALLBACK_VSCODE_VERSION, parseApiBase } from "./copilot.mjs";
5
7
  import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "./upstream-body.mjs";
6
8
 
7
9
  const DEFAULT_MODELS_TIMEOUT_MS = 10000;
10
+ const modelFlights = new WeakMap();
8
11
  const SUPPORTED_ENDPOINTS = [
9
12
  ["responses", new Set(["/responses", "/v1/responses"])],
10
13
  ["chat", new Set(["/chat/completions"])],
@@ -78,9 +81,21 @@ export async function fetchLiveCopilotModels({
78
81
  fetchImpl = fetch,
79
82
  timeoutMs = DEFAULT_MODELS_TIMEOUT_MS,
80
83
  vscodeVersion = FALLBACK_VSCODE_VERSION,
84
+ signal,
81
85
  } = {}) {
82
86
  const credentials = readModelCredentials(home);
87
+ let flights = modelFlights.get(fetchImpl);
88
+ if (!flights) { flights = createAbortAwareSingleflight();modelFlights.set(fetchImpl, flights); }
89
+ const key = `${home}\0${githubTokenFingerprint(credentials.token)}\0${vscodeVersion}\0${timeoutMs}`;
90
+ const result = await flights.run(key, sharedSignal => lookupLiveModels(credentials, { fetchImpl, timeoutMs, vscodeVersion, signal: sharedSignal }), { signal });
91
+ return structuredClone(result); // Independent callers retain independent catalog values.
92
+ }
93
+
94
+ async function lookupLiveModels(credentials, { fetchImpl, timeoutMs, vscodeVersion, signal }) {
83
95
  const controller = new AbortController();
96
+ const cancel = () => controller.abort(signal.reason);
97
+ signal.addEventListener("abort", cancel, { once: true });
98
+ if (signal.aborted) cancel();
84
99
  const timer = setTimeout(() => controller.abort(), timeoutMs);
85
100
  try {
86
101
  const validation = await validateGithubToken(credentials.token, {
@@ -130,5 +145,6 @@ export async function fetchLiveCopilotModels({
130
145
  throw error;
131
146
  } finally {
132
147
  clearTimeout(timer);
148
+ signal.removeEventListener("abort", cancel);
133
149
  }
134
150
  }
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { readBoundedFileSync, MAX_MODEL_CACHE_FILE_BYTES } from "./bounded-file.mjs";
4
5
 
5
6
  export const MODEL_CACHE_SOFT_TTL_MS = 2 * 60 * 60 * 1000;
6
7
  export const MODEL_CACHE_HARD_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -32,7 +33,7 @@ export function loadModelCacheEntry({
32
33
  now = Date.now,
33
34
  } = {}) {
34
35
  try {
35
- const parsed = JSON.parse(fs.readFileSync(modelCachePath(home), "utf8"));
36
+ const parsed = JSON.parse(readBoundedFileSync(modelCachePath(home), { maxBytes: MAX_MODEL_CACHE_FILE_BYTES, encoding: "utf8" }));
36
37
  const savedAt = Date.parse(parsed.saved_at);
37
38
  if (!Number.isFinite(savedAt)) return null;
38
39
  const expectedFingerprint = String(credentialFingerprint || "").trim();
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { readBoundedFileSync } from "./bounded-file.mjs";
4
5
  import { execFileSync } from "node:child_process";
5
6
  import { createHash, X509Certificate, createPrivateKey, createPublicKey } from "node:crypto";
6
7
  import { atomicWriteFileSync } from "./atomic-file.mjs";
@@ -27,7 +28,7 @@ export function predictionPaths({ env = process.env, home = os.homedir(), platfo
27
28
  export function readPredictionSettings(options = {}) {
28
29
  const { settings } = predictionPaths(options);
29
30
  try {
30
- const value = JSON.parse(fs.readFileSync(settings, "utf8"));
31
+ const value = JSON.parse(readBoundedFileSync(settings, { encoding: "utf8" }));
31
32
  if (value?.version !== 1 || typeof value.enabled !== "boolean") throw new Error();
32
33
  return value;
33
34
  } catch (error) {
@@ -0,0 +1,39 @@
1
+ // Only the optional bridge is supervised. Model/image traffic, App processes,
2
+ // global proxy settings and certificate trust are never changed here.
3
+ export function supervisePrediction({ native, restart, state, warning = () => {},
4
+ intervalMs = 30_000, now = Date.now, setIntervalImpl = setInterval, clearIntervalImpl = clearInterval } = {}) {
5
+ let current = native, closed = false, flight = null, attempts = 0, retryAt = 0;
6
+ const delays = [30_000, 60_000, 120_000];
7
+ async function check() {
8
+ if (closed || flight || !current || current.enabled?.() === false || attempts >= delays.length || now() < retryAt) return;
9
+ if (current.healthy()) { state?.checked();return; }
10
+ const attempt = ++attempts;
11
+ retryAt = now() + delays[attempt - 1];
12
+ state?.recovering(attempt);
13
+ flight = (async () => {
14
+ try {
15
+ await current.close();
16
+ if (closed) return;
17
+ const resumed = await restart();
18
+ if (closed) { await resumed?.close();return; }
19
+ if (!resumed || resumed.pacUrl !== native.pacUrl) {
20
+ await resumed?.close();throw new Error("Prediction recovery did not retain the original route");
21
+ }
22
+ current = resumed;state?.recovered();
23
+ warning("Prediction bridge recovered on its original port; App restart was not requested");
24
+ } catch (error) {
25
+ state?.unavailable(error);
26
+ warning(`Prediction bridge recovery ${attempt}/${delays.length} failed: ${error.message}. Core service remains available`);
27
+ }
28
+ })();
29
+ try { await flight; } finally { flight = null; }
30
+ }
31
+ const timer = setIntervalImpl(() => { void check().catch(error => state?.unavailable(error)); }, intervalMs);
32
+ timer.unref?.();
33
+ return {
34
+ ...native,
35
+ check,
36
+ prepareRoute() { return current.prepareRoute?.(); },
37
+ async close() { closed = true;clearIntervalImpl(timer);await flight;await current?.close(); },
38
+ };
39
+ }
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { readBoundedFileSync } from "./bounded-file.mjs";
5
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
6
+ import { withFileLock } from "./lock.mjs";
7
+
8
+ const validPac = value => typeof value === "string" && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(value)
9
+ && Number(new URL(value).port) >= 1024 && Number(new URL(value).port) <= 65535;
10
+ const object = value => value && typeof value === "object" && !Array.isArray(value);
11
+
12
+ function regularFile(file) {
13
+ const stat = fs.lstatSync(file);
14
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Prediction route file is not a regular owned file; it was preserved");
15
+ }
16
+
17
+ function preferences(profile) {
18
+ for (const directory of [profile, path.join(profile, "Default")]) {
19
+ const stat = fs.lstatSync(directory);
20
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Prediction profile is not a regular directory; it was preserved");
21
+ }
22
+ regularFile(path.join(profile, "Local State"));
23
+ const file = path.join(profile, "Default", "Preferences");
24
+ regularFile(file);
25
+ const bytes = readBoundedFileSync(file);
26
+ const value = JSON.parse(bytes);
27
+ if (!object(value)) throw new Error("Unknown App preferences; they were preserved");
28
+ return { file, bytes, value };
29
+ }
30
+
31
+ function recordAt(file, profile) {
32
+ try {
33
+ regularFile(file);
34
+ const value = JSON.parse(readBoundedFileSync(file, { encoding: "utf8" }));
35
+ if (value?.version !== 1 || value.profile !== profile || !validPac(value.pacUrl)
36
+ || typeof value.hadProxy !== "boolean" || (value.hadProxy && !isDeepStrictEqual(value.previousProxy, { mode: "system" }))) {
37
+ throw new Error("Unknown saved prediction route ownership; no preference was changed");
38
+ }
39
+ return value;
40
+ } catch (error) { if (error.code === "ENOENT") return null; throw error; }
41
+ }
42
+
43
+ export function hasInstalledPredictionRoute({ directory, profile, pacUrl } = {}) {
44
+ try {
45
+ const record = recordAt(path.join(directory, "route.json"), profile);
46
+ return record?.pacUrl === pacUrl && isDeepStrictEqual(preferences(profile).value.proxy, { mode: "pac_script", pac_url: pacUrl });
47
+ } catch { return false; }
48
+ }
49
+
50
+ // A write is allowed only while the App is closed. The ownership intent is
51
+ // committed first, so an interrupted activation remains identifiable on off.
52
+ export async function updatePredictionRoute({ directory, profile, pacUrl, remove = false, assertClosed, direct = false,
53
+ writeFile = atomicWriteFileSync } = {}) {
54
+ if (!path.isAbsolute(profile || "") || (!remove && !validPac(pacUrl))) throw new Error("Invalid prediction route binding");
55
+ const recordFile = path.join(directory, "route.json");
56
+ if (remove && !fs.existsSync(recordFile)) return { status: "absent" };
57
+ if (!remove && !direct) return { status: "preserved", reason: "Existing system/company routing was preserved" };
58
+ return withFileLock(`${recordFile}.lock`, () => {
59
+ const record = recordAt(recordFile, profile);
60
+ if (remove && !record) return { status: "absent" };
61
+ let current;
62
+ try { current = preferences(profile); }
63
+ catch (error) {
64
+ if (error.code === "ENOENT" && !remove) return { status: "pending", reason: "App preferences are not initialized" };
65
+ throw error;
66
+ }
67
+ const owned = record && isDeepStrictEqual(current.value.proxy, { mode: "pac_script", pac_url: record.pacUrl });
68
+ if (remove && !owned) {
69
+ // The user replaced the route; retain their edit and remove only our intent.
70
+ fs.unlinkSync(recordFile);return { status: "preserved", reason: "User-edited App route was preserved" };
71
+ }
72
+ if (!remove && owned && record.pacUrl === pacUrl) return { status: "installed" };
73
+ if (!remove && !owned && Object.hasOwn(current.value, "proxy") && !isDeepStrictEqual(current.value.proxy, { mode: "system" })) {
74
+ return { status: "preserved", reason: "Existing App proxy preference was preserved" };
75
+ }
76
+ assertClosed();
77
+ if (!readBoundedFileSync(current.file).equals(current.bytes)) throw new Error("App preferences changed during route setup; retry after quitting the App");
78
+ if (remove) {
79
+ if (record.hadProxy) current.value.proxy = record.previousProxy;
80
+ else delete current.value.proxy;
81
+ } else {
82
+ const next = record || { version: 1, profile, pacUrl, hadProxy: Object.hasOwn(current.value, "proxy"),
83
+ ...(Object.hasOwn(current.value, "proxy") ? { previousProxy: current.value.proxy } : {}) };
84
+ writeFile(recordFile, JSON.stringify({ ...next, pacUrl }, null, 2) + "\n", { preserveMode: false });
85
+ current.value.proxy = { mode: "pac_script", pac_url: pacUrl };
86
+ }
87
+ // Recheck after committing the small intent file, before touching App data.
88
+ assertClosed();
89
+ if (!readBoundedFileSync(current.file).equals(current.bytes)) throw new Error("App preferences changed during route setup; the saved intent was retained");
90
+ writeFile(current.file, JSON.stringify(current.value) + "\n");
91
+ if (remove) fs.unlinkSync(recordFile);
92
+ return { status: remove ? "removed" : "installed" };
93
+ }, { timeoutMs: 100, pollMs: 10 });
94
+ }
@@ -3,11 +3,17 @@ import { operationErrorDetails } from "./operation-error.mjs";
3
3
 
4
4
  export function createPredictionState({ now = () => new Date().toISOString() } = {}) {
5
5
  let state = { configured: false, bridge: "stopped", client_route: "unknown", candidate: "unknown", reason: null,
6
+ launch_route: "unknown", persistence: "unknown", recovery: { attempts: 0, recovered: 0, last_check_at: null },
6
7
  configuration: {}, counters: { configuration_responses: 0, modified: 0, tls_errors: 0, upstream_errors: 0 }, last_event_at: null };
7
8
  return {
8
9
  configure(enabled) { state.configured = enabled === true; },
9
- running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy; },
10
+ running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy;delete state.error; },
10
11
  stopped() { state.bridge = "stopped"; },
12
+ launch(route) { state.launch_route = ["verified", "persisted"].includes(route) ? route : "unverified"; },
13
+ persistence(value) { state.persistence = value.status; },
14
+ checked() { state.recovery.last_check_at = now(); },
15
+ recovering(attempt) { state.bridge = "recovering";state.recovery.attempts = attempt;state.recovery.last_check_at = now(); },
16
+ recovered() { state.bridge = "running";state.reason = null;delete state.error;state.recovery.recovered++; },
11
17
  unavailable(error) {
12
18
  state.bridge = "unavailable";
13
19
  state.reason = redactDiagnosticText(String(error?.message || "Prediction setup failed")).slice(0, 400);