codex-copilot-dx 1.2.5 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,11 +14,11 @@ npm install -g codex-copilot-dx@latest
14
14
  ccdx
15
15
  ```
16
16
 
17
- No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.5/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.5/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
17
+ No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.6/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.6/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
18
18
 
19
19
  CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
20
20
 
21
- The [local control console](http://127.0.0.1:2026/) keeps indented Codex/Claude pages, Model sources, Usage, Requests and Settings. Codex owns source/model, Auto Review, images, input suggestions and conversation buffering; Model sources owns accounts, catalogs and Microsoft 365 access. Browsing a catalog never changes routing. Usage offers animated bars (default) or curves without extra requests; reduced motion keeps them static. Overview shows an approximate token cache hit rate, retaining partial/unknown states. The existing visual style and logo remain.
21
+ The [local control console](http://127.0.0.1:2026/) keeps indented Codex/Claude pages, Model sources, Usage, Requests and Settings. Codex owns source/model, Auto Review, images, input suggestions and conversation buffering; Model sources owns accounts, catalogs and Microsoft 365 access. Browsing a catalog never changes routing. Usage offers animated bars (default) or curves without extra requests; reduced motion keeps them static. Overview shows an approximate token cache hit rate, retaining partial/unknown states. The existing visual style and logo remain. System proxy exceptions accept shortened IPv4 networks; M365 network failures retain specific, redacted reasons.
22
22
 
23
23
  Startup shows bounded checks, sources with discovered model lists and Claude Code/App configuration. Prediction normally uses one summary line; `ccdx prediction status` retains recovery and environment details. After Ready, an interactive terminal shows current source/Claude state and a line-framed table of this process's returned usage and inference counters. Notices and activity each have their own line; individual requests do not scroll. Input includes reused input tokens. `ccdx --verbose` (also `--show-request-id`, or debug logging) retains detail output; optional file logging remains independently controlled. Source and Claude summaries wrap on narrow terminals. Failed reads show previous-data status and the last successful update time. Non-TTY, CI, dumb, or terminals too small for the full region use plain output (at least 40 columns / 16 rows are required). `Ready` only means the core service is available; discovered catalogs and configured clients do not prove inference access.
24
24
 
@@ -48,6 +48,11 @@ to M365. No GitHub token, image credential or browser Cookie is reused. Windows
48
48
  use a separate OS WinHTTP worker for M365 company routing; macOS preserves static
49
49
  system/environment routing and reports unsupported dynamic PAC. Native runtime
50
50
  absence and policy refusal do not disable GitHub.
51
+
52
+ `network-route.mjs` canonicalizes abbreviated IPv4 CIDRs only while adapting system `ExceptionsList` input, before merging it with the unchanged strict `NO_PROXY` input. `network-bypass.mjs` remains the shared strict Node/PAC matcher; it performs no DNS lookup. This fixes no-proxy and static-proxy macOS configurations without dropping exception rules or weakening unsupported dynamic-PAC protection.
53
+
54
+ `providers/m365-network-diagnostic.mjs` is a small pure projection of fixed proxy failure codes, source and stage, shared by transport, provider state, protected dashboard routes and CLI. Raw error chains/settings never cross that boundary. M365 retains existing outer error categories; the source runtime forwards the bounded diagnostic, and existing bilingual renderers expose a readable explanation with technical details. Startup uses the same fixed English explanation. Refresh failures retain last-good catalogs and never change the selected provider; successful transport creation clears the setup diagnostic. No new service, storage, dependency, route fallback or provider retry is introduced.
55
+
51
56
  `claude-client-lifecycle.mjs` owns configuration reconciliation and restore state, independently from source auth/catalog code. It checks lifecycle/profile validity after asynchronous policy inspection and preserves the existing field-ownership writer.
52
57
  Claude handler/configuration readiness is also separate from M365 provider
53
58
  readiness. A Claude setup failure or a GPT-only catalog cannot block the explicitly
package/docs/REFERENCE.md CHANGED
@@ -66,6 +66,10 @@ origin. Explicit proxy/trust settings are preserved. Windows delegates system
66
66
  PAC/WPAD and integrated authentication to its own isolated WinHTTP worker;
67
67
  unsupported macOS dynamic PAC is reported rather than bypassed.
68
68
 
69
+ System `ExceptionsList` entries such as `169.254/16`, `10/8`, `172.16/12` and `192.168.1/24` are normalized to full four-octet IPv4 CIDRs before the existing shared Node/PAC matcher. Missing octets become zero only when the supplied octets cover the prefix; invalid octets, ambiguous leading zeros, out-of-range or underspecified prefixes remain errors. User-supplied `NO_PROXY` retains its existing strict syntax. No system setting, proxy bypass policy, DNS lookup or network probe is added. The shared system-input correction also applies to prediction environment parsing.
70
+
71
+ M365 proxy-setup failures retain their existing outer category (`m365_proxy_settings_unsupported`, `m365_proxy_discovery_failed`, or the existing environment-failure category `m365_network_error`) and add an optional `network_diagnostic`: fixed `source` (`system`/`environment`), `stage` (`proxy_discovery`/`proxy_config`) and `cause_code`. Causes distinguish discovery, dynamic PAC/WPAD, invalid bypass rules, invalid static settings and invalid/unsupported proxy addresses; unknown causes stay generic. CLI/startup explain the specific cause without suggesting a new sign-in for a known network setup failure. WebUI shows the bilingual reason in source status (codes in its tooltip) and the existing model-check details, with source/stage/cause fields. Proxy URLs, credentials, raw settings and raw nested errors are never projected. These local setup failures happen before the model HTTP request; a local 502/503 does not establish a model-service denial. Successful transport setup or a later unrelated refresh failure clears the previous setup diagnostic. Failed catalog reads still remain failures and preserve last-good data; they are not successful empty catalogs. No automatic route substitution or extra polling is added.
72
+
69
73
  The M365 profile under `~/.local/share/codex-copilot-dx/profiles/m365/` contains
70
74
  `settings.json`, nonsecret `account.json`, account-bound `models.json`, a private
71
75
  local `gateway.json` key, and `client-config.json` field ownership. JSON reads are
@@ -1004,7 +1008,7 @@ Unknown support prevents an explicitly requested exception from starting.
1004
1008
  For an older updater that still requires Git, install the Release tarball directly:
1005
1009
 
1006
1010
  ```sh
1007
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.5/codex-copilot-dx-1.2.5.tgz
1011
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.6/codex-copilot-dx-1.2.6.tgz
1008
1012
  # Windows PowerShell: use npm.cmd instead of npm.
1009
1013
  ```
1010
1014
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.5",
3
+ "version": "1.2.6",
4
4
  "description": "Local Codex adapter and optional Microsoft 365 Claude gateway",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/cli-m365.mjs CHANGED
@@ -10,6 +10,7 @@ import { readBoundedResponseText } from "./upstream-body.mjs";
10
10
  import { parseAdapterAddressOptions } from "./cli-options.mjs";
11
11
  import { autoReviewReasoningEfforts } from "./models.mjs";
12
12
  import { m365AccountMessage } from "./providers/m365-accounts.mjs";
13
+ import { m365NetworkDiagnostic, m365NetworkMessage } from "./providers/m365-network-diagnostic.mjs";
13
14
 
14
15
  export async function fetchActiveProviderModels({ control = providerControl, ...options } = {}) {
15
16
  if (readProviderSettings(options).codex !== "m365") {
@@ -33,11 +34,12 @@ export async function providerControl({ host = "127.0.0.1", port = 2026, action,
33
34
 
34
35
  export function formatM365Status(state) {
35
36
  const m = state.m365 || {}, claude = m.claude || {}, models = m.models || {};
37
+ const network = m365NetworkDiagnostic(m.network_diagnostic);
36
38
  return [
37
39
  `Microsoft 365: ${terminalCell(m.state || "not running")}${m.reason ? ` (${terminalCell(m.reason)})` : ""}`,
38
40
  ...(m.account?.login ? [`Account: ${terminalCell(m.account.login)}`] : []),
39
41
  ...(m.account?.tenant ? [`Tenant: ${terminalCell(m.account.tenant)} / ${terminalCell(m.account.selection_source || "legacy")}`] : []),
40
- ...(m.reason ? [m365AccountMessage(m.reason)] : []),
42
+ ...(network ? [`Network: ${network.source} / ${network.stage} / ${network.cause_code}`, m365NetworkMessage(network)] : m.reason ? [m365AccountMessage(m.reason)] : []),
41
43
  `Models: ${models.claude || 0} Claude / ${models.gpt || 0} GPT (${models.source || "unavailable"})`,
42
44
  `Claude gateway: ${claude.gateway || "not running"}${claude.base_url ? ` / ${claude.base_url}` : ""}`,
43
45
  ...(claude.reason ? [`Claude detail: ${terminalCell(claude.reason)}`] : []),
@@ -73,6 +73,21 @@
73
73
  "source_check_none": ["No previous model list is available.", "暂无可用的旧模型列表。"],
74
74
  "source_check_time": ["Last check", "本次检查"],
75
75
  "source_check_reason": ["Reason", "失败原因"],
76
+ "network_route_source": ["Network settings", "网络设置来源"],
77
+ "network_failure_stage": ["Failed at", "失败阶段"],
78
+ "network_cause_code": ["Cause code", "原因代码"],
79
+ "network_source_system": ["System settings", "系统设置"],
80
+ "network_source_environment": ["Environment variables", "环境变量"],
81
+ "network_stage_proxy_discovery": ["Read system proxy settings", "读取系统代理"],
82
+ "network_stage_proxy_config": ["Interpret proxy rules", "解析代理规则"],
83
+ "network_detail": ["{source} / {stage} / {code} / {category}", "{source} / {stage} / {code} / {category}"],
84
+ "network_cause_proxy_discovery_failed": ["Could not read system proxy settings. Existing settings kept.", "无法读取系统代理。原设置已保留。"],
85
+ "network_cause_proxy_bypass_invalid": ["Invalid proxy exception rule. Existing settings kept.", "代理例外规则无效。原设置已保留。"],
86
+ "network_cause_proxy_system_invalid": ["Invalid system proxy address or port. Existing settings kept.", "系统代理地址或端口无效。原设置已保留。"],
87
+ "network_cause_proxy_address_invalid": ["Invalid proxy address. Existing settings kept.", "代理地址无效。原设置已保留。"],
88
+ "network_cause_proxy_address_unsupported": ["Unsupported proxy address format. Existing settings kept.", "代理地址格式不支持。原设置已保留。"],
89
+ "network_cause_proxy_dynamic_unsupported": ["System PAC or WPAD is not supported. Existing settings kept.", "暂不支持系统自动代理。原设置已保留。"],
90
+ "network_cause_proxy_settings_unsupported": ["Could not interpret proxy settings. Existing settings kept.", "无法解析代理设置。原设置已保留。"],
76
91
  "source_check_action": ["Use Refresh to check this source again.", "点击刷新,重新检查此来源。"],
77
92
  "source_failure_summary": ["{source} / {detail}", "{source} / {detail}"],
78
93
  "codex_body_admission_active_active_queued_queued_queue_limit_lim": ["Codex body admission: active {active} / queued {queued} / queue limit {limit}", "Codex请求体:进行中{active}\n排队{queued} / 队列上限{limit}"],
@@ -19,7 +19,13 @@
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
+ }
23
29
  auth.append(authRow);
24
30
  for (const client of provider.clients || []) {
25
31
  const row = tableRow([provider.name, client.name, states[client.state] || client.state,
@@ -427,21 +427,23 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
427
427
  if (state.error) {
428
428
  const message = String(state.error.message || state.error).slice(0, 240);
429
429
  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
430
  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] })
431
+ const diagnostic = state.error.diagnostic || {}, network = diagnostic.network;
432
+ 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
433
  : sourceReason ? phrase("source_catalog_unavailable", { code: sourceReason[1] }) : phrase(message);
435
434
  const source = providerEntries.find(entry => entry.id === selectedProvider)?.name || selectedProvider;
436
435
  const previous = modelSnapshots.get(selectedProvider);
436
+ element("models-note").removeAttribute("data-i18n");
437
437
  element("models-note").replaceChildren();
438
438
  const summary = document.createElement("span"), kept = document.createElement("span");
439
439
  localize(summary, "source_check_failed", { source });
440
440
  localize(kept, previous?.checked_at ? "source_check_previous" : "source_check_none", { time: previous?.checked_at ? new Date(previous.checked_at).toLocaleTimeString() : "" });
441
441
  element("models-note").append(summary, document.createElement("br"), kept);
442
442
  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]]) {
443
+ for (const [key, value] of [["source", source], ["source_check_time", diagnostic.checked_at], ["source_check_reason", reason],
444
+ ["network_route_source", network ? phrase(`network_source_${network.source}`) : null],
445
+ ["network_failure_stage", network ? phrase(`network_stage_${network.stage}`) : null],
446
+ ["network_cause_code", network?.cause_code], ["http_status", diagnostic.http_status]]) {
445
447
  if (value === null || value === undefined || value === "") continue;
446
448
  const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
447
449
  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 },
@@ -303,6 +305,7 @@ export async function handleDashboardApi(req, res, pathname, {
303
305
  const message = /^m365_[a-z0-9_]+$/.test(error.code || "") ? `Model catalog unavailable / ${error.code}` : liveModelError(error);
304
306
  if (!res.destroyed && !res.writableEnded) sendJson(res, error.statusCode || 502, { error: message,
305
307
  diagnostic: { provider: provider || null, checked_at: new Date().toISOString(), message,
308
+ network: m365NetworkDiagnostic(error.network_diagnostic),
306
309
  http_status: Number(/\bHTTP (\d{3})\b/.exec(message)?.[1]) || finite(error.statusCode),
307
310
  retry_after_ms: finite(error.retryAfterMs) } });
308
311
  } finally { abort.cleanup(); }
@@ -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
  }
@@ -9,6 +9,7 @@ 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 });
@@ -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
  }
@@ -206,7 +207,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
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
209
  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,
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;
@@ -16,6 +16,7 @@ import { resolveClaudeModel } from "../claude-models.mjs";
16
16
  import { modelReasoningEfforts } from "../provider-metadata.mjs";
17
17
  import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
18
18
  import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
19
+ import { m365NetworkDiagnostic } from "./m365-network-diagnostic.mjs";
19
20
 
20
21
  export const M365_API_BASE = "https://df.loki.delve.office.com/api/v1/llmapi";
21
22
  const SOFT_TTL_MS = 2 * 60 * 60 * 1000;
@@ -74,6 +75,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
74
75
  const guardConversation = createM365ConversationGuard({ home });
75
76
  let catalog = null, account = null, catalogAt = 0, state = "idle", reason = null, flight = null, controller = null, generation = 0;
76
77
  let network = null, networkFlight = null, cacheTtlAdjustments = 0;
78
+ let networkDiagnostic = null;
77
79
  const registry = { models: null, source: "unavailable", cacheState: "none", cacheSavedAtMs: null,
78
80
  refreshInFlight: false, generation: 0, lastError: null, lastErrorAtMs: null };
79
81
  const profile = () => account ? `m365:${m365AccountKey(account)}` : "m365:unavailable";
@@ -85,7 +87,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
85
87
  const start = createNetwork || (await import("./m365-network.mjs")).createM365Network;
86
88
  const opened = await start({ env, signal });
87
89
  if (state === "disabled") { opened.close();throw m365Error("m365_disabled"); }
88
- network = opened;return opened.fetch;
90
+ network = opened;networkDiagnostic = null;return opened.fetch;
89
91
  })().finally(() => { if (networkFlight === pending) networkFlight = null; });
90
92
  networkFlight = pending;
91
93
  }
@@ -128,7 +130,8 @@ export function createM365Provider({ home, env = process.env, account: accountOv
128
130
  } catch (error) {
129
131
  if (options.signal?.aborted) throw options.signal.reason || error;
130
132
  throw Object.assign(new Error(redactDiagnosticText(String(error.message).split(credential.token).join("[redacted]"))), {
131
- code: /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : "m365_network_error", statusCode: 502 });
133
+ code: /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : "m365_network_error", statusCode: 502,
134
+ network_diagnostic: m365NetworkDiagnostic(error.network_diagnostic) });
132
135
  }
133
136
  }
134
137
 
@@ -156,6 +159,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
156
159
  })().catch(error => {
157
160
  if (current === generation) {
158
161
  state = "unavailable";reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : "m365_unavailable";
162
+ networkDiagnostic = m365NetworkDiagnostic(error.network_diagnostic);
159
163
  registry.lastError = reason;registry.lastErrorAtMs = now();
160
164
  }
161
165
  throw error;
@@ -249,6 +253,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
249
253
  },
250
254
  snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login, tenant: account.tenant, selection_source: account.selection_source || "legacy" } : null,
251
255
  network: network?.snapshot() || null,
256
+ network_diagnostic: networkDiagnostic ? { ...networkDiagnostic } : null,
252
257
  cache_ttl_adjustments: cacheTtlAdjustments,
253
258
  models: { total: catalog?.data.length || 0, claude: m365Models(catalog, "claude").length, gpt: m365Models(catalog, "gpt").length,
254
259
  source: registry.source, refreshed_at: catalogAt ? new Date(catalogAt).toISOString() : null }, refresh_in_flight: Boolean(flight) }),