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.
@@ -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) {
@@ -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) {
@@ -1,6 +1,10 @@
1
- import { spawn } from "node:child_process";
1
+ import { spawn, execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
2
5
  import { createInterface } from "node:readline/promises";
3
6
  import { lookupLatestRelease, githubReleaseVersion } from "./version.mjs";
7
+ import { terminalCell } from "./terminal-text.mjs";
4
8
 
5
9
  const PACKAGE_NAME = "codex-copilot-dx";
6
10
  const UPDATE_SPECS = {
@@ -8,6 +12,38 @@ const UPDATE_SPECS = {
8
12
  github: "github:DaleXiao/codex-copilot-dx",
9
13
  };
10
14
 
15
+ function npmLaunch(args, { platform, env }) {
16
+ if (platform !== "win32") return { command: "npm", args, options: {} };
17
+ return { command: path.win32.join(env.SystemRoot || env.WINDIR || "C:\\Windows", "System32", "cmd.exe"),
18
+ args: ["/d", "/s", "/v:off", "/c", `"npm.cmd ${args.join(" ")}"`],
19
+ options: { windowsVerbatimArguments: true, windowsHide: true } };
20
+ }
21
+
22
+ export function inspectPackageUpdateEnvironment({ env = process.env, platform = process.platform,
23
+ packageRoot = fileURLToPath(new URL("../", import.meta.url)), nodePath = process.execPath, exec = execFileSync } = {}) {
24
+ const paths = platform === "win32" ? path.win32 : path;
25
+ const commandName = platform === "win32" ? "npm.cmd" : "npm";
26
+ const searchPath = Object.entries(env).find(([key]) => key.toLowerCase() === "path")?.[1] || "";
27
+ const npmPath = searchPath.split(platform === "win32" ? ";" : ":")
28
+ .filter(Boolean).map(directory => paths.join(directory.replace(/^"|"$/g, ""), commandName))
29
+ .find(file => { try { return fs.statSync(file).isFile(); } catch { return false; } });
30
+ const result = { node: nodePath, package_root: paths.resolve(packageRoot), npm: npmPath || null,
31
+ prefix: null, target: null, state: "unavailable" };
32
+ if (!npmPath) return result;
33
+ try {
34
+ const launch = npmLaunch(["prefix", "--global"], { platform, env });
35
+ const value = exec(launch.command, launch.args, { env, shell: false, stdio: ["ignore", "pipe", "pipe"], encoding: "utf8", timeout: 3000,
36
+ maxBuffer: 64 * 1024, ...launch.options }).trim();
37
+ if (!paths.isAbsolute(value) || /[\r\n\0]/.test(value)) return result;
38
+ result.prefix = paths.normalize(value);
39
+ result.target = paths.join(value, ...(platform === "win32" ? [] : ["lib"]), "node_modules", PACKAGE_NAME);
40
+ const normalize = file => platform === "win32" ? paths.resolve(file).toLowerCase() : paths.resolve(file);
41
+ const ownedGlobal = result.package_root.endsWith(paths.join("node_modules", PACKAGE_NAME));
42
+ result.state = !ownedGlobal ? "checkout" : normalize(result.package_root) === normalize(result.target) ? "matched" : "different";
43
+ return result;
44
+ } catch { return result; } // Preflight cannot replace the installer's normal error handling.
45
+ }
46
+
11
47
  export function normalizeUpdateSource(value) {
12
48
  const source = String(value || "").trim().toLowerCase();
13
49
  if (source === "gh") return "github";
@@ -58,6 +94,7 @@ export async function runPackageUpdateCommand({
58
94
  source,
59
95
  spawnImpl = spawn,
60
96
  fetchImpl = fetch,
97
+ inspectEnvironmentFn = inspectPackageUpdateEnvironment,
61
98
  } = {}) {
62
99
  let selectedSource = normalizeUpdateSource(source);
63
100
  if (source && !selectedSource) throw new Error(`Update source must be npm or github: ${source}`);
@@ -100,10 +137,18 @@ export async function runPackageUpdateCommand({
100
137
  const update = globalUpdateCommand(selectedSource, { platform, releaseTag: release?.tagName });
101
138
  const sourceLabel = selectedSource === "npm" ? "npm registry" : `GitHub release ${release.tagName}`;
102
139
  output.write(`Updating ${PACKAGE_NAME} from ${sourceLabel}...\n`);
103
- const child = spawnImpl(update.command, update.args, {
140
+ const environment = inspectEnvironmentFn({ env, platform });
141
+ if (environment?.state === "different") {
142
+ output.write(`Warning: npm targets ${terminalCell(environment.target)}, not the running package at ${terminalCell(environment.package_root)}. Existing PATH and prefix choices were preserved.\n`);
143
+ }
144
+ // npm.cmd needs cmd.exe. Only fixed install arguments and a validated stable
145
+ // release tag enter this command line; no user-supplied command is evaluated.
146
+ const launch = npmLaunch(update.args, { platform, env });
147
+ const child = spawnImpl(launch.command, launch.args, {
104
148
  env,
105
149
  shell: false,
106
150
  stdio: "inherit",
151
+ ...launch.options,
107
152
  });
108
153
  await waitForExit(child);
109
154
  output.write(`Updated ${PACKAGE_NAME} from ${sourceLabel}. Restart the running adapter to use the new version.\n`);
@@ -99,3 +99,10 @@ export function createResponseFailureDiagnostics({
99
99
  },
100
100
  };
101
101
  }
102
+
103
+ export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers }) {
104
+ const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
105
+ message: "HTTP request failed; original response was preserved." } }, "http.error", { headers });
106
+ return { ...details, request_id: requestId, http_status: statusCode, route,
107
+ origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true };
108
+ }
@@ -381,10 +381,14 @@ export function markStreamFailure() {
381
381
  }
382
382
 
383
383
  export function markResponseModel(model) {
384
+ const context = currentRequestContext();
385
+ if (context) context.model = model;
384
386
  tracker()?.setModel?.(model);
385
387
  }
386
388
 
387
389
  export function markResponseErrorOrigin(origin) {
390
+ const context = currentRequestContext();
391
+ if (context) context.errorOrigin = origin;
388
392
  tracker()?.setErrorOrigin?.(origin);
389
393
  }
390
394
 
@@ -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 { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
@@ -39,7 +39,7 @@ function invalidSettings(filePath, reason) {
39
39
  export function readUserSettings({ env = process.env, home = os.homedir(), strict = false } = {}) {
40
40
  const filePath = userSettingsPath({ env, home });
41
41
  try {
42
- const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
42
+ const parsed = JSON.parse(readBoundedFileSync(filePath, { encoding: "utf8" }));
43
43
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
44
44
  throw invalidSettings(filePath, "expected a JSON object");
45
45
  }