codex-copilot-dx 1.2.4 → 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 +2 -2
- package/docs/ARCHITECTURE.md +7 -0
- package/docs/REFERENCE.md +10 -2
- package/package.json +1 -1
- package/src/cli-m365.mjs +3 -1
- package/src/dashboard/console.js +1 -1
- package/src/dashboard/index.html +2 -1
- package/src/dashboard/language.js +20 -0
- package/src/dashboard/status.js +9 -1
- package/src/dashboard/ui.css +9 -0
- package/src/dashboard/ui.js +15 -8
- package/src/dashboard/usage.js +101 -19
- package/src/dashboard-api.mjs +3 -0
- package/src/network-route.mjs +12 -1
- package/src/provider-runtime.mjs +3 -2
- package/src/providers/m365-network-diagnostic.mjs +28 -0
- package/src/providers/m365-network.mjs +6 -3
- package/src/providers/m365.mjs +7 -2
- package/src/usage-store.mjs +21 -10
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.
|
|
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. The existing visual style
|
|
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
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -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
|
|
@@ -277,6 +282,8 @@ while visible/automatic, and source/settings evidence every eight status ticks.
|
|
|
277
282
|
Catalog and retained-log reads retain their slower, view-scoped policy. Animation
|
|
278
283
|
frames still load once per page when opened.
|
|
279
284
|
|
|
285
|
+
`dashboard/usage.js` owns bar/curve geometry and viewport-gated, one-shot Web Animations. The two views share retained analytics and accessible day buttons; their paths never connect unavailable history or overshoot adjacent values. View-only changes leave the calendar nodes intact. The UI lifecycle cancels motion on hidden/suspended views and reduced-motion changes; no animation timer or chart dependency is added. `usage-store.mjs` shares cache-evidence validation between retained summaries and process-local totals; runtime snapshots expose the weighted cache ratio plus a partial-evidence flag, without new persistence or log scans. The Overview renderer formats that snapshot and preserves unknown/invalid values.
|
|
286
|
+
|
|
280
287
|
`dashboard-updates.mjs` is loaded only by the protected update-information route. It projects bounded public stable-release metadata and publication dates, with process-local single-flight, five-minute success and one-minute failure caches. Its asynchronous npm network-configuration read reuses the installer's existing policy-preserving downloader; it adds no runtime dependency, credentials or synchronous child process on the service event loop. Metadata has a four-second per-request deadline and 128 KiB decoded-body bound. It never installs or restarts anything and does not alter startup's independent web-redirect lookup. `dashboard/updates.js` renders current/available/unknown states and validated, pinned installation command text; `refresh.js` owns its visible Settings refresh cadence. Failed checks preserve explicitly labeled prior metadata. No provider authentication or inference is involved.
|
|
281
288
|
|
|
282
289
|
`claude-models.mjs` owns exact ID spelling and capability-cap projection shared by
|
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.
|
|
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
|
|
|
@@ -1200,14 +1204,18 @@ are not guessed into one. Legacy untagged Provider records retain their historic
|
|
|
1200
1204
|
GitHub attribution. Cache-read tokens are included in input, not added twice.
|
|
1201
1205
|
The separate current-run summary updates from returned usage in memory, without
|
|
1202
1206
|
rescanning retained logs at the status cadence.
|
|
1207
|
+
Overview adds an approximate token cache hit rate: returned reused input tokens divided by returned input tokens, weighted by tokens rather than request percentages. Missing evidence is distinct from an explicit zero; all-unknown cache evidence, zero input and invalid counts display `—`. Mixed complete/incomplete cache evidence displays `~` before the recorded aggregate ratio. This describes recorded input reuse, not a request success ratio, invoice or whole-account cache statistic. Missing output alone does not invalidate usable input/cache evidence.
|
|
1203
1208
|
|
|
1204
|
-
Usage analytics remains collapsed until opened: 7/30/90-day
|
|
1209
|
+
Usage analytics remains collapsed until opened: 7/30/90-day charts and a bounded
|
|
1205
1210
|
365-day calendar in the browser time zone. Model/range/day selection reuses its
|
|
1206
1211
|
snapshot. Days outside retained history are distinct from zero recorded activity.
|
|
1207
1212
|
Filters, chart nodes and unsaved animation selection survive unrelated refreshes.
|
|
1208
1213
|
Dark/light, English/Chinese and reduced motion remain supported. Language changes
|
|
1209
1214
|
translate page labels in place without fetching models or rebuilding charts;
|
|
1210
1215
|
commands, identifiers and upstream error text retain their original values.
|
|
1216
|
+
Chart view defaults to Bar chart on each page load; its dropdown switches to Line chart without another request or log scan. Both views retain the same input/output values, scale, model/source/range filters and date selection. Lines show separate input/output series, pass through each known day's value, stay between neighboring values and break across unavailable history; a lone known day is a point. The calendar is unchanged by view switching.
|
|
1217
|
+
|
|
1218
|
+
Visible bar stacks rise from the baseline once over 450 ms; curves draw left to right over 600 ms (a lone point fades in over 200 ms). Opening/revealing a chart and changing its data, filters or view can replay the entrance. Selecting a day, changing calendar measure and unchanged background refreshes do not replay it. Hidden/collapsed views, page suspension and reduced-motion preferences cancel active chart motion; reduced-motion or unsupported animation APIs retain the complete static chart. Chart motion adds no polling loop, chart library or runtime dependency.
|
|
1211
1219
|
|
|
1212
1220
|
The atom logo stays in the sidebar brand (compact top navigation on narrow screens).
|
|
1213
1221
|
It rotates once on load and manual Refresh, never on scheduled reads, and respects
|
package/package.json
CHANGED
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)}`] : []),
|
package/src/dashboard/console.js
CHANGED
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
label(el("page-title"), titles[next]);
|
|
48
48
|
if (["codex", "models", "system"].includes(next)) void loadSettings();
|
|
49
49
|
if (next === "models") { void dashboardRefresh.refresh("models");void dashboardRefresh.refresh("auth"); }
|
|
50
|
-
if (next === "usage") void dashboardRefresh.refresh("usage");
|
|
50
|
+
if (next === "usage") { void dashboardRefresh.refresh("usage");usageView.revealChart(); } else usageView.stopMotion();
|
|
51
51
|
if (next === "system") { void dashboardRefresh.refresh("animation");void dashboardRefresh.refresh("updates"); }
|
|
52
52
|
syncAnimationPreview();
|
|
53
53
|
}
|
package/src/dashboard/index.html
CHANGED
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
<div class="table-wrap"><table><thead><tr><th data-i18n="source">Source</th><th data-i18n="client">APP</th><th data-i18n="state">STATE</th><th data-i18n="gateway">LOCAL ACCESS</th><th data-i18n="last_request">LAST REQUEST</th></tr></thead><tbody id="provider-clients"></tbody></table></div>
|
|
53
53
|
<div id="provider-requests" class="hint"></div>
|
|
54
54
|
</details>
|
|
55
|
-
<section class="panel dashboard-section"><h2 data-i18n="this_run_usage">THIS RUN</h2><p id="runtime-usage" class="table-note"></p><p class="hint" data-i18n="updated_from_returned_usage_not_a_live_bill_pending_usage_is_not">Counts returned usage only. Pending usage is not included. This is not a live bill.</p></section>
|
|
55
|
+
<section class="panel dashboard-section"><h2 data-i18n="this_run_usage">THIS RUN</h2><p id="runtime-usage" class="table-note"></p><p class="table-note"><span data-i18n="approx_cache_hit_rate">Approx. cache hit rate</span>: <strong id="runtime-cache-hit" data-i18n-title="runtime_cache_hit_basis" title="Reused input / input tokens. ~ Partial counts. — Unknown or invalid.">—</strong></p><p class="hint" data-i18n="updated_from_returned_usage_not_a_live_bill_pending_usage_is_not">Counts returned usage only. Pending usage is not included. This is not a live bill.</p></section>
|
|
56
56
|
</div>
|
|
57
57
|
<div data-view="codex" hidden>
|
|
58
58
|
<section class="panel dashboard-section" aria-labelledby="routing-heading">
|
|
@@ -166,6 +166,7 @@
|
|
|
166
166
|
<div class="analytics-controls">
|
|
167
167
|
<label><span data-i18n="model_5e2c6">Model</span> <select id="analytics-model"><option value="" data-i18n="all_models">All models</option></select></label>
|
|
168
168
|
<label><span data-i18n="daily_range">Date range</span> <select id="analytics-range"><option value="7" data-i18n="7_days">Last 7 days</option><option value="30" selected data-i18n="30_days">Last 30 days</option><option value="90" data-i18n="90_days">Last 90 days</option></select></label>
|
|
169
|
+
<label><span data-i18n="chart_view">Chart view</span> <select id="analytics-view"><option value="bars" selected data-i18n="bar_chart">Bar chart</option><option value="line" data-i18n="line_chart">Line chart</option></select></label>
|
|
169
170
|
<label><span data-i18n="activity">Measure</span> <select id="analytics-metric"><option value="requests" data-i18n="calls_b73a5">Requests</option><option value="tokens" data-i18n="tokens">Usage (Token)</option></select></label>
|
|
170
171
|
</div>
|
|
171
172
|
<p id="analytics-note" class="table-note" role="status" data-i18n="open_to_read_retained_usage_history">Open to view usage trends.</p>
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
"chart_view": ["Chart view", "图表视图"],
|
|
4
|
+
"bar_chart": ["Bar chart", "柱状图"],
|
|
5
|
+
"line_chart": ["Line chart", "曲线图"],
|
|
6
|
+
"approx_cache_hit_rate": ["Approx. cache hit rate", "粗略缓存命中率"],
|
|
7
|
+
"runtime_cache_hit_basis": ["Reused input / input tokens. ~ Partial counts. — Unknown or invalid.", "复用输入 ÷ 输入 Token。\n~:数据不完整。—:未知或无效。"],
|
|
3
8
|
"provider_status_scope": ["Source and application status", "模型来源与应用状态"],
|
|
4
9
|
"version_updates": ["VERSION & UPDATES", "版本与更新"],
|
|
5
10
|
"copy_command": ["Copy command", "复制指令"],
|
|
@@ -68,6 +73,21 @@
|
|
|
68
73
|
"source_check_none": ["No previous model list is available.", "暂无可用的旧模型列表。"],
|
|
69
74
|
"source_check_time": ["Last check", "本次检查"],
|
|
70
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.", "无法解析代理设置。原设置已保留。"],
|
|
71
91
|
"source_check_action": ["Use Refresh to check this source again.", "点击刷新,重新检查此来源。"],
|
|
72
92
|
"source_failure_summary": ["{source} / {detail}", "{source} / {detail}"],
|
|
73
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}"],
|
package/src/dashboard/status.js
CHANGED
|
@@ -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)
|
|
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,
|
|
@@ -214,6 +220,8 @@
|
|
|
214
220
|
const usage = data.runtime_usage;
|
|
215
221
|
text("runtime-usage", usage ? "records_usage_records_input_input_cache_read_cached_output_outpu" : "—",
|
|
216
222
|
usage ? { records: number(usage.records), input: number(usage.input_tokens), cached: number(usage.cached_input_tokens), output: number(usage.output_tokens), partial: usage.partial_records ? " ~" : "" } : {});
|
|
223
|
+
const rate = usage?.cache_hit_rate;
|
|
224
|
+
text("runtime-cache-hit", Number.isFinite(rate) && rate >= 0 && rate <= 1 ? `${usage.cache_hit_rate_partial ? "~" : ""}${(rate * 100).toFixed(1)}%` : "—");
|
|
217
225
|
element("process-state").textContent = `PID ${data.pid || "—"} / ${globalThis.location?.origin || ""}`;
|
|
218
226
|
text("process-memory", "rss_rss_heap_heap", { rss: mib(data.process?.rss_bytes), heap: mib(data.process?.heap_used_bytes) });
|
|
219
227
|
text("process-queues", "codex_body_admission_active_active_queued_queued_queue_limit_lim", {
|
package/src/dashboard/ui.css
CHANGED
|
@@ -110,6 +110,14 @@ select { max-width: 260px; padding: 5px; font: inherit; color: var(--text); back
|
|
|
110
110
|
.daily-bars { display: flex; align-items: end; gap: 3px; height: 130px; border-bottom: 1px solid var(--border); }
|
|
111
111
|
.daily-bar { height: 100%; flex: 1; min-width: 0; padding: 0; border: 0; display: flex; flex-direction: column; justify-content: end; background: transparent; border-radius: 0; }
|
|
112
112
|
.daily-bar span { display: block; flex-shrink: 0; width: 100%; }
|
|
113
|
+
.daily-bar .bar-stack { display:flex; flex-direction:column; justify-content:end; height:100%; transform-origin:center bottom; }
|
|
114
|
+
.daily-lines { position:relative; gap:0; }
|
|
115
|
+
.daily-line-plot { position:absolute; inset:0; width:100%; height:100%; pointer-events:none; overflow:visible; }
|
|
116
|
+
.daily-curve { fill:none; stroke-width:2; stroke-linecap:round; stroke-linejoin:round; stroke-dasharray:1; stroke-dashoffset:0; }
|
|
117
|
+
.curve-input { stroke:var(--accent-soft); }
|
|
118
|
+
.curve-output { stroke:var(--ansi-39); }
|
|
119
|
+
.daily-lines .daily-bar { z-index:1; }
|
|
120
|
+
.daily-lines .daily-bar:hover { background:color-mix(in srgb, var(--accent-soft) 10%, transparent); }
|
|
113
121
|
.bar-input { background: var(--accent-soft); }
|
|
114
122
|
.bar-output { background: var(--ansi-39); }
|
|
115
123
|
.daily-bar:hover { background: var(--option-hover); }
|
|
@@ -119,6 +127,7 @@ select { max-width: 260px; padding: 5px; font: inherit; color: var(--text); back
|
|
|
119
127
|
.chart-legend span::before { content: "■"; margin-right: 6px; }
|
|
120
128
|
.legend-input::before { color: var(--accent-soft); }
|
|
121
129
|
.legend-output::before { color: var(--ansi-39); }
|
|
130
|
+
.daily-lines ~ .chart-legend span::before { content:"━"; }
|
|
122
131
|
.calendar-scroll { overflow-x: auto; padding: 4px; }
|
|
123
132
|
.calendar-grid { width: max-content; }
|
|
124
133
|
.calendar-months { display: grid; grid-auto-columns: 12px; gap: 4px; margin-bottom: 7px; color: var(--muted); font-size: 9px; height: 14px; }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -15,7 +15,8 @@ const text = (id, key, values) => { localize(element(id), key, values); };
|
|
|
15
15
|
const finite = (value) => value !== null && value !== undefined && Number.isFinite(Number(value));
|
|
16
16
|
const number = (value) => finite(value) ? Math.max(0, Math.round(Number(value))).toLocaleString() : "—";
|
|
17
17
|
const mib = (value) => finite(value) ? `${(Number(value) / 1048576).toFixed(1)} MiB` : "—";
|
|
18
|
-
const viewHelpers = { element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator: globalThis.navigator
|
|
18
|
+
const viewHelpers = { element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator: globalThis.navigator,
|
|
19
|
+
motionAllowed: () => !reducedMotion.matches && document.visibilityState === "visible" && element("usage-analytics").open && element("model-usage").open && !element("model-usage").closest("[hidden]") };
|
|
19
20
|
const { render, renderProviders, renderFailures, renderContext } = globalThis.ccdxDashboardStatus.create(viewHelpers);
|
|
20
21
|
const usageView = globalThis.ccdxDashboardUsage.create(viewHelpers);
|
|
21
22
|
const { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay } = usageView;
|
|
@@ -104,6 +105,9 @@ new IntersectionObserver(([entry]) => {
|
|
|
104
105
|
}).observe(element("animation-options"));
|
|
105
106
|
document.addEventListener("visibilitychange", syncAnimationPreview);
|
|
106
107
|
reducedMotion.addEventListener("change", syncAnimationPreview);
|
|
108
|
+
reducedMotion.addEventListener("change", () => { if (reducedMotion.matches) usageView.stopMotion(); });
|
|
109
|
+
document.addEventListener("visibilitychange", () => { if (document.visibilityState !== "visible") usageView.stopMotion(); });
|
|
110
|
+
new IntersectionObserver(([entry]) => usageView.setChartVisible(entry.isIntersecting)).observe(element("daily-bars"));
|
|
107
111
|
|
|
108
112
|
function buildAnimationOptions(data) {
|
|
109
113
|
const container = element("animation-options");
|
|
@@ -423,21 +427,23 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
|
423
427
|
if (state.error) {
|
|
424
428
|
const message = String(state.error.message || state.error).slice(0, 240);
|
|
425
429
|
const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
|
|
426
|
-
if (httpError) text("models-note", "live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] });
|
|
427
|
-
else text("models-note", message);
|
|
428
430
|
const sourceReason = /^Model catalog unavailable \/ (m365_[a-z0-9_]+)$/.exec(message);
|
|
429
|
-
const
|
|
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] })
|
|
430
433
|
: sourceReason ? phrase("source_catalog_unavailable", { code: sourceReason[1] }) : phrase(message);
|
|
431
434
|
const source = providerEntries.find(entry => entry.id === selectedProvider)?.name || selectedProvider;
|
|
432
435
|
const previous = modelSnapshots.get(selectedProvider);
|
|
436
|
+
element("models-note").removeAttribute("data-i18n");
|
|
433
437
|
element("models-note").replaceChildren();
|
|
434
438
|
const summary = document.createElement("span"), kept = document.createElement("span");
|
|
435
439
|
localize(summary, "source_check_failed", { source });
|
|
436
440
|
localize(kept, previous?.checked_at ? "source_check_previous" : "source_check_none", { time: previous?.checked_at ? new Date(previous.checked_at).toLocaleTimeString() : "" });
|
|
437
441
|
element("models-note").append(summary, document.createElement("br"), kept);
|
|
438
442
|
const fields = element("model-check-fields");fields.replaceChildren();
|
|
439
|
-
const
|
|
440
|
-
|
|
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]]) {
|
|
441
447
|
if (value === null || value === undefined || value === "") continue;
|
|
442
448
|
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
|
|
443
449
|
if (value?.key) localize(detail, value.key, value.values);else detail.textContent = String(value).slice(0, 300);
|
|
@@ -516,7 +522,7 @@ element("auto-refresh").addEventListener("click", () => {
|
|
|
516
522
|
try { localStorage.setItem(autoRefreshKey, dashboardRefresh.automatic ? "on" : "off"); } catch { /* Keep the current choice. */ }
|
|
517
523
|
});
|
|
518
524
|
document.addEventListener("visibilitychange", () => dashboardRefresh.visibilityChanged());
|
|
519
|
-
window.addEventListener("pagehide", () => { dashboardRefresh.suspend(); stopAnimationPreview(); });
|
|
525
|
+
window.addEventListener("pagehide", () => { dashboardRefresh.suspend(); stopAnimationPreview();usageView.stopMotion(); });
|
|
520
526
|
window.addEventListener("pageshow", () => { dashboardRefresh.resume(); syncAnimationPreview(); });
|
|
521
527
|
|
|
522
528
|
for (const [id, key] of [["account-authorization", "auth"], ["client-features", "status"], ["request-context", "status"], ["recent-failures", "status"], ["upstream-models", "models"], ["model-usage", "usage"]]) {
|
|
@@ -535,9 +541,10 @@ element("animation-settings").addEventListener("toggle", () => {
|
|
|
535
541
|
syncAnimationPreview();
|
|
536
542
|
});
|
|
537
543
|
element("usage-analytics").addEventListener("toggle", () => {
|
|
544
|
+
if (element("usage-analytics").open) usageView.revealChart();else usageView.stopMotion();
|
|
538
545
|
if (element("usage-analytics").open && element("model-usage").open) dashboardRefresh.refresh("usage");
|
|
539
546
|
});
|
|
540
|
-
for (const id of ["analytics-model", "analytics-range", "analytics-metric"]) element(id).addEventListener("change", () => {
|
|
547
|
+
for (const id of ["analytics-model", "analytics-range", "analytics-metric", "analytics-view"]) element(id).addEventListener("change", () => {
|
|
541
548
|
renderAnalytics();
|
|
542
549
|
if (usageView.data && usageView.selectedDate) renderUsageTable();
|
|
543
550
|
});
|
package/src/dashboard/usage.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
(() => {
|
|
2
|
-
function
|
|
2
|
+
function curvePath(points) {
|
|
3
|
+
return points.map(([x, y], index) => {
|
|
4
|
+
if (!index) return `M${x},${y}`;
|
|
5
|
+
const [previousX, previousY] = points[index - 1], middle = (previousX + x) / 2;
|
|
6
|
+
return `C${middle},${previousY} ${middle},${y} ${x},${y}`;
|
|
7
|
+
}).join(" ");
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function create({ element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator, motionAllowed = () => false }) {
|
|
3
11
|
function usageValues(row) {
|
|
4
12
|
const rate = Number.isFinite(row.cache_hit_rate) && row.cache_hit_rate >= 0 && row.cache_hit_rate <= 1
|
|
5
13
|
? `${row.cache_hit_rate_partial ? "~" : ""}${(row.cache_hit_rate * 100).toFixed(1)}%` : "—";
|
|
@@ -7,8 +15,92 @@
|
|
|
7
15
|
}
|
|
8
16
|
|
|
9
17
|
let usageData = null;
|
|
10
|
-
let analyticsSignature;
|
|
18
|
+
let analyticsSignature, calendarSignature;
|
|
11
19
|
let selectedUsageDate = "";
|
|
20
|
+
let dailySignature, dailySelection, chartVisible = false, motionPending = false;
|
|
21
|
+
let motionTargets = [];
|
|
22
|
+
const animations = new Set();
|
|
23
|
+
|
|
24
|
+
function stopMotion() {
|
|
25
|
+
for (const animation of animations) animation.cancel();
|
|
26
|
+
animations.clear();motionPending = false;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function playMotion() {
|
|
30
|
+
if (!motionPending || !chartVisible || !motionAllowed()) return;
|
|
31
|
+
stopMotion();
|
|
32
|
+
for (const { node, line, point } of motionTargets) {
|
|
33
|
+
if (!node.animate) continue;
|
|
34
|
+
const animation = node.animate(point ? [{ opacity: 0 }, { opacity: 1 }] : line
|
|
35
|
+
? [{ strokeDashoffset: 1 }, { strokeDashoffset: 0 }]
|
|
36
|
+
: [{ transform: "scaleY(0)" }, { transform: "scaleY(1)" }],
|
|
37
|
+
{ duration: point ? 200 : line ? 600 : 450, easing: "cubic-bezier(0.25, 1, 0.5, 1)" });
|
|
38
|
+
animations.add(animation);
|
|
39
|
+
animation.finished?.then(() => animations.delete(animation), () => animations.delete(animation));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function revealChart() { motionPending = true;playMotion(); }
|
|
44
|
+
function setChartVisible(value) { chartVisible = value;if (value) playMotion();else if (animations.size) stopMotion(); }
|
|
45
|
+
|
|
46
|
+
function svgNode(tag, attributes) {
|
|
47
|
+
const node = document.createElementNS("http://www.w3.org/2000/svg", tag);
|
|
48
|
+
for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value));
|
|
49
|
+
return node;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function renderDaily(daily, model, maximum) {
|
|
53
|
+
const line = element("analytics-view").value === "line";
|
|
54
|
+
const signature = JSON.stringify([daily, model, line]);
|
|
55
|
+
if (signature === dailySignature && selectedUsageDate === dailySelection) return;
|
|
56
|
+
const changed = signature !== dailySignature;
|
|
57
|
+
dailySignature = signature;dailySelection = selectedUsageDate;
|
|
58
|
+
stopMotion();motionTargets = [];
|
|
59
|
+
const chart = element("daily-bars");
|
|
60
|
+
chart.className = line ? "daily-bars daily-lines" : "daily-bars";
|
|
61
|
+
chart.replaceChildren();
|
|
62
|
+
if (line) {
|
|
63
|
+
const plot = svgNode("svg", { class: "daily-line-plot", viewBox: "0 0 1000 130", preserveAspectRatio: "none", "aria-hidden": "true", focusable: "false" });
|
|
64
|
+
for (const key of ["input_tokens", "output_tokens"]) {
|
|
65
|
+
let segment = [];
|
|
66
|
+
const color = key === "input_tokens" ? "curve-input" : "curve-output";
|
|
67
|
+
const flush = () => {
|
|
68
|
+
if (segment.length > 1) {
|
|
69
|
+
const path = svgNode("path", { d: curvePath(segment), class: `daily-curve ${color}`, pathLength: 1, "vector-effect": "non-scaling-stroke" });
|
|
70
|
+
plot.append(path);motionTargets.push({ node: path, line: true });
|
|
71
|
+
} else if (segment.length === 1) {
|
|
72
|
+
const [x, y] = segment[0];
|
|
73
|
+
const circle = svgNode("circle", { cx: x, cy: y, r: 2, class: color, fill: "none", "stroke-width": 2, "vector-effect": "non-scaling-stroke" });
|
|
74
|
+
plot.append(circle);motionTargets.push({ node: circle, point: true });
|
|
75
|
+
}
|
|
76
|
+
segment = [];
|
|
77
|
+
};
|
|
78
|
+
daily.forEach((day, index) => {
|
|
79
|
+
if (!day.available) { flush();return; }
|
|
80
|
+
const point = analyticsPoint(day, model), x = (index + 0.5) / daily.length * 1000, y = 128 - point[key] / maximum * 124;
|
|
81
|
+
segment.push([x, y]);
|
|
82
|
+
});
|
|
83
|
+
flush();
|
|
84
|
+
}
|
|
85
|
+
chart.append(plot);
|
|
86
|
+
}
|
|
87
|
+
for (const day of daily) {
|
|
88
|
+
const point = analyticsPoint(day, model), button = dayButton(day, point);
|
|
89
|
+
button.className = "daily-bar";
|
|
90
|
+
if (!line) {
|
|
91
|
+
const stack = document.createElement("span");stack.className = "bar-stack";
|
|
92
|
+
for (const key of ["output_tokens", "input_tokens"]) {
|
|
93
|
+
const segment = document.createElement("span");
|
|
94
|
+
segment.className = key === "input_tokens" ? "bar-input" : "bar-output";
|
|
95
|
+
segment.style.height = `${point[key] / maximum * 100}%`;
|
|
96
|
+
stack.append(segment);
|
|
97
|
+
}
|
|
98
|
+
button.append(stack);motionTargets.push({ node: stack, line: false });
|
|
99
|
+
}
|
|
100
|
+
chart.append(button);
|
|
101
|
+
}
|
|
102
|
+
motionPending = changed;playMotion();
|
|
103
|
+
}
|
|
12
104
|
|
|
13
105
|
function renderUsageTable() {
|
|
14
106
|
const day = selectedUsageDate && usageData.analytics?.days.find((entry) => entry.date === selectedUsageDate);
|
|
@@ -61,7 +153,8 @@
|
|
|
61
153
|
const analytics = usageData?.analytics;
|
|
62
154
|
if (!analytics) return;
|
|
63
155
|
const model = element("analytics-model").value;
|
|
64
|
-
const
|
|
156
|
+
const commonSignature = JSON.stringify([analytics, model, element("analytics-range").value, element("analytics-metric").value, selectedUsageDate]);
|
|
157
|
+
const signature = `${commonSignature}:${element("analytics-view").value}`;
|
|
65
158
|
if (signature === analyticsSignature) return;
|
|
66
159
|
analyticsSignature = signature;
|
|
67
160
|
const days = analytics.days;
|
|
@@ -70,22 +163,11 @@
|
|
|
70
163
|
const point = analyticsPoint(day, model);
|
|
71
164
|
return point.input_tokens + point.output_tokens;
|
|
72
165
|
}));
|
|
73
|
-
|
|
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
|
-
}
|
|
166
|
+
renderDaily(daily, model, maximum);
|
|
87
167
|
text("daily-from", daily[0].date);
|
|
88
168
|
text("daily-to", analytics.to);
|
|
169
|
+
if (commonSignature === calendarSignature) return;
|
|
170
|
+
calendarSignature = commonSignature;
|
|
89
171
|
const metric = element("analytics-metric").value;
|
|
90
172
|
const value = (day) => {
|
|
91
173
|
const point = analyticsPoint(day, model);
|
|
@@ -157,7 +239,7 @@
|
|
|
157
239
|
text("analytics-updated", "updated_time", { time: new Date().toLocaleTimeString() });
|
|
158
240
|
}
|
|
159
241
|
}
|
|
160
|
-
return { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay, usageValues, get data() { return usageData; }, get selectedDate() { return selectedUsageDate; } };
|
|
242
|
+
return { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay, usageValues, setChartVisible, revealChart, stopMotion, get data() { return usageData; }, get selectedDate() { return selectedUsageDate; } };
|
|
161
243
|
}
|
|
162
|
-
globalThis.ccdxDashboardUsage = { create };
|
|
244
|
+
globalThis.ccdxDashboardUsage = { create, curvePath };
|
|
163
245
|
})();
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -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(); }
|
package/src/network-route.mjs
CHANGED
|
@@ -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
|
}
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
|
67
|
+
catch { throw m365ProxyFailure({ code: "proxy_discovery_failed" }, "system", "proxy_discovery_failed"); }
|
|
65
68
|
try { plan = resolveNetworkRoute({ env, systemProxy, checkApi: false }); }
|
|
66
|
-
catch { throw
|
|
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;
|
package/src/providers/m365.mjs
CHANGED
|
@@ -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) }),
|
package/src/usage-store.mjs
CHANGED
|
@@ -27,7 +27,12 @@ let writeFailures = 0;
|
|
|
27
27
|
const runtimeUsage = { since: new Date().toISOString(), records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 };
|
|
28
28
|
const runtimeUsageByProvider = new Map();
|
|
29
29
|
|
|
30
|
-
export function runtimeUsageSnapshot() {
|
|
30
|
+
export function runtimeUsageSnapshot() {
|
|
31
|
+
const snapshot = totals => ({ ...totals,
|
|
32
|
+
cache_hit_rate: totals.records > (totals.cache_hit_unknown_requests || 0) ? usageCacheHitRate(totals) : null,
|
|
33
|
+
cache_hit_rate_partial: (totals.cache_hit_unknown_requests || 0) > 0 });
|
|
34
|
+
return { ...snapshot(runtimeUsage), by_provider: Object.fromEntries([...runtimeUsageByProvider].map(([id, totals]) => [id, snapshot(totals)])) };
|
|
35
|
+
}
|
|
31
36
|
|
|
32
37
|
export function usageLoggingStats() {
|
|
33
38
|
return { pending_records: pendingRecords, pending_bytes: pendingBytes, dropped_records: droppedRecords,
|
|
@@ -186,14 +191,17 @@ function scheduleUsageWriteDrain() {
|
|
|
186
191
|
export function recordUsage(record) {
|
|
187
192
|
if (!record) return Promise.resolve();
|
|
188
193
|
const usage = record.usage || {};
|
|
194
|
+
const { cached, unknown, invalid } = usageCacheEvidence(usage);
|
|
189
195
|
const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 16 ? provider : "other";
|
|
190
196
|
if (!runtimeUsageByProvider.has(label)) runtimeUsageByProvider.set(label, { records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 });
|
|
191
197
|
for (const totals of [runtimeUsage, runtimeUsageByProvider.get(label)]) {
|
|
192
198
|
totals.records++;
|
|
193
|
-
for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens",
|
|
199
|
+
for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cached], ["output_tokens", usage.output_tokens]]) {
|
|
194
200
|
if (Number.isFinite(value) && value >= 0) totals[target] += value;
|
|
195
201
|
}
|
|
196
|
-
if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) ||
|
|
202
|
+
if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cached === undefined) totals.partial_records++;
|
|
203
|
+
if (unknown) totals.cache_hit_unknown_requests = (totals.cache_hit_unknown_requests || 0) + 1;
|
|
204
|
+
if (invalid) totals.cache_hit_invalid_requests = (totals.cache_hit_invalid_requests || 0) + 1;
|
|
197
205
|
}
|
|
198
206
|
if (process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
|
|
199
207
|
const filePath = usageLogPath();
|
|
@@ -320,13 +328,7 @@ export function summarizeUsage(records, { provider = "" } = {}) {
|
|
|
320
328
|
const modelTotals = summary.byModel[model];
|
|
321
329
|
modelTotals.requests += 1;
|
|
322
330
|
addUsageTotals(modelTotals, record.usage);
|
|
323
|
-
const
|
|
324
|
-
const cached = cacheReadTokens(record.usage || {});
|
|
325
|
-
const cacheCounts = [record.usage?.cached_input_tokens, record.usage?.cache_read_input_tokens];
|
|
326
|
-
const unknown = !Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input;
|
|
327
|
-
const invalid = (input != null && (!Number.isFinite(input) || input < 0))
|
|
328
|
-
|| cacheCounts.some(value => value != null && (!Number.isFinite(value) || value < 0))
|
|
329
|
-
|| (Number.isFinite(input) && Number.isFinite(cached) && cached > input);
|
|
331
|
+
const { unknown, invalid } = usageCacheEvidence(record.usage || {});
|
|
330
332
|
const qualified = `${source} / ${model}`;
|
|
331
333
|
if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
|
|
332
334
|
const sourceTotals = summary.bySourceModel[qualified];
|
|
@@ -424,3 +426,12 @@ export function usageCacheHitRate(usage = {}) {
|
|
|
424
426
|
|| !Number.isFinite(cached) || cached < 0 || cached > input) return null;
|
|
425
427
|
return cached / input;
|
|
426
428
|
}
|
|
429
|
+
|
|
430
|
+
function usageCacheEvidence(usage) {
|
|
431
|
+
const input = usage.input_tokens, cached = cacheReadTokens(usage);
|
|
432
|
+
const unknown = !Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input;
|
|
433
|
+
const invalid = (input != null && (!Number.isFinite(input) || input < 0))
|
|
434
|
+
|| [usage.cached_input_tokens, usage.cache_read_input_tokens].some(value => value != null && (!Number.isFinite(value) || value < 0))
|
|
435
|
+
|| (Number.isFinite(input) && Number.isFinite(cached) && cached > input);
|
|
436
|
+
return { cached, unknown, invalid };
|
|
437
|
+
}
|