codex-copilot-dx 1.2.5 → 1.2.7

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.
@@ -19,12 +19,27 @@
19
19
  const identity = provider.auth || {};
20
20
  const authRow = tableRow([provider.name, identity.account || "—", states[identity.state] || "unknown",
21
21
  states[provider.state] || "unknown", identity.checked_at || "—", duration(identity.expires_in_ms)], { labels: [2, 3] });
22
- if (provider.reason) localize(authRow.children[3], "state_reason", { state: phrase(states[provider.state] || "unknown"), reason: provider.reason });
22
+ if (provider.reason) {
23
+ const network = provider.network_diagnostic;
24
+ localize(authRow.children[3], "state_reason", { state: phrase(states[provider.state] || "unknown"),
25
+ reason: network ? phrase(`network_cause_${network.cause_code}`) : provider.reason });
26
+ if (network) localize(authRow.children[3], "network_detail", { source: phrase(`network_source_${network.source}`),
27
+ stage: phrase(`network_stage_${network.stage}`), code: network.cause_code, category: provider.reason }, "title");
28
+ }
29
+ if (globalThis.ccdxIcons) {
30
+ globalThis.ccdxIcons.set(authRow.children[2], states[identity.state] || "unknown", globalThis.ccdxIcons.kind(identity.state));
31
+ globalThis.ccdxIcons.set(authRow.children[3], provider.reason ? "state_reason" : states[provider.state] || "unknown", globalThis.ccdxIcons.kind(provider.state),
32
+ provider.reason ? { state: phrase(states[provider.state] || "unknown"), reason: provider.network_diagnostic ? phrase(`network_cause_${provider.network_diagnostic.cause_code}`) : provider.reason } : {});
33
+ }
23
34
  auth.append(authRow);
24
35
  for (const client of provider.clients || []) {
25
36
  const row = tableRow([provider.name, client.name, states[client.state] || client.state,
26
37
  client.gateway || "—", client.last_request_at || "—"], { labels: [2, 3] });
27
38
  if (client.reason) localize(row.children[2], "state_reason", { state: phrase(states[client.state] || "unknown"), reason: client.reason });
39
+ if (globalThis.ccdxIcons) {
40
+ globalThis.ccdxIcons.set(row.children[2], client.reason ? "state_reason" : states[client.state] || client.state, globalThis.ccdxIcons.kind(client.state), client.reason ? { state: phrase(states[client.state] || "unknown"), reason: client.reason } : {});
41
+ if (["running", "unavailable"].includes(client.gateway)) globalThis.ccdxIcons.set(row.children[3], client.gateway, globalThis.ccdxIcons.kind(client.gateway));
42
+ }
28
43
  clients.append(row);
29
44
  }
30
45
  if (provider.requests) {
@@ -0,0 +1,151 @@
1
+ (() => {
2
+ const el = id => document.getElementById(id), language = globalThis.ccdxLanguage;
3
+ const label = (node, key, values) => language.set(node, key, values);
4
+ const text = (id, key, values) => label(el(id), key, values);
5
+ let account = null, pending = false, pollTimer = null, stopped = false, repairPreview = null;
6
+ const activeFlow = () => ["starting", "authorizing", "verifying"].includes(account?.operation?.state);
7
+ async function api(path, body) {
8
+ const response = await fetch(`/_ccdx/ui/${path}`, { method: body ? "POST" : "GET", cache: "no-store",
9
+ headers: { "X-CCDX-Dashboard": "1", ...(body ? { "Content-Type": "application/json" } : {}) },
10
+ ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(35000) });
11
+ const data = await response.json();
12
+ if (!response.ok) throw Object.assign(new Error("tools_action_failed"), { code: data.code || "tools_action_failed" });
13
+ return data;
14
+ }
15
+ function status(id, key, kind, values) { globalThis.ccdxIcons.set(el(id), key, kind, values); }
16
+ function field(list, key, value, kind) {
17
+ const term = document.createElement("dt"), detail = document.createElement("dd");label(term, key);
18
+ if (kind) globalThis.ccdxIcons.set(detail, value, kind);else detail.textContent = value;
19
+ list.append(term, detail);
20
+ }
21
+ function syncSource() {
22
+ const github = selectedProvider === "github";
23
+ el("github-account").hidden = !github;
24
+ el("m365-source-access").hidden = selectedProvider !== "m365";
25
+ el("source-account-panel").setAttribute("aria-labelledby", `model-provider-${selectedProvider}`);
26
+ }
27
+ function renderAccount(data) {
28
+ account = data;
29
+ const online = data.online, op = data.operation;
30
+ const invalid = online?.reason === "github_token_invalid", failed = online?.checked && !online.ok;
31
+ text("github-account-name", data.login || (data.saved ? "tools_saved_account" : "tools_not_signed_in"));
32
+ status("github-account-state", invalid ? "tools_signin_invalid" : online?.ok ? "tools_verified" : data.saved ? "saved_locally" : "tools_not_signed_in",
33
+ invalid ? "warning" : online?.ok ? "ok" : data.saved ? "unknown" : "unavailable");
34
+ text("github-account-hint", !data.saved ? "tools_login_hint" : invalid ? "tools_saved_not_valid" : failed ? "tools_access_hint" : "tools_account_hint");
35
+ const fields = el("github-account-fields");fields.replaceChildren();
36
+ field(fields, "tools_saved_signin", data.saved ? "saved_locally" : "tools_not_signed_in", data.saved ? "ok" : "unavailable");
37
+ for (const [id, key] of [["identity", "tools_github_identity"], ["access", "tools_copilot_access"], ["models", "tools_catalog_read"]]) {
38
+ const result = online?.stages?.[id] || "not_checked";
39
+ field(fields, key, result === "passed" ? "tools_verified" : result === "invalid" ? "tools_signin_invalid" : result === "unavailable" ? "tools_unavailable" : "tools_not_checked",
40
+ result === "passed" ? "ok" : result === "invalid" ? "warning" : result === "unavailable" ? "unavailable" : "unknown");
41
+ }
42
+ field(fields, "last_verified", data.checked_at ? new Date(data.checked_at).toLocaleString() : "—");
43
+ label(el("github-signin"), data.saved ? "tools_reauth" : "tools_login");
44
+ el("github-signin").hidden = data.saved && !invalid;
45
+ el("github-signin").disabled = pending || activeFlow();el("github-check").disabled = pending || activeFlow() || !data.saved;
46
+ el("github-logout").disabled = pending || activeFlow() || !data.saved;
47
+ el("github-force-reauth").disabled = pending || activeFlow();
48
+ el("github-login-flow").hidden = !activeFlow();
49
+ text("github-flow-state", op?.state === "verifying" ? "tools_verifying" : "tools_waiting");
50
+ el("github-user-code").textContent = op?.user_code || "—";
51
+ el("github-authorize").hidden = op?.state !== "authorizing";
52
+ el("github-authorize").href = op?.verification_uri === "https://github.com/login/device" ? op.verification_uri : "https://github.com/login/device";
53
+ el("github-cancel").disabled = pending;
54
+ el("github-check-code").textContent = online?.reason || "—";
55
+ el("github-check-http").textContent = online?.http_status || "—";
56
+ text("github-store", data.store === "ccdx" ? "tools_ccdx_store" : "tools_legacy_store");
57
+ if (op?.state === "complete") text("github-account-note", op.reason === "auth_restart_required" ? "auth_restart_required" : "tools_signin_complete");
58
+ else if (["failed", "cancelled"].includes(op?.state)) text("github-account-note", op.reason || "tools_action_failed");
59
+ else if (failed) text("github-account-note", online.reason === "github_token_invalid" ? "tools_reauth_hint" : online.reason === "copilot_access_denied" ? "tools_access_denied" : "tools_network_hint");
60
+ else if (online?.ok) text("github-account-note", "tools_check_complete");
61
+ else if (!activeFlow()) el("github-account-note").textContent = "";
62
+ schedulePoll();
63
+ }
64
+ function schedulePoll() {
65
+ clearTimeout(pollTimer);pollTimer = null;
66
+ if (stopped || !activeFlow() || document.visibilityState !== "visible") return;
67
+ pollTimer = setTimeout(async () => {
68
+ try {
69
+ const before = account.operation.state, data = await api("account");renderAccount(data);
70
+ if (before !== data.operation?.state && data.operation?.state === "complete") {
71
+ dashboardRefresh.invalidate("auth");dashboardRefresh.invalidate("models", { clear: true });
72
+ void dashboardRefresh.refreshVisible({ force: true });
73
+ }
74
+ } catch { text("github-account-note", "tools_read_failed");schedulePoll(); }
75
+ }, 1500);
76
+ }
77
+ async function accountAction(action) {
78
+ if (pending) return;
79
+ pending = true;if (account) renderAccount(account);text("github-account-note", "checking");
80
+ let failureCode = null;
81
+ try { renderAccount(await api("account", action)); }
82
+ catch (error) { failureCode = error.code; }
83
+ finally { pending = false;if (account) renderAccount(account);if (failureCode) text("github-account-note", failureCode); }
84
+ }
85
+ el("github-signin").addEventListener("click", () => void accountAction({ action: "start", reauth: account?.saved === true }));
86
+ el("github-force-reauth").addEventListener("click", () => void accountAction({ action: "start", reauth: true }));
87
+ el("github-check").addEventListener("click", () => void accountAction({ action: "check" }));
88
+ el("github-cancel").addEventListener("click", () => { if (account?.operation) void accountAction({ action: "cancel", id: account.operation.id }); });
89
+ el("github-logout").addEventListener("click", () => { if (window.confirm(language.format("tools_logout_confirm"))) void accountAction({ action: "logout", confirmed: true }); });
90
+ async function loadAccount() { try { renderAccount(await api("account")); } catch { text("github-account-note", "tools_read_failed"); } }
91
+ function renderChecks(data) {
92
+ const body = el("checks-body");body.replaceChildren();
93
+ const groups = new Map();
94
+ for (const check of data.checks || []) { if (!groups.has(check.id)) groups.set(check.id, []);groups.get(check.id).push(check); }
95
+ for (const [id, checks] of groups) {
96
+ const row = document.createElement("tr"), name = document.createElement("td"), result = document.createElement("td"), details = document.createElement("td");
97
+ const kind = checks.some(check => check.kind === "err" || check.kind === "warn") ? "warning" : checks.some(check => check.kind === "ok") ? "ok" : "unknown";
98
+ label(name, ({ "github-auth": "tools_github_signin", "codex-config": "tools_codex_settings", "windows-command": "tools_windows_command", provider: "source" })[id] || "tools_environment");
99
+ globalThis.ccdxIcons.set(result, kind === "warning" ? "tools_needs_attention" : kind === "ok" ? "tools_verified" : "tools_observed", kind);
100
+ const disclosure = document.createElement("details"), summary = document.createElement("summary");label(summary, "tools_details");disclosure.append(summary);
101
+ for (const check of checks) { const p = document.createElement("p");p.className = "hint";p.textContent = check.message;disclosure.append(p); }
102
+ details.append(disclosure);row.append(name, result, details);body.append(row);
103
+ }
104
+ if (!groups.size) text("checks-note", "tools_checks_empty");
105
+ else text("checks-note", "tools_checks_completed", { time: new Date(data.checked_at).toLocaleTimeString() });
106
+ }
107
+ async function localAction(action, button) {
108
+ button.disabled = true;text("checks-note", "checking");
109
+ try {
110
+ const data = await api("checks", action);
111
+ if (action.action === "check") renderChecks(data);
112
+ else if (action.action === "preview") {
113
+ repairPreview = data;el("config-repair-preview").hidden = false;
114
+ const fields = el("config-repair-fields");fields.replaceChildren();
115
+ field(fields, "tools_managed_fields", data.managed_keys.join(", "));
116
+ field(fields, "tools_backup", data.backup);
117
+ el("config-preview-details").textContent = data.checks.map(check => check.message).join("\n");
118
+ text("checks-note", "tools_review_repair");
119
+ } else if (action.action === "repair") {
120
+ el("config-repair-preview").hidden = true;repairPreview = null;
121
+ if (data.local?.checked_at) renderChecks(data.local);
122
+ text("checks-note", ["verified", "unchanged"].includes(data.status) ? "tools_repair_complete" : "tools_repair_preserved");
123
+ } else if (action.action === "network") { el("network-check-result").textContent = data.summary;text("checks-note", "tools_network_read_only"); }
124
+ else if (action.action === "report") {
125
+ const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: "application/json" }));
126
+ const link = document.createElement("a");link.href = url;link.download = "ccdx-diagnostic-report.json";link.click();
127
+ setTimeout(() => URL.revokeObjectURL(url), 1000);text("checks-note", "tools_report_saved");
128
+ }
129
+ } catch (error) { text("checks-note", error.code); }
130
+ finally { button.disabled = false; }
131
+ }
132
+ for (const [id, action] of [["check-local", "check"], ["check-network", "network"], ["export-report", "report"], ["preview-config-repair", "preview"]]) {
133
+ el(id).addEventListener("click", () => void localAction({ action }, el(id)));
134
+ }
135
+ el("apply-config-repair").addEventListener("click", () => { if (repairPreview) void localAction({ action: "repair", revision: repairPreview.revision }, el("apply-config-repair")); });
136
+ el("cancel-config-repair").addEventListener("click", () => { repairPreview = null;el("config-repair-preview").hidden = true; });
137
+ el("check-account-link").addEventListener("click", () => { chooseProvider("github");location.hash = "models"; });
138
+ async function navigate() {
139
+ syncSource();
140
+ if (location.hash === "#models") await loadAccount();
141
+ if (location.hash === "#checks") { try { const data = await api("checks");if (data.checked_at) renderChecks(data); } catch { text("checks-note", "tools_read_failed"); } }
142
+ }
143
+ window.addEventListener("ccdx:source-view", syncSource);
144
+ window.addEventListener("ccdx:providers", () => { queueMicrotask(() => { syncSource();if (location.hash === "#models" && !pending) void loadAccount(); }); });
145
+ el("refresh").addEventListener("click", () => { if (location.hash === "#models" && !pending) void loadAccount(); });
146
+ window.addEventListener("hashchange", () => void navigate());
147
+ window.addEventListener("pagehide", () => { stopped = true;clearTimeout(pollTimer); });
148
+ window.addEventListener("pageshow", () => { stopped = false;schedulePoll(); });
149
+ document.addEventListener("visibilitychange", schedulePoll);
150
+ void navigate();
151
+ })();
@@ -285,3 +285,26 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
285
285
 
286
286
  :root[data-theme="light"] #animation-settings { --ansi-white:#234231;--ansi-159:#116b64;--ansi-123:#0d7771;--ansi-87:#116b75;--ansi-51:#14697e;--ansi-45:#1a6183;--ansi-39:#265f8d;--ansi-33:#365a8d; }
287
287
  :root[data-theme="light"] #animation-settings[data-terminal-palette="klein"] { --ansi-white:#002fa7;--ansi-159:#002fa7;--ansi-123:#002fa7;--ansi-87:#002fa7;--ansi-51:#002fa7;--ansi-45:#002fa7;--ansi-39:#002fa7;--ansi-33:#002fa7; }
288
+
289
+ .state-label { display:inline-flex; align-items:center; gap:8px; max-width:100%; vertical-align:middle; white-space:normal; }
290
+ .state-icon { width:16px; height:16px; flex:none; fill:none; stroke:currentColor; stroke-width:1.6; stroke-linecap:round; stroke-linejoin:round; }
291
+ .state-label.state-ok, .state-label.state-running { color:var(--accent); }
292
+ .state-label.state-warning { color:var(--bad); }
293
+ .state-label.state-unavailable, .state-label.state-unknown { color:var(--muted); }
294
+ .state-label > span { color:inherit; white-space:normal; }
295
+ .badge:has(.state-label)::before { display:none; }
296
+ .source-browse-note { margin:12px 0 20px; }
297
+ .account-name { margin:18px 0 6px; font-size:19px; color:var(--strong); font-weight:650; }
298
+ .account-fields { display:grid; grid-template-columns:minmax(110px,150px) minmax(0,1fr); gap:10px 18px; margin:20px 0; font-size:12px; line-height:1.7; }
299
+ .account-fields dt { color:var(--muted); }
300
+ .account-fields dd { margin:0; min-width:0; }
301
+ .tool-details, .tool-flow { margin-top:18px; padding-top:16px; border-top:1px solid var(--border); }
302
+ .tool-details summary, .tool-flow h3 { color:var(--heading); font-size:12px; }
303
+ .device-code { display:block; color:var(--accent); font-size:23px; letter-spacing:.1em; margin:16px 0; }
304
+ .tool-link { display:inline-flex; min-height:36px; align-items:center; color:var(--accent); margin-right:16px; }
305
+ .tool-code { background:var(--page); border:1px solid var(--border); padding:14px; font:inherit; font-size:12px; line-height:1.7; white-space:pre-wrap; overflow-wrap:anywhere; }
306
+ .checks-table td { vertical-align:top; white-space:normal; }
307
+ .checks-table th:first-child { width:23%; }
308
+ .checks-table th:nth-child(2) { width:21%; }
309
+ .checks-table details p { margin:8px 0; }
310
+ @media(max-width:640px) { .account-fields { grid-template-columns:100px minmax(0,1fr); gap:10px; } .checks-table { min-width:530px; } }
@@ -269,6 +269,7 @@ function chooseProvider(id) {
269
269
  if (previous) applyModels(previous, { changed: true });
270
270
  else { emptyTable("live-models-body", 6, "reading_provider_catalog");text("models-note", "reading_provider_catalog"); }
271
271
  element("live-models-body").setAttribute("aria-labelledby", `model-provider-${id}`);
272
+ window.dispatchEvent(new CustomEvent("ccdx:source-view"));
272
273
  void loadModels();
273
274
  }
274
275
 
@@ -303,7 +304,7 @@ function applyProviders(data, { changed }) {
303
304
  let button = providerTabs.get(provider.id);
304
305
  if (!button) {
305
306
  button = document.createElement("button");button.type = "button";button.setAttribute("role", "tab");
306
- button.id = `model-provider-${provider.id}`;button.setAttribute("aria-controls", "live-models-body");
307
+ button.id = `model-provider-${provider.id}`;button.setAttribute("aria-controls", "source-account-panel");
307
308
  button.addEventListener("click", () => chooseProvider(provider.id));
308
309
  button.addEventListener("keydown", event => {
309
310
  if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
@@ -393,6 +394,8 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
393
394
  state: state => {
394
395
  text("connection", state.pending && !state.value ? "reading" : state.error ? "unavailable_eb0be" : "service_reachable");
395
396
  element("connection").className = `badge ${state.pending ? "neutral" : state.error ? "bad" : "good"}`;
397
+ globalThis.ccdxIcons?.set(element("connection"), state.pending && !state.value ? "reading" : state.error ? "unavailable_eb0be" : "service_reachable",
398
+ state.pending && !state.value ? "unknown" : state.error ? "unavailable" : "running");
396
399
  if (state.error) refreshTime(element("updated"), state);
397
400
  for (const node of timestamps.get("status")) refreshTime(node, state);
398
401
  },
@@ -427,21 +430,23 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
427
430
  if (state.error) {
428
431
  const message = String(state.error.message || state.error).slice(0, 240);
429
432
  const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
430
- if (httpError) text("models-note", "live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] });
431
- else text("models-note", message);
432
433
  const sourceReason = /^Model catalog unavailable \/ (m365_[a-z0-9_]+)$/.exec(message);
433
- const reason = httpError ? phrase("live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] })
434
+ const diagnostic = state.error.diagnostic || {}, network = diagnostic.network;
435
+ const reason = network ? phrase(`network_cause_${network.cause_code}`) : httpError ? phrase("live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] })
434
436
  : sourceReason ? phrase("source_catalog_unavailable", { code: sourceReason[1] }) : phrase(message);
435
437
  const source = providerEntries.find(entry => entry.id === selectedProvider)?.name || selectedProvider;
436
438
  const previous = modelSnapshots.get(selectedProvider);
439
+ element("models-note").removeAttribute("data-i18n");
437
440
  element("models-note").replaceChildren();
438
441
  const summary = document.createElement("span"), kept = document.createElement("span");
439
442
  localize(summary, "source_check_failed", { source });
440
443
  localize(kept, previous?.checked_at ? "source_check_previous" : "source_check_none", { time: previous?.checked_at ? new Date(previous.checked_at).toLocaleTimeString() : "" });
441
444
  element("models-note").append(summary, document.createElement("br"), kept);
442
445
  const fields = element("model-check-fields");fields.replaceChildren();
443
- const diagnostic = state.error.diagnostic || {};
444
- for (const [key, value] of [["source", source], ["source_check_time", diagnostic.checked_at], ["source_check_reason", reason], ["http_status", diagnostic.http_status]]) {
446
+ for (const [key, value] of [["source", source], ["source_check_time", diagnostic.checked_at], ["source_check_reason", reason],
447
+ ["network_route_source", network ? phrase(`network_source_${network.source}`) : null],
448
+ ["network_failure_stage", network ? phrase(`network_stage_${network.stage}`) : null],
449
+ ["network_cause_code", network?.cause_code], ["http_status", diagnostic.http_status]]) {
445
450
  if (value === null || value === undefined || value === "") continue;
446
451
  const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
447
452
  if (value?.key) localize(detail, value.key, value.values);else detail.textContent = String(value).slice(0, 300);
@@ -1,5 +1,6 @@
1
1
  import os from "node:os";
2
2
  import { isProviderId } from "./provider-metadata.mjs";
3
+ import { m365NetworkDiagnostic } from "./providers/m365-network-diagnostic.mjs";
3
4
  import { fetchLiveCopilotModels } from "./live-models.mjs";
4
5
  import { authStatus } from "./auth-status.mjs";
5
6
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
@@ -123,6 +124,7 @@ function dashboardProviders(providerStateFn, authStatusFn) {
123
124
  return { id: entry.id, name: label(entry.name) || entry.id, enabled: entry.enabled === true,
124
125
  selection: { codex: entry.selection?.codex === true, models_required: entry.selection?.models_required === true },
125
126
  state: code(entry.state) || "unknown", reason: code(entry.reason), generation: finite(entry.generation),
127
+ network_diagnostic: m365NetworkDiagnostic(entry.network_diagnostic),
126
128
  auth: { state: code(auth.state) || "unknown", account: label(auth.account), token_cached: auth.token_cached === true,
127
129
  expires_in_ms: finite(auth.expires_in_ms), checked_at: label(auth.checked_at) || null },
128
130
  models: { count: finite(entry.models?.count), source: code(entry.models?.source) || "unknown", checked_at: label(entry.models?.checked_at) || null },
@@ -146,6 +148,7 @@ export async function handleDashboardApi(req, res, pathname, {
146
148
  updateStatusFn,
147
149
  serviceControl,
148
150
  applyAnimation,
151
+ tools,
149
152
  } = {}) {
150
153
  if (!isLoopbackAddress(req.socket?.remoteAddress)
151
154
  || req.headers?.host === undefined
@@ -158,6 +161,10 @@ export async function handleDashboardApi(req, res, pathname, {
158
161
  return;
159
162
  }
160
163
 
164
+ if (["/_ccdx/ui/account", "/_ccdx/ui/checks"].includes(pathname)) {
165
+ return tools.handle(req, res, pathname, sendJson, sameOrigin);
166
+ }
167
+
161
168
  if (pathname === PROVIDERS_PATH && req.method === "GET") {
162
169
  try { sendJson(res, 200, { source: "provider_status", providers: dashboardProviders(providerStateFn, authStatusFn) }); }
163
170
  catch { sendJson(res, 500, { error: "Could not read provider status" }); }
@@ -303,6 +310,7 @@ export async function handleDashboardApi(req, res, pathname, {
303
310
  const message = /^m365_[a-z0-9_]+$/.test(error.code || "") ? `Model catalog unavailable / ${error.code}` : liveModelError(error);
304
311
  if (!res.destroyed && !res.writableEnded) sendJson(res, error.statusCode || 502, { error: message,
305
312
  diagnostic: { provider: provider || null, checked_at: new Date().toISOString(), message,
313
+ network: m365NetworkDiagnostic(error.network_diagnostic),
306
314
  http_status: Number(/\bHTTP (\d{3})\b/.exec(message)?.[1]) || finite(error.statusCode),
307
315
  retry_after_ms: finite(error.retryAfterMs) } });
308
316
  } finally { abort.cleanup(); }
@@ -0,0 +1,43 @@
1
+ import { createAccountTools } from "./account-tools.mjs";
2
+ import { createLocalTools } from "./local-tools.mjs";
3
+ import { createRequestAbort, readJsonBody } from "./http-transport.mjs";
4
+
5
+ export const TOOL_PATHS = new Set(["/_ccdx/ui/account", "/_ccdx/ui/checks"]);
6
+ export function createDashboardTools(options = {}) {
7
+ const accounts = options.accountTools || createAccountTools({ ...options, onChanged: options.credentialsChanged });
8
+ const local = options.localTools || createLocalTools(options);
9
+ return {
10
+ dispose() { accounts.dispose(); },
11
+ async handle(req, res, pathname, sendJson, sameOrigin) {
12
+ const account = pathname === "/_ccdx/ui/account";
13
+ if (req.method === "GET") {
14
+ try { sendJson(res, 200, account ? accounts.snapshot() : local.snapshot()); }
15
+ catch { sendJson(res, 409, { error: "tools_read_failed", code: "tools_read_failed" }); }
16
+ return;
17
+ }
18
+ if (req.method !== "POST") { sendJson(res, 405, { error: "Use GET or POST" });return; }
19
+ if (!sameOrigin(req)) { sendJson(res, 403, { error: "Tools require the same-origin dashboard" });return; }
20
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { sendJson(res, 415, { error: "Expected application/json" });return; }
21
+ const abort = createRequestAbort(req, res);abort.setTimeout(5000, "request_body_timeout");
22
+ try {
23
+ const input = await readJsonBody(req, { maxBodyBytes: 4096, maxDecodedBodyBytes: 4096, signal: abort.signal });
24
+ abort.clearTimeout();
25
+ const fields = account ? { check: ["action"], start: ["action", "reauth"], cancel: ["action", "id"], logout: ["action", "confirmed"], reload: ["action"] }
26
+ : { check: ["action"], preview: ["action"], repair: ["action", "revision"], network: ["action"], report: ["action"] };
27
+ const allowed = input && typeof input === "object" && !Array.isArray(input) && fields[input.action];
28
+ if (!allowed || Object.keys(input).some(key => !allowed.includes(key)) || (input.action === "start" && input.reauth !== undefined && typeof input.reauth !== "boolean")) {
29
+ sendJson(res, 400, { error: "tools_invalid_action", code: "tools_invalid_action" });return;
30
+ }
31
+ const target = account ? accounts : local;
32
+ if (!account && input.action === "report" && !local.snapshot().checked_at) await local.check();
33
+ const value = await (input.action === "start" ? target.start({ reauth: input.reauth })
34
+ : input.action === "cancel" ? target.cancel(input.id) : input.action === "logout" ? target.logout(input)
35
+ : input.action === "repair" ? target.repair(input) : target[input.action]());
36
+ if (!res.destroyed && !res.writableEnded) sendJson(res, 200, value);
37
+ } catch (error) {
38
+ const code = /^(auth|copilot|config|tools)_[a-z_]+$/.test(error.code || "") ? error.code : "tools_action_failed";
39
+ sendJson(res, error.statusCode || 409, { error: code, code });
40
+ } finally { abort.cleanup(); }
41
+ },
42
+ };
43
+ }
package/src/dashboard.mjs CHANGED
@@ -12,6 +12,8 @@ const ASSETS = new Map([
12
12
  ["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
13
13
  ["/usage.js", ["./dashboard/usage.js", "text/javascript; charset=utf-8"]],
14
14
  ["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
15
+ ["/icons.js", ["./dashboard/icons.js", "text/javascript; charset=utf-8"]],
16
+ ["/tools.js", ["./dashboard/tools.js", "text/javascript; charset=utf-8"]],
15
17
  ]);
16
18
 
17
19
  export async function serveDashboard(req, res, pathname) {
package/src/doctor.mjs CHANGED
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
4
  import net from "node:net";
5
- import { githubTokenPath, readGithubTokenMetadata, validateGithubToken } from "./auth.mjs";
5
+ import { githubTokenPath, managedGithubTokenPath, readGithubTokenMetadata, validateGithubToken } from "./auth.mjs";
6
6
  import {
7
7
  AUTH_PROFILE_CODEX,
8
8
  readAuthProfileCredentials,
@@ -65,7 +65,8 @@ export function inspectGitHubToken({ home = os.homedir() } = {}) {
65
65
  export function inspectAuthProfiles({ home = os.homedir() } = {}) {
66
66
  return [
67
67
  ...inspectGitHubToken({ home }),
68
- { kind: "ok", message: "Codex authentication profile uses the legacy path" },
68
+ { kind: "info", message: githubTokenPath(home) === managedGithubTokenPath(home)
69
+ ? "Codex authentication profile uses the CCDX-owned store" : "Codex authentication profile uses the legacy path" },
69
70
  ];
70
71
  }
71
72
 
@@ -0,0 +1,53 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import { createHash } from "node:crypto";
4
+ import { collectDoctorChecks } from "./doctor.mjs";
5
+ import { inspectCodexConfig, repairCodexConfig } from "./codex-config-doctor.mjs";
6
+ import { codexPaths } from "./codex-paths.mjs";
7
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
8
+ import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
9
+ import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
10
+ import { localPackageVersion } from "./version.mjs";
11
+
12
+ export function createLocalTools({ home = os.homedir(), env = process.env, host = "127.0.0.1", port = 2026,
13
+ platform = process.platform, collect = collectDoctorChecks, inspectConfig = inspectCodexConfig, repairConfig = repairCodexConfig,
14
+ inspectNetwork = inspectPredictionEnvironment } = {}) {
15
+ const options = { home, env, host, port, platform };
16
+ let last = null, flight = null;
17
+ const safe = text => redactDiagnosticText(String(text || "")).split(home).join("~")
18
+ .replace(/[\w.+-]+@[\w.-]+/g, "[account]").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 600);
19
+ const project = checks => checks.slice(0, 80).map(check => ({ id: /^[a-z-]{1,60}$/.test(check.id || "") ? check.id : "local",
20
+ kind: ["ok", "info", "warn", "err"].includes(check.kind) ? check.kind : "info", message: safe(check.message) }));
21
+ function snapshot() { return { source: "local_tools", ...last }; }
22
+ async function check() {
23
+ if (flight) return flight;
24
+ flight = Promise.resolve().then(async () => {
25
+ last = { checked_at: new Date().toISOString(), checks: project(await collect({ ...options, checkAdapter: false })) };
26
+ return snapshot();
27
+ }).finally(() => { flight = null; });
28
+ return flight;
29
+ }
30
+ function revision() {
31
+ try { return createHash("sha256").update(fs.readFileSync(codexPaths(options).config)).digest("hex"); }
32
+ catch (error) { if (error.code === "ENOENT") return "missing";throw error; }
33
+ }
34
+ function preview() {
35
+ return { source: "config_repair_preview", revision: revision(), checks: project(inspectConfig(options)),
36
+ managed_keys: ["openai_base_url", "model_context_window", "model_auto_compact_token_limit", "shell_environment_policy", "features.context_management"],
37
+ backup: "config.toml.ccdx-doctor.bak" };
38
+ }
39
+ function repair(input) {
40
+ if (typeof input.revision !== "string" || input.revision !== revision()) throw Object.assign(new Error("config_preview_changed"), { code: "config_preview_changed", statusCode: 409 });
41
+ const result = repairConfig({ ...options, expectedRevision: input.revision });
42
+ const checks = project(inspectConfig(options).map(check => ({ ...check, id: "codex-config" })));
43
+ if (last) last = { checked_at: new Date().toISOString(), checks: [...last.checks.filter(check => check.id !== "codex-config"), ...checks] };
44
+ return { source: "config_repair_result", status: result.status, changed: result.changed === true,
45
+ checks, local: snapshot() };
46
+ }
47
+ function network() {
48
+ const value = inspectNetwork({ env, platform });
49
+ return { source: "network_check", checked_at: new Date().toISOString(), summary: safe(formatPredictionEnvironment(value.summary)) };
50
+ }
51
+ return { snapshot, check, preview, repair, network, report: () => ({ version: localPackageVersion(),
52
+ exported_at: new Date().toISOString(), scope: "local checks only; accounts and credentials omitted", ...snapshot() }) };
53
+ }
@@ -42,7 +42,7 @@ export function inspectPredictionEnvironment({ env = process.env, platform = pro
42
42
  network = { settings };
43
43
  }
44
44
  } else {
45
- const systemProxy = exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2000, maxBuffer: 64 * 1024 });
45
+ const systemProxy = platform === "darwin" ? exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2000, maxBuffer: 64 * 1024 }) : "";
46
46
  network = { networkRoute: resolveNetworkRoute({ env, systemProxy }) };
47
47
  }
48
48
  } catch (error) {
@@ -21,6 +21,17 @@ function variable(env, lower, upper) {
21
21
  return { value: String(env[key] || "").trim(), source: key };
22
22
  }
23
23
 
24
+ function systemBypassRule(value) {
25
+ const rule = value.trim().toLowerCase();
26
+ const match = /^(\d+(?:\.\d+){0,2})\/(\d{1,2})$/.exec(rule);
27
+ if (!match) return rule;
28
+ const octets = match[1].split("."), prefix = Number(match[2]);
29
+ if (!/^(0|[1-9]\d?)$/.test(match[2]) || prefix > octets.length * 8 || octets.some(part => !/^(0|[1-9]\d{0,2})$/.test(part) || Number(part) > 255)) {
30
+ throw routeError("proxy_bypass_invalid", "Invalid system proxy bypass CIDR rule; existing routes were preserved");
31
+ }
32
+ return `${[...octets, ...Array(4 - octets.length).fill("0")].join(".")}/${prefix}`;
33
+ }
34
+
24
35
  export function resolveNetworkRoute({ env = process.env, systemProxy = "", checkApi = true } = {}) {
25
36
  const api = String(env.CODEX_API_BASE_URL || "").trim().replace(/\/+$/, "");
26
37
  if (checkApi && api && api !== OFFICIAL_API) {
@@ -44,7 +55,7 @@ export function resolveNetworkRoute({ env = process.env, systemProxy = "", check
44
55
  const https = proxy(httpsEnv.value, httpsEnv.source) || proxy(allEnv.value, allEnv.source) || system("HTTPS", "http") || system("SOCKS", "socks5");
45
56
  const noProxy = variable(env, "no_proxy", "NO_PROXY").value;
46
57
  const exceptions = /ExceptionsList\s*:\s*<array>\s*\{([^}]+)\}/.exec(systemProxy)?.[1] || "";
47
- const bypass = [...new Set([...noProxy.split(","), ...[...exceptions.matchAll(/\d+\s*:\s*([^\n]+)/g)].map((m) => m[1])]
58
+ const bypass = [...new Set([...noProxy.split(","), ...[...exceptions.matchAll(/\d+\s*:\s*([^\n]+)/g)].map((m) => systemBypassRule(m[1]))]
48
59
  .map((s) => s.trim().toLowerCase()).filter(Boolean))];
49
60
  return { http, https, bypass, rules: compileBypassRules(bypass), excludeSimple: settings.ExcludeSimpleHostnames === "1" };
50
61
  }
@@ -1,5 +1,5 @@
1
- export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js", "/console.js", "/updates.js"]);
2
- export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates"]);
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js"]);
2
+ export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks"]);
3
3
 
4
4
  export function isOptionalRoute(method, pathname) {
5
5
  return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
@@ -10,12 +10,18 @@ export function isOptionalRoute(method, pathname) {
10
10
  // shared HTTP dispatcher and cannot initialize or change core inference.
11
11
  export function createOptionalRoutes(options = {}) {
12
12
  let imageMcpHandler = options.imageMcpHandler || null;
13
+ let tools = null;
13
14
  return {
15
+ dispose() { tools?.dispose(); },
14
16
  imageStats() { return imageMcpHandler?.stats?.(); },
15
17
  async handle(req, res, pathname) {
16
18
  if (DASHBOARD_API_PATHS.has(pathname)) {
17
19
  const { handleDashboardApi } = await import("./dashboard-api.mjs");
18
- return handleDashboardApi(req, res, pathname, options.dashboardOptions);
20
+ if (["/_ccdx/ui/account", "/_ccdx/ui/checks"].includes(pathname)) {
21
+ const { createDashboardTools } = await import("./dashboard-tools.mjs");
22
+ tools ||= createDashboardTools(options.dashboardOptions);
23
+ }
24
+ return handleDashboardApi(req, res, pathname, { ...options.dashboardOptions, tools });
19
25
  }
20
26
  if ((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname)) {
21
27
  const { serveDashboard } = await import("./dashboard.mjs");
@@ -9,13 +9,14 @@ import { requestM365Accounts } from "./providers/m365-auth.mjs";
9
9
  import { publicM365Accounts, accountChoiceId, m365AccountMessage } from "./providers/m365-accounts.mjs";
10
10
  import { providerRegistry } from "./provider-registry.mjs";
11
11
  import { createClaudeClientLifecycle } from "./claude-client-lifecycle.mjs";
12
+ import { m365NetworkMessage } from "./providers/m365-network-diagnostic.mjs";
12
13
 
13
14
  const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
14
15
  { code: reason, statusCode: 503 });
15
16
 
16
17
  // Composition owns source selection. Providers never modify Codex, prediction,
17
18
  // image configuration or each other's credentials.
18
- export function createProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", home, env = process.env, platform = process.platform,
19
+ export function createProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
19
20
  corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
20
21
  discoverM365 = requestM365Accounts } = {}) {
21
22
  const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
@@ -80,7 +81,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
80
81
  return m365;
81
82
  })().catch(error => {
82
83
  reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_unavailable";
83
- log("info", m365AccountMessage(reason));return null;
84
+ log("info", m365NetworkMessage(m365?.snapshot().network_diagnostic) || m365AccountMessage(reason));return null;
84
85
  }).finally(() => { if (pending === operation) pending = null; });
85
86
  pending = operation;return operation;
86
87
  }
@@ -205,8 +206,8 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
205
206
  { id: "github", name: "GitHub Copilot", generation: dashboardGeneration(github), enabled: true, state: service.token_cached ? "ready" : "unknown",
206
207
  auth: { state: "unknown", token_cached: service.token_cached === true, expires_in_ms: service.token_expires_in_ms ?? null },
207
208
  models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
208
- clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "github", state: "configured" }] },
209
- { id: "m365", name: "Microsoft 365", generation: m365 ? dashboardGeneration(m365) : 0, enabled, state: ms.state, reason: ms.reason,
209
+ clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "github", state: githubClientConfigured ? "configured" : "unknown" }] },
210
+ { id: "m365", name: "Microsoft 365", generation: m365 ? dashboardGeneration(m365) : 0, enabled, state: ms.state, reason: ms.reason, network_diagnostic: ms.network_diagnostic,
210
211
  auth: { state: ms.token_cached ? "authorized" : !enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
211
212
  account: ms.account?.login || "", token_cached: ms.token_cached === true,
212
213
  tenant: ms.account?.tenant || "", selection_source: ms.account?.selection_source || null,
@@ -0,0 +1,28 @@
1
+ // Only fixed codes leave the network layer; raw proxy settings and errors do not.
2
+ const messages = Object.freeze({
3
+ proxy_discovery_failed: "Could not read system proxy settings. Existing settings kept.",
4
+ proxy_bypass_invalid: "Invalid proxy exception rule. Existing settings kept.",
5
+ proxy_system_invalid: "Invalid system proxy address or port. Existing settings kept.",
6
+ proxy_address_invalid: "Invalid proxy address. Existing settings kept.",
7
+ proxy_address_unsupported: "Unsupported proxy address format. Existing settings kept.",
8
+ proxy_dynamic_unsupported: "System PAC or WPAD is not supported. Existing settings kept.",
9
+ proxy_settings_unsupported: "Could not interpret proxy settings. Existing settings kept.",
10
+ });
11
+
12
+ export function m365NetworkDiagnostic(value) {
13
+ if (!value || !["system", "environment"].includes(value.source) || !Object.hasOwn(messages, value.cause_code)) return null;
14
+ return { source: value.source, stage: value.cause_code === "proxy_discovery_failed" ? "proxy_discovery" : "proxy_config", cause_code: value.cause_code };
15
+ }
16
+
17
+ export function m365NetworkMessage(value) {
18
+ const diagnostic = m365NetworkDiagnostic(value);
19
+ return diagnostic ? messages[diagnostic.cause_code] : null;
20
+ }
21
+
22
+ export function m365ProxyFailure(error, source, category = "proxy_settings_unsupported") {
23
+ const cause_code = Object.hasOwn(messages, error?.code) ? error.code : "proxy_settings_unsupported";
24
+ const network_diagnostic = m365NetworkDiagnostic({ source, cause_code });
25
+ return Object.assign(new Error(`Microsoft 365 network is unavailable (m365_${category})`, {
26
+ cause: new Error(messages[cause_code]),
27
+ }), { code: `m365_${category}`, statusCode: 503, network_diagnostic });
28
+ }
@@ -6,6 +6,7 @@ import { resolveNetworkRoute, networkProxyFor, bypassNetworkProxy, networkRouteS
6
6
  import { createProxyAgent } from "../proxy-tunnel.mjs";
7
7
  import { loadRuntimeConfig } from "../runtime-config.mjs";
8
8
  import { m365HelperEnvironment } from "./m365-auth.mjs";
9
+ import { m365ProxyFailure } from "./m365-network-diagnostic.mjs";
9
10
 
10
11
  const HOST = "df.loki.delve.office.com";
11
12
  const targetUrl = new URL(`https://${HOST}/api/v1/llmapi/models`);
@@ -47,7 +48,9 @@ export function requestFetch(requestImpl, agent) {
47
48
 
48
49
  export async function createM365Network({ env = process.env, platform = process.platform, signal,
49
50
  execFileImpl = promisify(execFile), startWindowsNetwork, requestImpl = https.request } = {}) {
50
- const explicit = resolveNetworkRoute({ env, checkApi: false });
51
+ let explicit;
52
+ try { explicit = resolveNetworkRoute({ env, checkApi: false }); }
53
+ catch (error) { throw m365ProxyFailure(error, "environment", "network_error"); }
51
54
  const environmentRoute = networkProxyFor(targetUrl, explicit), bypass = bypassNetworkProxy(HOST, 443, explicit);
52
55
  const runtime = loadRuntimeConfig(env);
53
56
  if (platform === "win32" && !environmentRoute && !bypass) {
@@ -61,9 +64,9 @@ export async function createM365Network({ env = process.env, platform = process.
61
64
  if (platform === "darwin" && !environmentRoute && !bypass) {
62
65
  let systemProxy;
63
66
  try { ({ stdout: systemProxy } = await execFileImpl("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2500, maxBuffer: 65536, signal })); }
64
- catch { throw fail("proxy_discovery_failed"); }
67
+ catch { throw m365ProxyFailure({ code: "proxy_discovery_failed" }, "system", "proxy_discovery_failed"); }
65
68
  try { plan = resolveNetworkRoute({ env, systemProxy, checkApi: false }); }
66
- catch { throw fail("proxy_settings_unsupported"); }
69
+ catch (error) { throw m365ProxyFailure(error, "system"); }
67
70
  }
68
71
  const agent = createProxyAgent(plan, { timeoutMs: 30000 });
69
72
  agent.maxSockets = 8;agent.maxFreeSockets = 2;