codex-copilot-dx 0.9.28 → 0.9.29
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 +1 -1
- package/docs/ARCHITECTURE.md +12 -0
- package/docs/README.md +1 -0
- package/docs/REFERENCE.md +16 -4
- package/package.json +1 -1
- package/src/adapter.mjs +1 -1
- package/src/dashboard/index.html +4 -2
- package/src/dashboard/language.js +10 -0
- package/src/dashboard/refresh.js +103 -0
- package/src/dashboard/theme.js +1 -1
- package/src/dashboard/ui.css +3 -1
- package/src/dashboard/ui.js +203 -117
- package/src/dashboard.mjs +1 -0
- package/src/http-transport.mjs +4 -135
- package/src/live-models.mjs +6 -9
- package/src/responses-proxy.mjs +3 -1
- package/src/upstream-body.mjs +137 -0
- package/src/upstream-headers.mjs +6 -0
package/README.md
CHANGED
|
@@ -23,7 +23,7 @@ enabled. The configured `dummy` API key is a placeholder, not a credential.
|
|
|
23
23
|
|
|
24
24
|
Open [the local dashboard](http://127.0.0.1:2026/) for status, model discovery,
|
|
25
25
|
usage, cache/limits, recent failures, request context and animation settings.
|
|
26
|
-
|
|
26
|
+
Auto refresh runs every 30 minutes while visible and can be switched off. Hidden pages pause; opening sections and manual refresh still work.
|
|
27
27
|
|
|
28
28
|
## Commands
|
|
29
29
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -59,6 +59,18 @@ Without a complete verified local source, rejection still returns
|
|
|
59
59
|
metadata cannot reconstruct unavailable encrypted memory. LAN/browser callers
|
|
60
60
|
and referenced/split histories do not gain filesystem recovery access.
|
|
61
61
|
|
|
62
|
+
## Dashboard reads
|
|
63
|
+
|
|
64
|
+
`dashboard/refresh.js` owns the browser-only read lifecycle: one visible-page
|
|
65
|
+
timer, per-group in-flight deduplication, attempt freshness, cancellation and
|
|
66
|
+
last-good snapshots. `ui.js` owns rendering and user selections. Models, usage,
|
|
67
|
+
status/account and animation metadata remain independent resources; no timer
|
|
68
|
+
or data watcher is added to the Node service. Animation frames load once per
|
|
69
|
+
page when opened, and read refresh does not overwrite an unsaved choice.
|
|
70
|
+
`upstream-body.mjs` is the shared bounded response reader. The transport retains
|
|
71
|
+
its existing exports; live model lookup uses the same 8 MiB catalog limit as
|
|
72
|
+
core model discovery, without importing the request lifecycle or UI layer.
|
|
73
|
+
|
|
62
74
|
## Configuration ownership
|
|
63
75
|
|
|
64
76
|
`CODEX_HOME` selects Codex configuration. App profile/trust paths have their own
|
package/docs/README.md
CHANGED
|
@@ -17,6 +17,7 @@ These reports record a specific release and test environment. Their version,
|
|
|
17
17
|
test counts, timings, live-provider observations, and limitations remain
|
|
18
18
|
historical facts rather than current guarantees.
|
|
19
19
|
|
|
20
|
+
- [0.9.29: visible-page refresh, atom favicon and safe reasoning declarations](RELEASE_0.9.29.md)
|
|
20
21
|
- [0.9.28: verified local plaintext recovery and validation boundaries](RELEASE_0.9.28.md)
|
|
21
22
|
- [0.9.27: Windows certificate setup without Git/OpenSSL](RELEASE_0.9.27.md)
|
|
22
23
|
- [0.9.26: Windows native predictions, safe ownership recovery and dashboard disclosures](RELEASE_0.9.26.md)
|
package/docs/REFERENCE.md
CHANGED
|
@@ -244,6 +244,18 @@ plaintext. Cross-machine/LAN recovery is intentionally unavailable. A full
|
|
|
244
244
|
plaintext replay can still exceed the upstream context window; this recovery
|
|
245
245
|
does not silently truncate it or add chunked re-compaction.
|
|
246
246
|
|
|
247
|
+
### Reasoning usage declaration
|
|
248
|
+
|
|
249
|
+
Native Responses success replies preserve `X-Reasoning-Included: true` only
|
|
250
|
+
when the upstream explicitly returns a case-insensitive literal `true`.
|
|
251
|
+
Missing, false or other values are not forwarded: current Codex treats header
|
|
252
|
+
presence as a declaration that historical reasoning is already counted.
|
|
253
|
+
CCDX does not infer that declaration from `output_tokens_details`, invent it,
|
|
254
|
+
add it to Chat-converted replies or HTTP/JSON failures, or change token totals.
|
|
255
|
+
Streaming headers describe the upstream declaration, not a guarantee that the
|
|
256
|
+
stream will later complete. This is compatibility metadata, not proof of lower
|
|
257
|
+
context use, faster inference or fewer compactions on every client.
|
|
258
|
+
|
|
247
259
|
### Fast and Standard modes
|
|
248
260
|
|
|
249
261
|
Codex can select Standard or Fast without changing CCDX configuration. When the client requests a model with `service_tier: "priority"`, CCDX uses its exact `-fast` model only when the live Copilot catalog advertises that variant as enabled, selectable, OpenAI-owned, and Responses-only. Standard mode continues to use the base model; CCDX does not invent Fast availability when the upstream catalog does not provide it. This retains the established `gpt-5.6-sol` / `gpt-5.6-sol-fast` mapping and applies the same exact-match rule to future models.
|
|
@@ -522,19 +534,19 @@ JSON reply to a streaming request is still not silently converted to SSE.
|
|
|
522
534
|
|
|
523
535
|
After starting `ccdx`, open [http://127.0.0.1:2026/](http://127.0.0.1:2026/) in a browser. If `ADAPTER_PORT` is customized, use that port instead. The dashboard shares the existing adapter listener; CCDX does not open a browser automatically or start another service. The page and its assets require both a loopback connection and a loopback Host header, even when LAN binding is enabled.
|
|
524
536
|
|
|
525
|
-
The dashboard loads local status, a live GitHub Copilot model directory, and a summary of local usage metadata once when opened.
|
|
537
|
+
The dashboard loads local status, a live GitHub Copilot model directory, and a summary of local usage metadata once when opened. The top Refresh updates status/account and expanded data groups; model and usage sections retain their own Refresh controls. Auto refresh is on by default, saved only in this browser, and updates status/account plus expanded groups every 30 minutes while the page is visible. Opening a data section updates its group unless it was attempted within 30 seconds. Hidden pages pause; returning after 30 minutes catches up once, without replaying missed intervals. Turning automatic updates off retains manual and open-section refresh. No server background task is added. In-flight reads are shared per group; failures retain the prior snapshot and success timestamp. Unchanged model rows and charts are retained rather than rebuilt. The appearance button switches between the default dark terminal theme (sun icon) and a light theme (moon icon); the choice is stored only in that browser. The Requests card shows the running adapter's active raw and decoded per-request body limits, not request-body usage; Local History shows its in-memory Responses history use and active limit. Limit changes remain CLI-only (`ccdx limits` and `ccdx cache`). The live model table uses the same fresh account validation and selectable GPT filtering as `ccdx models`, never labels cached fallback data as online, and makes no inference request. A catalog listing does not guarantee inference access. The Model Usage table combines the current and rotated local usage logs, shows totals and up to 100 model rows, and contains no prompt, response body, or credential fields. The animation selector previews the existing themes and saves through the same settings writer as `ccdx animation`; changes take effect on the next adapter start, and `CCDX_TERMINAL_ANIMATION=off` still disables terminal motion. Dashboard data requests require a custom header that cross-site simple requests cannot send; animation writes also require a matching same-origin `Origin`. The dashboard does not initialize the optional image handler. The overview's known-model count is the adapter's current in-memory catalog, not the live table. A missing image-generation status does not prove the feature is disabled: use `ccdx image-status` to check setup. Recent upstream error prose may contain sensitive details, so review the page before sharing screenshots.
|
|
526
538
|
|
|
527
539
|
The dashboard labels the upstream token cache hit metric **Reuse Rate** and cached input **Reused Input**, separate from **Local History**. Chinese uses short functional names such as “对话暂存”, “重用输入” and “重用比例”. English and Chinese preserve model IDs, commands, units, HTTP status codes and raw diagnostic values. Animation display names translate in place; theme IDs and CLI parameters do not change.
|
|
528
540
|
|
|
529
|
-
The transparent, single-color
|
|
541
|
+
The transparent, single-color atom-orbit favicon follows the dashboard's saved light/dark choice without a separate network request.
|
|
530
542
|
|
|
531
|
-
The saved GitHub Copilot account appears immediately to the left of the Status updated time. It uses the same local credentials and fingerprint-bound identity metadata as `ccdx auth status`, with username (or numeric ID fallback) and a `SAVED` label; this is not an online entitlement check. Missing, invalid, unidentified, or unreadable credentials are shown explicitly. The account read runs
|
|
543
|
+
The saved GitHub Copilot account appears immediately to the left of the Status updated time. It uses the same local credentials and fingerprint-bound identity metadata as `ccdx auth status`, with username (or numeric ID fallback) and a `SAVED` label; this is not an online entitlement check. Missing, invalid, unidentified, or unreadable credentials are shown explicitly. The account read runs on page load, top Refresh and visible-page automatic updates, independently of adapter status and without upstream authentication calls. Its timestamp is in the account tooltip; failed updates retain the prior account and explicitly label the failure. Its loopback-only, custom-header-protected API exposes no token, fingerprint, credential path, or raw metadata. The general status endpoint retains its existing identity-free contract.
|
|
532
544
|
|
|
533
545
|
Account names containing underscores are supported, including `dingxiao_microsoft`. A numeric ID is a fallback, not a replacement for an available, safely displayable username; the existing length bounds and credential-shaped text suppression still apply.
|
|
534
546
|
|
|
535
547
|
The language button immediately right of the appearance button switches between English and Simplified Chinese. English remains the default; the choice is saved only in the current browser, separately from light/dark mode. Switching translates the existing page in place: it does not fetch API data, rebuild charts, change selected filters, discard unsaved animation choices, or reset expanded failure details. Static labels, live status text, chart tooltips and accessibility labels follow the selected language. Model IDs, account names, dates, numeric values and upstream diagnostic prose stay unchanged; copied diagnostic fields retain their original names and values. The local translation asset adds no dependency, external service, polling or inference-path work.
|
|
536
548
|
|
|
537
|
-
Usage Trends is collapsed by default. Opening it adds daily input/output token bars (7/30/90 days) and a 365-day calendar of recorded usage calls or tokens, grouped in the browser's time zone. Cache-read tokens are already part of input and are not added again. Model and range filters use the current snapshot without additional requests; selecting a day shows its filtered model totals in the Model Usage table, and Show all restores the original table. Analytics shares the existing current/rotated-log scan and exposes only bounded metadata (365 days, up to 100 model filters). Days before retained history are hatched, not presented as zero; the oldest retained day may be partial. Counts describe retained usage records, not messages, session time, or all HTTP requests.
|
|
549
|
+
Usage Trends is collapsed by default. Opening it adds daily input/output token bars (7/30/90 days) and a 365-day calendar of recorded usage calls or tokens, grouped in the browser's time zone. Cache-read tokens are already part of input and are not added again. Model and range filters use the current snapshot without additional requests; selecting a day shows its filtered model totals in the Model Usage table, and Show all restores the original table. Analytics shares the existing current/rotated-log scan and exposes only bounded metadata (365 days, up to 100 model filters). Days before retained history are hatched, not presented as zero; the oldest retained day may be partial. Counts describe retained usage records, not messages, session time, or all HTTP requests. Open-section, manual and visible-page automatic refresh update the snapshot. Analytics are requested only while expanded inside the open usage section or while a day filter needs them. Filters and selected dates survive refresh; a closed unfiltered chart reuses its displayed data until reopened. There is no server background collection.
|
|
538
550
|
|
|
539
551
|
Terminal Animation is collapsed at the bottom of the page, with an Animation shortcut in the header. Preview frames load only when opened; closing it, hiding the page, or requesting reduced motion stops the preview timer. Unsaved choices survive folding and reopening. Recent response failures expand to diagnostic fields (time, model, code, message, response/request IDs, and retry policy) with a Copy details control. The view combines the last 10 retained `response.failed` events with failures from the 20 most recently finished Responses/compact requests, showing at most 10 entries. Matching local request IDs attach the final outcome and timing metadata, so a recovered event can show `completed`; an uncorrelated retry attempt does not prove recovery. Transport failures and incomplete/cancelled requests can appear without a `response.failed` event. These are bounded runtime observations, not complete session histories. Diagnostic prose is redacted by the existing recorder but can still contain sensitive context: review before copying or sharing.
|
|
540
552
|
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -63,7 +63,7 @@ export {
|
|
|
63
63
|
} from "./responses-request.mjs";
|
|
64
64
|
|
|
65
65
|
const ADAPTER_RUNTIME_CONFIG = loadRuntimeConfig();
|
|
66
|
-
const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/ui.js"]);
|
|
66
|
+
const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/ui.js"]);
|
|
67
67
|
const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth"]);
|
|
68
68
|
|
|
69
69
|
export function requestPath(reqUrl) {
|
package/src/dashboard/index.html
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
<script src="/language.js"></script>
|
|
9
9
|
<script src="/theme.js"></script>
|
|
10
10
|
<link rel="stylesheet" href="/ui.css">
|
|
11
|
+
<script src="/refresh.js" defer></script>
|
|
11
12
|
<script src="/ui.js" defer></script>
|
|
12
13
|
<title data-i18n>CCDX · Local dashboard</title>
|
|
13
14
|
</head>
|
|
@@ -15,7 +16,7 @@
|
|
|
15
16
|
<div class="shell">
|
|
16
17
|
<header class="topbar">
|
|
17
18
|
<div class="brand">CCDX <span class="brand-detail" data-i18n>/ LOCAL STATUS</span></div>
|
|
18
|
-
<div class="topbar-actions"><span id="connection" class="badge neutral" role="status" data-i18n>READING</span><button id="theme-toggle" class="icon-button" type="button" aria-label="Switch to light mode" title="Switch to light mode"><svg class="icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42"/></svg><svg class="icon-moon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" focusable="false"><path d="M12 3A9 9 0 1 0 21 12 7 7 0 0 1 12 3Z"/></svg></button><button id="language-toggle" class="icon-button language-button" type="button" aria-label="Switch to Chinese" title="Switch to Chinese">中文</button><button id="open-animation" type="button" aria-controls="animation-settings" aria-expanded="false" data-i18n>Animation</button><button id="refresh" type="button" data-i18n>Refresh</button></div>
|
|
19
|
+
<div class="topbar-actions"><span id="connection" class="badge neutral" role="status" data-i18n>READING</span><button id="theme-toggle" class="icon-button" type="button" aria-label="Switch to light mode" title="Switch to light mode"><svg class="icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42"/></svg><svg class="icon-moon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" focusable="false"><path d="M12 3A9 9 0 1 0 21 12 7 7 0 0 1 12 3Z"/></svg></button><button id="language-toggle" class="icon-button language-button" type="button" aria-label="Switch to Chinese" title="Switch to Chinese">中文</button><button id="open-animation" type="button" aria-controls="animation-settings" aria-expanded="false" data-i18n>Animation</button><button id="auto-refresh" type="button" aria-pressed="true" data-i18n data-i18n-title title="Every 30 minutes while visible. Open sections update on demand.">Auto refresh</button><button id="refresh" type="button" data-i18n>Refresh</button></div>
|
|
19
20
|
</header>
|
|
20
21
|
|
|
21
22
|
<main>
|
|
@@ -86,6 +87,7 @@
|
|
|
86
87
|
<label><span data-i18n>Activity</span> <select id="analytics-metric"><option value="requests" data-i18n>Calls</option><option value="tokens" data-i18n>Tokens</option></select></label>
|
|
87
88
|
</div>
|
|
88
89
|
<p id="analytics-note" class="table-note" role="status" data-i18n>Open to read retained usage history.</p>
|
|
90
|
+
<p id="analytics-updated" class="refresh-time"></p>
|
|
89
91
|
<div class="chart-heading"><h3 data-i18n>DAILY TOKENS</h3><span data-i18n>INPUT + OUTPUT / CACHE INCLUDED IN INPUT</span></div>
|
|
90
92
|
<div id="daily-bars" class="daily-bars" aria-label="Daily token usage" data-i18n-label></div>
|
|
91
93
|
<div class="daily-axis"><span id="daily-from"></span><span id="daily-to"></span></div>
|
|
@@ -109,7 +111,7 @@
|
|
|
109
111
|
</details>
|
|
110
112
|
</main>
|
|
111
113
|
|
|
112
|
-
<footer data-i18n>LOCAL ONLY /
|
|
114
|
+
<footer data-i18n>LOCAL ONLY / VISIBLE PAGE UPDATES</footer>
|
|
113
115
|
</div>
|
|
114
116
|
</body>
|
|
115
117
|
</html>
|
|
@@ -23,6 +23,16 @@
|
|
|
23
23
|
"LOCAL OK": ["LOCAL OK", "本机正常"],
|
|
24
24
|
"UNAVAILABLE": ["UNAVAILABLE", "无法读取"],
|
|
25
25
|
"Refresh": ["Refresh", "刷新"],
|
|
26
|
+
"Auto refresh": ["Auto refresh", "自动更新"],
|
|
27
|
+
"Auto refresh / ON": ["Auto refresh · ON", "自动更新 · 开"],
|
|
28
|
+
"Auto refresh / OFF": ["Auto refresh · OFF", "自动更新 · 关"],
|
|
29
|
+
"Every 30 minutes while visible. Open sections update on demand.": ["Every 30 minutes while visible. Opening a section updates it.", "可见时每30分钟更新。\n展开区域也会更新。"],
|
|
30
|
+
"LOCAL ONLY / VISIBLE PAGE UPDATES": ["LOCAL ONLY / UPDATES WHILE VISIBLE", "仅限本机 / 页面可见时更新"],
|
|
31
|
+
"Updated {time}": ["Updated {time}", "更新于{time}"],
|
|
32
|
+
"Saved account / updated {time}": ["Saved account only / updated {time}", "本机保存账号 / 更新于{time}"],
|
|
33
|
+
"Update failed / last {time}": ["Update failed / last {time}", "更新失败 / 上次{time}"],
|
|
34
|
+
"Update failed": ["Update failed", "更新失败"],
|
|
35
|
+
"GitHub / {account} / UPDATE FAILED": ["GitHub / {account} / UPDATE FAILED", "GitHub / {account} / 更新失败"],
|
|
26
36
|
"Animation": ["Animation", "动效"],
|
|
27
37
|
"Switch to light mode": ["Light mode", "白天模式"],
|
|
28
38
|
"Switch to dark mode": ["Dark mode", "夜间模式"],
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const interval = 30 * 60 * 1000;
|
|
3
|
+
const freshness = 30 * 1000;
|
|
4
|
+
|
|
5
|
+
function createController({ resources, visible, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
|
|
6
|
+
const states = new Map(Object.keys(resources).map(key => [key, {
|
|
7
|
+
value: undefined, signature: undefined, variant: undefined, pending: null,
|
|
8
|
+
updatedAt: null, attemptedAt: null, error: null, generation: 0, abort: null,
|
|
9
|
+
}]));
|
|
10
|
+
let timer = null;
|
|
11
|
+
let active = true;
|
|
12
|
+
let automatic = true;
|
|
13
|
+
const state = key => states.get(key);
|
|
14
|
+
const stopTimer = () => { if (timer !== null) clearTimer(timer); timer = null; };
|
|
15
|
+
const notify = key => resources[key].state?.(state(key));
|
|
16
|
+
|
|
17
|
+
function schedule() {
|
|
18
|
+
stopTimer();
|
|
19
|
+
if (!active || !automatic || !visible()) return;
|
|
20
|
+
timer = setTimer(() => {
|
|
21
|
+
timer = null;
|
|
22
|
+
refreshVisible();
|
|
23
|
+
schedule();
|
|
24
|
+
}, interval);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function refresh(key, { force = false } = {}) {
|
|
28
|
+
if (!active) return;
|
|
29
|
+
const resource = resources[key];
|
|
30
|
+
const entry = state(key);
|
|
31
|
+
const variant = resource.variant?.() || "";
|
|
32
|
+
if (entry.pending) {
|
|
33
|
+
const pending = entry.pending;
|
|
34
|
+
const generation = entry.generation;
|
|
35
|
+
if (entry.pendingVariant === variant) return pending;
|
|
36
|
+
await pending;
|
|
37
|
+
if (!active || generation !== entry.generation) return entry.pending;
|
|
38
|
+
return refresh(key, { force: true });
|
|
39
|
+
}
|
|
40
|
+
if (!force && entry.attemptVariant === variant && entry.attemptedAt !== null && now() - entry.attemptedAt < freshness) return entry.value;
|
|
41
|
+
const generation = ++entry.generation;
|
|
42
|
+
const abort = new AbortController();
|
|
43
|
+
entry.abort = abort;
|
|
44
|
+
entry.attemptedAt = now();
|
|
45
|
+
entry.attemptVariant = variant;
|
|
46
|
+
entry.pendingVariant = variant;
|
|
47
|
+
entry.error = null;
|
|
48
|
+
entry.pending = Promise.resolve().then(async () => {
|
|
49
|
+
try {
|
|
50
|
+
const value = await resource.load({ variant, signal: abort.signal });
|
|
51
|
+
if (!active || generation !== entry.generation) return;
|
|
52
|
+
const signature = JSON.stringify(resource.project ? resource.project(value) : value);
|
|
53
|
+
const changed = signature !== entry.signature;
|
|
54
|
+
resource.apply(value, { changed });
|
|
55
|
+
entry.value = value;
|
|
56
|
+
entry.signature = signature;
|
|
57
|
+
entry.variant = variant;
|
|
58
|
+
entry.updatedAt = now();
|
|
59
|
+
return value;
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (active && generation === entry.generation) entry.error = error;
|
|
62
|
+
} finally {
|
|
63
|
+
if (generation === entry.generation) {
|
|
64
|
+
entry.pending = null;
|
|
65
|
+
entry.abort = null;
|
|
66
|
+
notify(key);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
notify(key);
|
|
71
|
+
return entry.pending;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function refreshVisible({ force = false } = {}) {
|
|
75
|
+
if (!active || !visible()) return Promise.resolve([]);
|
|
76
|
+
return Promise.all(Object.keys(resources).filter(key => resources[key].visible())
|
|
77
|
+
.filter(key => force || state(key).attemptedAt === null || now() - state(key).attemptedAt >= interval)
|
|
78
|
+
.map(key => refresh(key, { force })));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function invalidate(key) {
|
|
82
|
+
const entry = state(key);
|
|
83
|
+
entry.generation += 1;
|
|
84
|
+
entry.abort?.abort();
|
|
85
|
+
entry.pending = null;
|
|
86
|
+
entry.abort = null;
|
|
87
|
+
entry.attemptedAt = null;
|
|
88
|
+
entry.variant = undefined;
|
|
89
|
+
notify(key);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
refresh, refreshVisible, state, invalidate,
|
|
94
|
+
setAutomatic(value) { automatic = value === true; if (automatic) refreshVisible(); schedule(); },
|
|
95
|
+
visibilityChanged() { if (automatic && visible()) refreshVisible(); schedule(); },
|
|
96
|
+
resume() { active = true; if (automatic) refreshVisible(); schedule(); },
|
|
97
|
+
suspend() { active = false; stopTimer(); for (const key of states.keys()) if (state(key).pending) invalidate(key); },
|
|
98
|
+
get automatic() { return automatic; },
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
globalThis.ccdxRefresh = { createController };
|
|
103
|
+
})();
|
package/src/dashboard/theme.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
const applyTheme = () => {
|
|
8
8
|
document.documentElement.dataset.theme = theme;
|
|
9
9
|
const color = theme === "dark" ? "#a6f5a8" : "#176b3a";
|
|
10
|
-
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><
|
|
10
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><g fill="none" stroke="${color}" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="${color}"/></svg>`;
|
|
11
11
|
document.getElementById("favicon").href = `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
|
12
12
|
};
|
|
13
13
|
applyTheme();
|
package/src/dashboard/ui.css
CHANGED
|
@@ -129,7 +129,9 @@ select { max-width: 260px; padding: 5px; font: inherit; color: var(--text); back
|
|
|
129
129
|
.calendar-day[data-level="3"] { background: color-mix(in srgb, var(--accent-soft) 70%, var(--surface)); }
|
|
130
130
|
.calendar-day[data-level="4"] { background: var(--accent-soft); }
|
|
131
131
|
.calendar-day:disabled, .daily-bar:disabled { background: repeating-linear-gradient(135deg, transparent, transparent 3px, var(--border) 3px, var(--border) 4px); opacity: .5; cursor: default; }
|
|
132
|
-
footer { color: var(--footer); font-size: 10px; letter-spacing: .05em; padding: 22px 0 30px; }
|
|
132
|
+
footer { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; color: var(--footer); font-size: 10px; letter-spacing: .05em; padding: 22px 0 30px; }
|
|
133
|
+
#auto-refresh[aria-pressed="false"] { background: transparent; color: var(--muted); border-color: var(--border); }
|
|
134
|
+
.refresh-time { display: block; margin: 10px 0 0; color: var(--muted); font-size: 11px; line-height: 1.5; }
|
|
133
135
|
@media (max-width: 1000px) { .animation-options { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
|
134
136
|
@media (max-width: 900px) { .overview { grid-template-columns: repeat(2, minmax(0, 1fr)); } .details { grid-template-columns: repeat(2, minmax(0, 1fr)); } .details .panel:last-child { grid-column: 1 / -1; } }
|
|
135
137
|
@media (max-width: 680px) { .animation-options { grid-template-columns: 1fr; } }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -15,30 +15,19 @@ 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
|
-
let authLoading = false;
|
|
19
18
|
let contextRequests = [];
|
|
20
19
|
let contextCompactions = {};
|
|
20
|
+
let failureSignature;
|
|
21
|
+
let contextSignature;
|
|
21
22
|
|
|
22
|
-
function renderAuth(data) {
|
|
23
|
+
function renderAuth(data, { failed = false } = {}) {
|
|
23
24
|
const account = data.login ? `@${data.login}` : data.id ? `ID ${data.id}` : phrase("account unknown");
|
|
24
25
|
const label = data.reason === "credential_read_failed" ? "UNAVAILABLE"
|
|
25
26
|
: !data.configured ? "NOT CONFIGURED" : !data.valid ? "INVALID" : "SAVED";
|
|
26
|
-
text("auth-account", label === "SAVED" ? "GitHub / {account} / SAVED" : `GitHub / ${label}`, { account });
|
|
27
|
+
text("auth-account", failed ? "GitHub / {account} / UPDATE FAILED" : label === "SAVED" ? "GitHub / {account} / SAVED" : `GitHub / ${label}`, { account });
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
|
|
30
|
-
if (authLoading) return;
|
|
31
|
-
authLoading = true;
|
|
32
|
-
text("auth-account", "GitHub / READING");
|
|
33
|
-
try {
|
|
34
|
-
const response = await fetch("/_ccdx/ui/auth", { cache: "no-store", headers: { "X-CCDX-Dashboard": "1" }, signal: AbortSignal.timeout(5000) });
|
|
35
|
-
const data = await response.json();
|
|
36
|
-
if (!response.ok || data.source !== "local_auth_status") throw new Error("Auth status unavailable");
|
|
37
|
-
renderAuth(data);
|
|
38
|
-
} catch {
|
|
39
|
-
text("auth-account", "GitHub / UNAVAILABLE");
|
|
40
|
-
} finally { authLoading = false; }
|
|
41
|
-
}
|
|
30
|
+
const loadAuth = () => dashboardRefresh.refresh("auth", { force: true });
|
|
42
31
|
|
|
43
32
|
function duration(value) {
|
|
44
33
|
if (!finite(value)) return "—";
|
|
@@ -50,6 +39,9 @@ function duration(value) {
|
|
|
50
39
|
}
|
|
51
40
|
|
|
52
41
|
function renderFailures(recent, recentRequests = []) {
|
|
42
|
+
const signature = JSON.stringify([recent, recentRequests]);
|
|
43
|
+
if (signature === failureSignature) return;
|
|
44
|
+
failureSignature = signature;
|
|
53
45
|
const list = element("failures");
|
|
54
46
|
const expanded = new Set([...list.querySelectorAll("details[open]")].map((item) => item.dataset.key));
|
|
55
47
|
list.replaceChildren();
|
|
@@ -192,6 +184,9 @@ function renderContext(performance) {
|
|
|
192
184
|
completed: number(contextCompactions.completed), incomplete: number(contextCompactions.incomplete), failed: number(contextCompactions.failed),
|
|
193
185
|
});
|
|
194
186
|
if (element("request-context")?.open === false) return;
|
|
187
|
+
const signature = JSON.stringify(contextRequests);
|
|
188
|
+
if (signature === contextSignature) return;
|
|
189
|
+
contextSignature = signature;
|
|
195
190
|
body.replaceChildren();
|
|
196
191
|
for (const request of contextRequests) {
|
|
197
192
|
const context = request.context || {};
|
|
@@ -207,36 +202,9 @@ function renderContext(performance) {
|
|
|
207
202
|
if (!contextRequests.length) emptyTable("context-body", 7, "No observed request metadata.");
|
|
208
203
|
}
|
|
209
204
|
|
|
210
|
-
|
|
211
|
-
const button = element("refresh");
|
|
212
|
-
button.disabled = true;
|
|
213
|
-
text("connection", "READING");
|
|
214
|
-
element("connection").className = "badge neutral";
|
|
215
|
-
try {
|
|
216
|
-
const response = await fetch("/_ccdx/status", {
|
|
217
|
-
cache: "no-store",
|
|
218
|
-
headers: { Accept: "application/json" },
|
|
219
|
-
signal: AbortSignal.timeout(5000),
|
|
220
|
-
});
|
|
221
|
-
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
222
|
-
const data = await response.json();
|
|
223
|
-
if (data?.ok !== true || data?.name !== "codex-copilot-dx") throw new Error("Unexpected status response");
|
|
224
|
-
render(data);
|
|
225
|
-
text("connection", "LOCAL OK");
|
|
226
|
-
element("connection").className = "badge good";
|
|
227
|
-
} catch {
|
|
228
|
-
text("connection", "UNAVAILABLE");
|
|
229
|
-
element("connection").className = "badge bad";
|
|
230
|
-
text("updated", "Status unavailable / check ccdx, then refresh");
|
|
231
|
-
} finally {
|
|
232
|
-
button.disabled = false;
|
|
233
|
-
}
|
|
234
|
-
}
|
|
205
|
+
const refresh = () => dashboardRefresh.refresh("status", { force: true });
|
|
235
206
|
|
|
236
|
-
element("refresh").addEventListener("click", () => {
|
|
237
|
-
element("request-context").addEventListener("toggle", () => { if (element("request-context").open) renderContext(); });
|
|
238
|
-
refresh();
|
|
239
|
-
loadAuth();
|
|
207
|
+
element("refresh").addEventListener("click", () => dashboardRefresh.refreshVisible({ force: true }));
|
|
240
208
|
|
|
241
209
|
const animationRows = new Map();
|
|
242
210
|
let animationTimelines = [];
|
|
@@ -246,7 +214,7 @@ let previewDisabledByEnvironment = false;
|
|
|
246
214
|
let previewVisible = false;
|
|
247
215
|
let previewTimer = null;
|
|
248
216
|
let previewStarted = 0;
|
|
249
|
-
let
|
|
217
|
+
let animationSaving = false;
|
|
250
218
|
let animationFramesLoaded = false;
|
|
251
219
|
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
|
252
220
|
|
|
@@ -361,28 +329,26 @@ function animationNote(data) {
|
|
|
361
329
|
: "Saved choice applies on next ccdx start.";
|
|
362
330
|
}
|
|
363
331
|
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
text("animation-note", String(error.message || error).slice(0, 180));
|
|
382
|
-
} finally {
|
|
383
|
-
animationLoading = false;
|
|
384
|
-
if (!includeFrames && element("animation-settings").open) loadAnimation();
|
|
332
|
+
function loadAnimation(options) {
|
|
333
|
+
if (!animationSaving) return dashboardRefresh.refresh("animation", options);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function applyAnimation(data, { changed } = {}) {
|
|
337
|
+
if (changed === false) { updateAnimationState(); return; }
|
|
338
|
+
if (!animationFramesLoaded && data.themes.some(theme => theme.frames)) {
|
|
339
|
+
buildAnimationOptions(data);
|
|
340
|
+
animationFramesLoaded = true;
|
|
341
|
+
} else {
|
|
342
|
+
const dirty = selectedAnimation && selectedAnimation !== savedAnimation;
|
|
343
|
+
savedAnimation = data.theme;
|
|
344
|
+
if (!dirty) selectedAnimation = data.theme;
|
|
345
|
+
previewDisabledByEnvironment = data.disabled_by_environment === true;
|
|
346
|
+
for (const [id, row] of animationRows) row.setAttribute("aria-pressed", String(id === selectedAnimation));
|
|
347
|
+
element("save-animation").disabled = selectedAnimation === savedAnimation;
|
|
348
|
+
syncAnimationPreview();
|
|
385
349
|
}
|
|
350
|
+
updateAnimationState();
|
|
351
|
+
text("animation-note", animationNote(data));
|
|
386
352
|
}
|
|
387
353
|
|
|
388
354
|
function updateAnimationState() {
|
|
@@ -392,6 +358,8 @@ function updateAnimationState() {
|
|
|
392
358
|
async function saveAnimation() {
|
|
393
359
|
const button = element("save-animation");
|
|
394
360
|
if (!selectedAnimation || selectedAnimation === savedAnimation) return;
|
|
361
|
+
animationSaving = true;
|
|
362
|
+
dashboardRefresh.invalidate("animation");
|
|
395
363
|
button.disabled = true;
|
|
396
364
|
text("animation-note", "Saving…");
|
|
397
365
|
try {
|
|
@@ -409,7 +377,9 @@ async function saveAnimation() {
|
|
|
409
377
|
} catch (error) {
|
|
410
378
|
text("animation-note", "Not saved / {error}", { error: String(error.message || error).slice(0, 150) });
|
|
411
379
|
} finally {
|
|
380
|
+
animationSaving = false;
|
|
412
381
|
button.disabled = selectedAnimation === savedAnimation;
|
|
382
|
+
loadAnimation({ force: true });
|
|
413
383
|
}
|
|
414
384
|
}
|
|
415
385
|
|
|
@@ -436,34 +406,18 @@ function tableRow(values, { total = false, labels = [] } = {}) {
|
|
|
436
406
|
return row;
|
|
437
407
|
}
|
|
438
408
|
|
|
439
|
-
async function loadModels() {
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
text("models-note", "Querying GitHub Copilot…");
|
|
444
|
-
emptyTable("live-models-body", 4, "Loading…");
|
|
445
|
-
try {
|
|
446
|
-
const response = await fetch("/_ccdx/ui/models/live", { cache: "no-store", headers: { "X-CCDX-Dashboard": "1" }, signal: AbortSignal.timeout(15000) });
|
|
447
|
-
const data = await response.json();
|
|
448
|
-
if (!response.ok || data.source !== "live") throw new Error(data.error || `HTTP ${response.status}`);
|
|
409
|
+
async function loadModels() { return dashboardRefresh.refresh("models", { force: true }); }
|
|
410
|
+
|
|
411
|
+
function applyModels(data, { changed }) {
|
|
412
|
+
if (changed) {
|
|
449
413
|
const body = element("live-models-body");
|
|
450
414
|
body.replaceChildren();
|
|
451
415
|
for (const model of data.models) {
|
|
452
416
|
body.append(tableRow([model.id, model.vendor, model.endpoints.join(" / "), model.preview ? "preview" : "—"], { labels: [3] }));
|
|
453
417
|
}
|
|
454
418
|
if (!data.models.length) emptyTable("live-models-body", 4, "No selectable GPT models advertised.");
|
|
455
|
-
text("models-state", "LIVE SNAPSHOT");
|
|
456
|
-
text("models-note", "{selectable} selectable / {advertised} advertised / {host} / {time}", { selectable: number(data.selectable), advertised: number(data.advertised), host: data.upstream_host, time: new Date(data.checked_at).toLocaleTimeString() });
|
|
457
|
-
} catch (error) {
|
|
458
|
-
text("models-state", "LIVE LOOKUP FAILED");
|
|
459
|
-
const message = String(error.message || error).slice(0, 240);
|
|
460
|
-
const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
|
|
461
|
-
if (httpError) text("models-note", "Live model lookup failed (HTTP {status}). Run ccdx models for details.", { status: httpError[1] });
|
|
462
|
-
else text("models-note", message);
|
|
463
|
-
emptyTable("live-models-body", 4, "No live catalog available.");
|
|
464
|
-
} finally {
|
|
465
|
-
button.disabled = false;
|
|
466
419
|
}
|
|
420
|
+
text("models-note", "{selectable} selectable / {advertised} advertised / {host} / {time}", { selectable: number(data.selectable), advertised: number(data.advertised), host: data.upstream_host, time: new Date(data.checked_at).toLocaleTimeString() });
|
|
467
421
|
}
|
|
468
422
|
|
|
469
423
|
function usageValues(row) {
|
|
@@ -473,7 +427,7 @@ function usageValues(row) {
|
|
|
473
427
|
}
|
|
474
428
|
|
|
475
429
|
let usageData = null;
|
|
476
|
-
let
|
|
430
|
+
let analyticsSignature;
|
|
477
431
|
let selectedUsageDate = "";
|
|
478
432
|
|
|
479
433
|
function renderUsageTable() {
|
|
@@ -495,6 +449,10 @@ function renderUsageTable() {
|
|
|
495
449
|
});
|
|
496
450
|
}
|
|
497
451
|
|
|
452
|
+
function renderUsageState() {
|
|
453
|
+
text("usage-state", selectedUsageDate && usageData.analytics?.days.some(day => day.date === selectedUsageDate) ? selectedUsageDate : "LOCAL LOG");
|
|
454
|
+
}
|
|
455
|
+
|
|
498
456
|
function analyticsPoint(day, model) {
|
|
499
457
|
return model ? day.models.find((row) => row.model === model) || { requests: 0, input_tokens: 0, output_tokens: 0 } : day;
|
|
500
458
|
}
|
|
@@ -523,6 +481,9 @@ function renderAnalytics() {
|
|
|
523
481
|
const analytics = usageData?.analytics;
|
|
524
482
|
if (!analytics) return;
|
|
525
483
|
const model = element("analytics-model").value;
|
|
484
|
+
const signature = JSON.stringify([analytics, model, element("analytics-range").value, element("analytics-metric").value, selectedUsageDate]);
|
|
485
|
+
if (signature === analyticsSignature) return;
|
|
486
|
+
analyticsSignature = signature;
|
|
526
487
|
const days = analytics.days;
|
|
527
488
|
const daily = days.slice(-Number(element("analytics-range").value));
|
|
528
489
|
const maximum = Math.max(1, ...daily.map((day) => {
|
|
@@ -593,44 +554,167 @@ function updateAnalyticsModels() {
|
|
|
593
554
|
const select = element("analytics-model");
|
|
594
555
|
const previous = select.value;
|
|
595
556
|
select.replaceChildren();
|
|
596
|
-
for (const model of ["", ...usageData.analytics.models]) {
|
|
557
|
+
for (const model of [...new Set(["", ...usageData.analytics.models, ...(previous ? [previous] : [])])]) {
|
|
597
558
|
const option = document.createElement("option");
|
|
598
559
|
option.value = model;
|
|
599
560
|
if (model) option.textContent = model;
|
|
600
561
|
else localize(option, "All models");
|
|
601
562
|
select.append(option);
|
|
602
563
|
}
|
|
603
|
-
select.value =
|
|
564
|
+
select.value = previous;
|
|
604
565
|
}
|
|
605
566
|
|
|
606
|
-
async function loadUsage() {
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
button.disabled = true;
|
|
612
|
-
text("usage-state", "READING LOG");
|
|
613
|
-
text("usage-note", "Aggregating local usage metadata…");
|
|
614
|
-
emptyTable("usage-body", 7, "Loading…");
|
|
615
|
-
try {
|
|
616
|
-
const query = includeAnalytics ? `?analytics=1&time_zone=${encodeURIComponent(Intl.DateTimeFormat().resolvedOptions().timeZone)}` : "";
|
|
617
|
-
const response = await fetch(`/_ccdx/ui/usage${query}`, { cache: "no-store", headers: { "X-CCDX-Dashboard": "1" }, signal: AbortSignal.timeout(15000) });
|
|
618
|
-
const data = await response.json();
|
|
619
|
-
if (!response.ok || data.source !== "local_usage_log") throw new Error(data.error || `HTTP ${response.status}`);
|
|
620
|
-
usageData = data;
|
|
567
|
+
async function loadUsage() { return dashboardRefresh.refresh("usage", { force: true }); }
|
|
568
|
+
|
|
569
|
+
function applyUsage(data, { changed }) {
|
|
570
|
+
usageData = { ...data, ...(!data.analytics && usageData?.analytics ? { analytics: usageData.analytics } : {}) };
|
|
571
|
+
if (changed) {
|
|
621
572
|
if (data.analytics) updateAnalyticsModels();
|
|
622
573
|
renderUsageTable();
|
|
623
|
-
renderAnalytics();
|
|
624
|
-
} catch (error) {
|
|
625
|
-
text("usage-state", "LOG UNAVAILABLE");
|
|
626
|
-
text("usage-note", String(error.message || error).slice(0, 180));
|
|
627
|
-
emptyTable("usage-body", 7, "No usage summary available.");
|
|
628
|
-
if (includeAnalytics) text("analytics-note", "Analytics unavailable / refresh Usage to retry.");
|
|
629
|
-
} finally {
|
|
630
|
-
usageLoading = false;
|
|
631
|
-
button.disabled = false;
|
|
632
|
-
if (!includeAnalytics && element("usage-analytics").open) loadUsage();
|
|
574
|
+
if (data.analytics) renderAnalytics();
|
|
633
575
|
}
|
|
576
|
+
if (data.analytics) {
|
|
577
|
+
text("analytics-updated", "Updated {time}", { time: new Date().toLocaleTimeString() });
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
async function readDashboard(url, { signal, timeout = 15000, source } = {}) {
|
|
582
|
+
const response = await fetch(url, { cache: "no-store", headers: { "X-CCDX-Dashboard": "1", Accept: "application/json" },
|
|
583
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]) });
|
|
584
|
+
const data = await response.json();
|
|
585
|
+
if (!response.ok || (source && data.source !== source)) throw new Error(data.error || `HTTP ${response.status}`);
|
|
586
|
+
return data;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function refreshTime(target, state) {
|
|
590
|
+
const time = state.updatedAt === null ? null : new Date(state.updatedAt).toLocaleTimeString();
|
|
591
|
+
if (state.error) localize(target, time ? "Update failed / last {time}" : "Update failed", { time });
|
|
592
|
+
else if (time) localize(target, "Updated {time}", { time });
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const timestamps = new Map();
|
|
596
|
+
for (const [key, ids] of [["status", ["client-features", "request-context", "recent-failures"]], ["models", ["upstream-models"]], ["usage", ["model-usage"]], ["animation", ["animation-settings"]]]) {
|
|
597
|
+
timestamps.set(key, ids.map(id => {
|
|
598
|
+
const node = document.createElement("p");
|
|
599
|
+
node.className = "refresh-time";
|
|
600
|
+
element(id).append(node);
|
|
601
|
+
return node;
|
|
602
|
+
}));
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
606
|
+
visible: () => document.visibilityState === "visible",
|
|
607
|
+
resources: {
|
|
608
|
+
status: {
|
|
609
|
+
visible: () => true,
|
|
610
|
+
load: async ({ signal }) => {
|
|
611
|
+
const data = await readDashboard("/_ccdx/status", { signal, timeout: 5000 });
|
|
612
|
+
if (data.ok !== true || data.name !== "codex-copilot-dx") throw new Error("Unexpected status response");
|
|
613
|
+
return data;
|
|
614
|
+
},
|
|
615
|
+
apply: render,
|
|
616
|
+
state: state => {
|
|
617
|
+
element("refresh").disabled = Boolean(state.pending);
|
|
618
|
+
text("connection", state.pending || (!state.value && !state.error) ? "READING" : state.error ? "UNAVAILABLE" : "LOCAL OK");
|
|
619
|
+
element("connection").className = `badge ${state.pending ? "neutral" : state.error ? "bad" : "good"}`;
|
|
620
|
+
if (state.error) refreshTime(element("updated"), state);
|
|
621
|
+
for (const node of timestamps.get("status")) refreshTime(node, state);
|
|
622
|
+
},
|
|
623
|
+
},
|
|
624
|
+
auth: {
|
|
625
|
+
visible: () => true,
|
|
626
|
+
load: ({ signal }) => readDashboard("/_ccdx/ui/auth", { signal, timeout: 5000, source: "local_auth_status" }),
|
|
627
|
+
apply: renderAuth,
|
|
628
|
+
state: state => {
|
|
629
|
+
if (state.value) renderAuth(state.value, { failed: Boolean(state.error) });
|
|
630
|
+
else text("auth-account", state.error ? "GitHub / UNAVAILABLE" : "GitHub / READING");
|
|
631
|
+
if (state.updatedAt !== null) localize(element("auth-account"), "Saved account / updated {time}", { time: new Date(state.updatedAt).toLocaleTimeString() }, "title");
|
|
632
|
+
},
|
|
633
|
+
},
|
|
634
|
+
models: {
|
|
635
|
+
visible: () => element("upstream-models").open,
|
|
636
|
+
load: async ({ signal }) => {
|
|
637
|
+
const data = await readDashboard("/_ccdx/ui/models/live", { signal, source: "live" });
|
|
638
|
+
if (!Array.isArray(data.models) || data.models.some(model => !model || typeof model.id !== "string" || !Array.isArray(model.endpoints))) throw new Error("Invalid model snapshot");
|
|
639
|
+
return data;
|
|
640
|
+
},
|
|
641
|
+
project: data => [data.models, data.selectable, data.advertised, data.upstream_host],
|
|
642
|
+
apply: applyModels,
|
|
643
|
+
state: state => {
|
|
644
|
+
element("refresh-models").disabled = Boolean(state.pending);
|
|
645
|
+
text("models-state", state.pending ? "CHECKING LIVE" : state.error ? "LIVE LOOKUP FAILED" : "LIVE SNAPSHOT");
|
|
646
|
+
if (state.error) {
|
|
647
|
+
const message = String(state.error.message || state.error).slice(0, 240);
|
|
648
|
+
const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
|
|
649
|
+
if (httpError) text("models-note", "Live model lookup failed (HTTP {status}). Run ccdx models for details.", { status: httpError[1] });
|
|
650
|
+
else text("models-note", message);
|
|
651
|
+
}
|
|
652
|
+
if (state.error && !state.value) emptyTable("live-models-body", 4, "No live catalog available.");
|
|
653
|
+
for (const node of timestamps.get("models")) refreshTime(node, state);
|
|
654
|
+
},
|
|
655
|
+
},
|
|
656
|
+
usage: {
|
|
657
|
+
visible: () => element("model-usage").open,
|
|
658
|
+
variant: () => ((element("model-usage").open && element("usage-analytics").open) || Boolean(selectedUsageDate)) ? "analytics" : "summary",
|
|
659
|
+
load: async ({ variant, signal }) => {
|
|
660
|
+
const data = await readDashboard(`/_ccdx/ui/usage${variant === "analytics" ? `?analytics=1&time_zone=${encodeURIComponent(Intl.DateTimeFormat().resolvedOptions().timeZone)}` : ""}`, { signal, source: "local_usage_log" });
|
|
661
|
+
if (!data.total || !Array.isArray(data.rows) || (variant === "analytics" && (!Array.isArray(data.analytics?.days) || !data.analytics.days.length))) throw new Error("Invalid usage snapshot");
|
|
662
|
+
return data;
|
|
663
|
+
},
|
|
664
|
+
apply: applyUsage,
|
|
665
|
+
state: state => {
|
|
666
|
+
element("refresh-usage").disabled = Boolean(state.pending);
|
|
667
|
+
if (state.pending) text("usage-state", "READING LOG");
|
|
668
|
+
else if (state.error) {
|
|
669
|
+
text("usage-state", "LOG UNAVAILABLE");
|
|
670
|
+
if (element("usage-analytics").open) text("analytics-note", "Analytics unavailable / refresh Usage to retry.");
|
|
671
|
+
if (!state.value) emptyTable("usage-body", 7, "No usage summary available.");
|
|
672
|
+
} else if (state.value) renderUsageState();
|
|
673
|
+
for (const node of timestamps.get("usage")) refreshTime(node, state);
|
|
674
|
+
},
|
|
675
|
+
},
|
|
676
|
+
animation: {
|
|
677
|
+
visible: () => element("animation-settings").open && !animationSaving,
|
|
678
|
+
variant: () => element("animation-settings").open && !animationFramesLoaded ? "frames" : "metadata",
|
|
679
|
+
project: data => [data.theme, data.source, data.disabled_by_environment, data.themes.map(theme => [theme.id, theme.label, theme.default, Boolean(theme.frames)])],
|
|
680
|
+
load: ({ variant, signal }) => readDashboard(`/_ccdx/ui/animation${variant === "frames" ? "" : "?frames=0"}`, { signal, timeout: 8000 }),
|
|
681
|
+
apply: applyAnimation,
|
|
682
|
+
state: state => {
|
|
683
|
+
if (state.error) {
|
|
684
|
+
text("animation-state", "UNAVAILABLE");
|
|
685
|
+
text("animation-note", String(state.error.message || state.error).slice(0, 180));
|
|
686
|
+
}
|
|
687
|
+
for (const node of timestamps.get("animation")) refreshTime(node, state);
|
|
688
|
+
},
|
|
689
|
+
},
|
|
690
|
+
},
|
|
691
|
+
});
|
|
692
|
+
|
|
693
|
+
const autoRefreshKey = "ccdx.dashboard.autoRefresh";
|
|
694
|
+
const updateAutoRefresh = () => {
|
|
695
|
+
element("auto-refresh").setAttribute("aria-pressed", String(dashboardRefresh.automatic));
|
|
696
|
+
text("auto-refresh", dashboardRefresh.automatic ? "Auto refresh / ON" : "Auto refresh / OFF");
|
|
697
|
+
};
|
|
698
|
+
let automatic = true;
|
|
699
|
+
try { automatic = localStorage.getItem(autoRefreshKey) !== "off"; } catch { /* Keep the default when browser storage is unavailable. */ }
|
|
700
|
+
dashboardRefresh.setAutomatic(automatic);
|
|
701
|
+
updateAutoRefresh();
|
|
702
|
+
element("auto-refresh").addEventListener("click", () => {
|
|
703
|
+
dashboardRefresh.setAutomatic(!dashboardRefresh.automatic);
|
|
704
|
+
updateAutoRefresh();
|
|
705
|
+
try { localStorage.setItem(autoRefreshKey, dashboardRefresh.automatic ? "on" : "off"); } catch { /* Keep the current choice. */ }
|
|
706
|
+
});
|
|
707
|
+
document.addEventListener("visibilitychange", () => dashboardRefresh.visibilityChanged());
|
|
708
|
+
window.addEventListener("pagehide", () => { dashboardRefresh.suspend(); stopAnimationPreview(); });
|
|
709
|
+
window.addEventListener("pageshow", () => { dashboardRefresh.resume(); syncAnimationPreview(); });
|
|
710
|
+
|
|
711
|
+
for (const [id, key] of [["client-features", "status"], ["request-context", "status"], ["recent-failures", "status"], ["upstream-models", "models"], ["model-usage", "usage"]]) {
|
|
712
|
+
element(id).addEventListener("toggle", () => {
|
|
713
|
+
if (element(id).open) {
|
|
714
|
+
if (id === "request-context") renderContext();
|
|
715
|
+
dashboardRefresh.refresh(key);
|
|
716
|
+
}
|
|
717
|
+
});
|
|
634
718
|
}
|
|
635
719
|
|
|
636
720
|
element("save-animation").addEventListener("click", saveAnimation);
|
|
@@ -646,7 +730,7 @@ element("open-animation").addEventListener("click", () => {
|
|
|
646
730
|
settings.querySelector("summary").focus();
|
|
647
731
|
});
|
|
648
732
|
element("usage-analytics").addEventListener("toggle", () => {
|
|
649
|
-
if (element("usage-analytics").open &&
|
|
733
|
+
if (element("usage-analytics").open && element("model-usage").open) dashboardRefresh.refresh("usage");
|
|
650
734
|
});
|
|
651
735
|
for (const id of ["analytics-model", "analytics-range", "analytics-metric"]) element(id).addEventListener("change", () => {
|
|
652
736
|
renderAnalytics();
|
|
@@ -658,3 +742,5 @@ element("refresh-usage").addEventListener("click", loadUsage);
|
|
|
658
742
|
loadAnimation();
|
|
659
743
|
loadModels();
|
|
660
744
|
loadUsage();
|
|
745
|
+
refresh();
|
|
746
|
+
loadAuth();
|
package/src/dashboard.mjs
CHANGED
|
@@ -7,6 +7,7 @@ const ASSETS = new Map([
|
|
|
7
7
|
["/theme.js", ["./dashboard/theme.js", "text/javascript; charset=utf-8"]],
|
|
8
8
|
["/language.js", ["./dashboard/language.js", "text/javascript; charset=utf-8"]],
|
|
9
9
|
["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
|
|
10
|
+
["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
|
|
10
11
|
]);
|
|
11
12
|
|
|
12
13
|
export async function serveDashboard(req, res, pathname) {
|
package/src/http-transport.mjs
CHANGED
|
@@ -21,144 +21,13 @@ const HTTP_RUNTIME_CONFIG = loadRuntimeConfig();
|
|
|
21
21
|
const MAX_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxBodyBytes;
|
|
22
22
|
export const MAX_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
|
|
23
23
|
|
|
24
|
-
export
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
export {
|
|
25
|
+
MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, MAX_UPSTREAM_RETRY_DRAIN_BYTES,
|
|
26
|
+
readBoundedResponseBuffer, readBoundedResponseText, discardBoundedResponseBody,
|
|
27
|
+
} from "./upstream-body.mjs";
|
|
27
28
|
export const MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxUpstreamChatResponseBytes;
|
|
28
29
|
export const MAX_UPSTREAM_RESPONSES_SUCCESS_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxUpstreamResponsesResponseBytes;
|
|
29
30
|
|
|
30
|
-
function upstreamBodyTooLarge(label, maxBytes) {
|
|
31
|
-
const error = httpError(`${label} exceeds ${maxBytes} bytes`, 502);
|
|
32
|
-
error.code = "ccdx_upstream_response_too_large";
|
|
33
|
-
error.jsonBody = {
|
|
34
|
-
error: {
|
|
35
|
-
message: error.message,
|
|
36
|
-
type: "upstream_error",
|
|
37
|
-
code: error.code,
|
|
38
|
-
},
|
|
39
|
-
};
|
|
40
|
-
return error;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function unreadableUpstreamBody(label) {
|
|
44
|
-
const error = httpError(`${label} is not a readable web stream`, 502);
|
|
45
|
-
error.code = "ccdx_upstream_response_unreadable";
|
|
46
|
-
error.jsonBody = {
|
|
47
|
-
error: {
|
|
48
|
-
message: error.message,
|
|
49
|
-
type: "upstream_error",
|
|
50
|
-
code: error.code,
|
|
51
|
-
},
|
|
52
|
-
};
|
|
53
|
-
return error;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
async function cancelResponseBody(response) {
|
|
57
|
-
try { await response?.body?.cancel?.(); } catch {}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function responseAbortError(signal) {
|
|
61
|
-
if (signal?.reason instanceof Error) return signal.reason;
|
|
62
|
-
const error = new Error("The operation was aborted");
|
|
63
|
-
error.name = "AbortError";
|
|
64
|
-
return error;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function readResponseChunk(reader, signal) {
|
|
68
|
-
if (!signal) return reader.read();
|
|
69
|
-
if (signal.aborted) return Promise.reject(responseAbortError(signal));
|
|
70
|
-
return new Promise((resolve, reject) => {
|
|
71
|
-
let settled = false;
|
|
72
|
-
const finish = (callback, value) => {
|
|
73
|
-
if (settled) return;
|
|
74
|
-
settled = true;
|
|
75
|
-
signal.removeEventListener("abort", onAbort);
|
|
76
|
-
callback(value);
|
|
77
|
-
};
|
|
78
|
-
const onAbort = () => {
|
|
79
|
-
const error = responseAbortError(signal);
|
|
80
|
-
try { Promise.resolve(reader.cancel(error)).catch(() => {}); } catch {}
|
|
81
|
-
finish(reject, error);
|
|
82
|
-
};
|
|
83
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
84
|
-
reader.read().then(
|
|
85
|
-
(value) => finish(resolve, value),
|
|
86
|
-
(error) => finish(reject, error),
|
|
87
|
-
);
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function responseContentLength(response) {
|
|
92
|
-
const raw = response?.headers?.get?.("content-length")
|
|
93
|
-
?? response?.headers?.["content-length"]
|
|
94
|
-
?? response?.headers?.["Content-Length"];
|
|
95
|
-
const parsed = Number.parseInt(raw || "", 10);
|
|
96
|
-
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export async function readBoundedResponseBuffer(response, {
|
|
100
|
-
maxBytes,
|
|
101
|
-
label = "Upstream response body",
|
|
102
|
-
signal,
|
|
103
|
-
} = {}) {
|
|
104
|
-
const limit = Number.isFinite(maxBytes) && maxBytes >= 0 ? Math.floor(maxBytes) : 0;
|
|
105
|
-
if (signal?.aborted) {
|
|
106
|
-
cancelResponseBody(response);
|
|
107
|
-
throw responseAbortError(signal);
|
|
108
|
-
}
|
|
109
|
-
if (responseContentLength(response) > limit) {
|
|
110
|
-
await cancelResponseBody(response);
|
|
111
|
-
throw upstreamBodyTooLarge(label, limit);
|
|
112
|
-
}
|
|
113
|
-
if (!response?.body) {
|
|
114
|
-
if (typeof response?.text === "function") {
|
|
115
|
-
const buffer = Buffer.from(await response.text());
|
|
116
|
-
if (buffer.length > limit) throw upstreamBodyTooLarge(label, limit);
|
|
117
|
-
return buffer;
|
|
118
|
-
}
|
|
119
|
-
if ((responseContentLength(response) || 0) > 0) throw unreadableUpstreamBody(label);
|
|
120
|
-
return Buffer.alloc(0);
|
|
121
|
-
}
|
|
122
|
-
const reader = response?.body?.getReader?.();
|
|
123
|
-
if (!reader) throw unreadableUpstreamBody(label);
|
|
124
|
-
const chunks = [];
|
|
125
|
-
let total = 0;
|
|
126
|
-
try {
|
|
127
|
-
while (true) {
|
|
128
|
-
const { done, value } = await readResponseChunk(reader, signal);
|
|
129
|
-
if (done) break;
|
|
130
|
-
const chunk = Buffer.from(value);
|
|
131
|
-
total += chunk.length;
|
|
132
|
-
if (total > limit) {
|
|
133
|
-
await reader.cancel().catch(() => {});
|
|
134
|
-
throw upstreamBodyTooLarge(label, limit);
|
|
135
|
-
}
|
|
136
|
-
chunks.push(chunk);
|
|
137
|
-
}
|
|
138
|
-
return Buffer.concat(chunks, total);
|
|
139
|
-
} finally {
|
|
140
|
-
try {
|
|
141
|
-
reader.releaseLock();
|
|
142
|
-
} catch (error) {
|
|
143
|
-
if (!signal?.aborted) throw error;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
export async function readBoundedResponseText(response, options) {
|
|
149
|
-
return new TextDecoder().decode(await readBoundedResponseBuffer(response, options));
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
export async function discardBoundedResponseBody(response, maxBytes = MAX_UPSTREAM_RETRY_DRAIN_BYTES) {
|
|
153
|
-
try {
|
|
154
|
-
await readBoundedResponseBuffer(response, { maxBytes, label: "Upstream retry response body" });
|
|
155
|
-
return true;
|
|
156
|
-
} catch {
|
|
157
|
-
await cancelResponseBody(response);
|
|
158
|
-
return false;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
31
|
function payloadTooLarge(kind, maxBytes) {
|
|
163
32
|
return httpError(`${kind} request body exceeds ${maxBytes} bytes`, 413);
|
|
164
33
|
}
|
package/src/live-models.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import os from "node:os";
|
|
|
2
2
|
import { validateGithubToken } from "./auth.mjs";
|
|
3
3
|
import { AUTH_PROFILE_CODEX, readAuthProfileCredentials } from "./auth-profile.mjs";
|
|
4
4
|
import { buildHeaders, FALLBACK_VSCODE_VERSION, parseApiBase } from "./copilot.mjs";
|
|
5
|
+
import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "./upstream-body.mjs";
|
|
5
6
|
|
|
6
7
|
const DEFAULT_MODELS_TIMEOUT_MS = 10000;
|
|
7
8
|
const SUPPORTED_ENDPOINTS = [
|
|
@@ -59,14 +60,6 @@ function validationFailure(validation) {
|
|
|
59
60
|
return `GitHub Copilot authentication failed: ${validation?.reason || "unknown error"}${httpStatus}`;
|
|
60
61
|
}
|
|
61
62
|
|
|
62
|
-
async function responseText(response) {
|
|
63
|
-
try {
|
|
64
|
-
return await response.text();
|
|
65
|
-
} catch {
|
|
66
|
-
return "";
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
63
|
function readModelCredentials(home) {
|
|
71
64
|
let credentials;
|
|
72
65
|
try {
|
|
@@ -110,7 +103,11 @@ export async function fetchLiveCopilotModels({
|
|
|
110
103
|
redirect: "error",
|
|
111
104
|
signal: controller.signal,
|
|
112
105
|
});
|
|
113
|
-
const body = await
|
|
106
|
+
const body = await readBoundedResponseText(response, {
|
|
107
|
+
maxBytes: response.ok ? MAX_UPSTREAM_MODEL_CATALOG_BYTES : MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
108
|
+
label: "Copilot live model catalog",
|
|
109
|
+
signal: controller.signal,
|
|
110
|
+
});
|
|
114
111
|
if (!response.ok) {
|
|
115
112
|
const detail = safeText(body).slice(0, 240);
|
|
116
113
|
throw new Error(`Copilot models endpoint returned HTTP ${response.status}${detail ? `: ${detail}` : ""}`);
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -328,7 +328,7 @@ function storeCompletedResponse(reqContext, completed) {
|
|
|
328
328
|
|
|
329
329
|
function streamHeaders(resp) {
|
|
330
330
|
return {
|
|
331
|
-
...safeUpstreamResponseHeaders(resp.headers, { defaultContentType: "text/event-stream" }),
|
|
331
|
+
...safeUpstreamResponseHeaders(resp.headers, { defaultContentType: "text/event-stream", allowReasoningIncluded: resp.ok }),
|
|
332
332
|
"Cache-Control": "no-cache",
|
|
333
333
|
Connection: "keep-alive",
|
|
334
334
|
};
|
|
@@ -582,6 +582,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
582
582
|
markResponseTerminal("completed", { model: response.model || reqContext.body?.model, origin: "upstream_response" });
|
|
583
583
|
res.writeHead(resp.status, safeUpstreamResponseHeaders(resp.headers, {
|
|
584
584
|
contentType: "application/json",
|
|
585
|
+
allowReasoningIncluded: true,
|
|
585
586
|
}));
|
|
586
587
|
res.end(JSON.stringify(response));
|
|
587
588
|
return { successful: true, compacted: true };
|
|
@@ -636,6 +637,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
636
637
|
}
|
|
637
638
|
res.writeHead(resp.status, safeUpstreamResponseHeaders(resp.headers, {
|
|
638
639
|
contentType: "application/json",
|
|
640
|
+
allowReasoningIncluded: response.status !== "failed",
|
|
639
641
|
}));
|
|
640
642
|
res.end(data);
|
|
641
643
|
return { successful: response.status !== "failed" && response.status !== "incomplete", compacted: false };
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { httpError } from "./http-errors.mjs";
|
|
2
|
+
|
|
3
|
+
export const MAX_UPSTREAM_ERROR_BODY_BYTES = 1024 * 1024;
|
|
4
|
+
export const MAX_UPSTREAM_MODEL_CATALOG_BYTES = 8 * 1024 * 1024;
|
|
5
|
+
export const MAX_UPSTREAM_RETRY_DRAIN_BYTES = 64 * 1024;
|
|
6
|
+
|
|
7
|
+
function upstreamBodyTooLarge(label, maxBytes) {
|
|
8
|
+
const error = httpError(`${label} exceeds ${maxBytes} bytes`, 502);
|
|
9
|
+
error.code = "ccdx_upstream_response_too_large";
|
|
10
|
+
error.jsonBody = {
|
|
11
|
+
error: {
|
|
12
|
+
message: error.message,
|
|
13
|
+
type: "upstream_error",
|
|
14
|
+
code: error.code,
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
return error;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function unreadableUpstreamBody(label) {
|
|
21
|
+
const error = httpError(`${label} is not a readable web stream`, 502);
|
|
22
|
+
error.code = "ccdx_upstream_response_unreadable";
|
|
23
|
+
error.jsonBody = {
|
|
24
|
+
error: {
|
|
25
|
+
message: error.message,
|
|
26
|
+
type: "upstream_error",
|
|
27
|
+
code: error.code,
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
return error;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function cancelResponseBody(response) {
|
|
34
|
+
try { await response?.body?.cancel?.(); } catch {}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function responseAbortError(signal) {
|
|
38
|
+
if (signal?.reason instanceof Error) return signal.reason;
|
|
39
|
+
const error = new Error("The operation was aborted");
|
|
40
|
+
error.name = "AbortError";
|
|
41
|
+
return error;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function readResponseChunk(reader, signal) {
|
|
45
|
+
if (!signal) return reader.read();
|
|
46
|
+
if (signal.aborted) return Promise.reject(responseAbortError(signal));
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
let settled = false;
|
|
49
|
+
const finish = (callback, value) => {
|
|
50
|
+
if (settled) return;
|
|
51
|
+
settled = true;
|
|
52
|
+
signal.removeEventListener("abort", onAbort);
|
|
53
|
+
callback(value);
|
|
54
|
+
};
|
|
55
|
+
const onAbort = () => {
|
|
56
|
+
const error = responseAbortError(signal);
|
|
57
|
+
try { Promise.resolve(reader.cancel(error)).catch(() => {}); } catch {}
|
|
58
|
+
finish(reject, error);
|
|
59
|
+
};
|
|
60
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
61
|
+
reader.read().then(
|
|
62
|
+
(value) => finish(resolve, value),
|
|
63
|
+
(error) => finish(reject, error),
|
|
64
|
+
);
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function responseContentLength(response) {
|
|
69
|
+
const raw = response?.headers?.get?.("content-length")
|
|
70
|
+
?? response?.headers?.["content-length"]
|
|
71
|
+
?? response?.headers?.["Content-Length"];
|
|
72
|
+
const parsed = Number.parseInt(raw || "", 10);
|
|
73
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function readBoundedResponseBuffer(response, {
|
|
77
|
+
maxBytes,
|
|
78
|
+
label = "Upstream response body",
|
|
79
|
+
signal,
|
|
80
|
+
} = {}) {
|
|
81
|
+
const limit = Number.isFinite(maxBytes) && maxBytes >= 0 ? Math.floor(maxBytes) : 0;
|
|
82
|
+
if (signal?.aborted) {
|
|
83
|
+
cancelResponseBody(response);
|
|
84
|
+
throw responseAbortError(signal);
|
|
85
|
+
}
|
|
86
|
+
if (responseContentLength(response) > limit) {
|
|
87
|
+
await cancelResponseBody(response);
|
|
88
|
+
throw upstreamBodyTooLarge(label, limit);
|
|
89
|
+
}
|
|
90
|
+
if (!response?.body) {
|
|
91
|
+
if (typeof response?.text === "function") {
|
|
92
|
+
const buffer = Buffer.from(await response.text());
|
|
93
|
+
if (buffer.length > limit) throw upstreamBodyTooLarge(label, limit);
|
|
94
|
+
return buffer;
|
|
95
|
+
}
|
|
96
|
+
if ((responseContentLength(response) || 0) > 0) throw unreadableUpstreamBody(label);
|
|
97
|
+
return Buffer.alloc(0);
|
|
98
|
+
}
|
|
99
|
+
const reader = response?.body?.getReader?.();
|
|
100
|
+
if (!reader) throw unreadableUpstreamBody(label);
|
|
101
|
+
const chunks = [];
|
|
102
|
+
let total = 0;
|
|
103
|
+
try {
|
|
104
|
+
while (true) {
|
|
105
|
+
const { done, value } = await readResponseChunk(reader, signal);
|
|
106
|
+
if (done) break;
|
|
107
|
+
const chunk = Buffer.from(value);
|
|
108
|
+
total += chunk.length;
|
|
109
|
+
if (total > limit) {
|
|
110
|
+
await reader.cancel().catch(() => {});
|
|
111
|
+
throw upstreamBodyTooLarge(label, limit);
|
|
112
|
+
}
|
|
113
|
+
chunks.push(chunk);
|
|
114
|
+
}
|
|
115
|
+
return Buffer.concat(chunks, total);
|
|
116
|
+
} finally {
|
|
117
|
+
try {
|
|
118
|
+
reader.releaseLock();
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (!signal?.aborted) throw error;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function readBoundedResponseText(response, options) {
|
|
126
|
+
return new TextDecoder().decode(await readBoundedResponseBuffer(response, options));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function discardBoundedResponseBody(response, maxBytes = MAX_UPSTREAM_RETRY_DRAIN_BYTES) {
|
|
130
|
+
try {
|
|
131
|
+
await readBoundedResponseBuffer(response, { maxBytes, label: "Upstream retry response body" });
|
|
132
|
+
return true;
|
|
133
|
+
} catch {
|
|
134
|
+
await cancelResponseBody(response);
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
}
|
package/src/upstream-headers.mjs
CHANGED
|
@@ -41,12 +41,18 @@ function isSafeMetadataHeader(name) {
|
|
|
41
41
|
export function safeUpstreamResponseHeaders(headers, {
|
|
42
42
|
contentType,
|
|
43
43
|
defaultContentType,
|
|
44
|
+
allowReasoningIncluded = false,
|
|
44
45
|
} = {}) {
|
|
45
46
|
const out = {};
|
|
46
47
|
const resolvedContentType = contentType
|
|
47
48
|
?? headerValue(headers, "content-type")
|
|
48
49
|
?? defaultContentType;
|
|
49
50
|
if (resolvedContentType) out["Content-Type"] = resolvedContentType;
|
|
51
|
+
// Codex treats presence as true, even for a literal "false" value.
|
|
52
|
+
// Native Responses callers opt in; never invent a declaration for other routes.
|
|
53
|
+
if (allowReasoningIncluded && headerValue(headers, "x-reasoning-included")?.trim().toLowerCase() === "true") {
|
|
54
|
+
out["X-Reasoning-Included"] = "true";
|
|
55
|
+
}
|
|
50
56
|
|
|
51
57
|
if (headers && typeof headers[Symbol.iterator] === "function") {
|
|
52
58
|
for (const [rawName, value] of headers) {
|