codex-copilot-dx 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,8 +15,8 @@ ccdx
15
15
 
16
16
  Without Node.js, download and run the installer for your system:
17
17
 
18
- - macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.0/install.sh), then `sh install.sh`.
19
- - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.0/install.ps1), then `./install.ps1` under your current shell policy.
18
+ - macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.1/install.sh), then `sh install.sh`.
19
+ - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.1/install.ps1), then `./install.ps1` under your current shell policy.
20
20
 
21
21
  The installer reuses a compatible Node.js or installs a private, verified copy. Git and a compiler are not required. Complete platform packages include their dependencies. Company registry, proxy, certificate and shell policies are kept.
22
22
 
@@ -29,6 +29,7 @@ The Web UI opens at [http://127.0.0.1:2026](http://127.0.0.1:2026/). Run `ccdx w
29
29
  1. **Model sources:** connect an account or API, read its models and choose allowed apps.
30
30
  2. **Codex / Claude:** choose visible models, set a default and save. Preview and synchronize client settings when needed.
31
31
  3. **Overview / Requests:** check configuration, activity and errors.
32
+ 4. **Usage → Context:** inspect reported input, model windows and observed compactions from this run.
32
33
 
33
34
  For a custom API, enter its HTTPS address and key, then choose **Save & read models**. Select the models and interfaces it provides. Codex uses Responses; Claude uses Messages. Both share port 2026.
34
35
 
@@ -931,6 +931,8 @@ The connection snapshot's read-only source_impacts reports actual selected consu
931
931
 
932
932
  Unknown client capability adapters preserve existing shared settings and report their limitation. The presentation schema and protocol capability evidence do not share an enable gate. HTTP-200 error envelopes and native SSE errors feed the existing bounded diagnostics as model.error; transport bytes and retry policies remain unchanged.
933
933
 
934
+ Table disclosure metadata blocks use inline-size containment: their natural height remains, while long IDs, timestamps and diagnostics do not change the table columns' intrinsic widths. Rows with details stay top-aligned so their time/source/model text remains at its original vertical position. This shared rule covers request metadata, checks and nested capability details without adding fixed empty column space. The API capability row uses the same containment boundary. Global browser replay checks each disclosure's trigger/text x coordinate, peer-row text y position, column widths and horizontal scroll at opening, mid-animation, open and closed states.
935
+
934
936
  `dashboard/disclosure.js` is optional progressive enhancement of native details/summary. It uses cancellable opacity/transform animations, CSS chevrons independent of translated DOM text, and no polling/height animation. Reduced motion and hidden documents finish immediately. A resource integration test covers every script/style referenced by the shell. Flow regression measures layout reads and DOM identity under elapsed-only updates; existing geometry caches, list limits and visibility gates remain the performance mechanism.
935
937
 
936
938
 
@@ -988,3 +990,11 @@ Source-catalog tables keep fixed column geometry while native disclosures expand
988
990
  A full snapshot keeps a local map of compiled client plans, including reuse during source-impact projection. Public data remains cloned and contains the same revisions/route identifiers. No persistent or global cache is added. `updateAccessSettings` retains strict validation, the lock and original-byte v1 backup, then skips an atomic rewrite only when serialized bytes already match. Skipping a file write does not skip an explicit control action or client sync.
989
991
 
990
992
  The CLI keeps only command/version/status fundamentals before its early command dispatch. Existing tool implementations are imported in their branches; startup composition loads afterward in its previous dependency order. Native account stores, source/key identity, model projections and image/prediction behavior are unchanged. The repository-only `docs/STATE_REFACTOR_PLAN.md` records included boundaries, local measurements and deferred work.
993
+
994
+ ### Context observations
995
+
996
+ `context-metrics.mjs` owns a bounded, process-local numeric projection. After ordinary provider/conversation validation, request handlers observe only bounded explicit session/subagent metadata. A process-salted HMAC includes the pinned source profile; raw IDs, prompts and credentials never enter the view. Missing identity never falls back to prompt matching. The projection neither calls nor changes the conversation source guard.
997
+
998
+ `stream-performance.mjs` feeds one terminal record to this projection, separately from its unchanged ordinary status context shape. Existing Responses/Messages usage observations supply reported input and cached input; declared window observations retain unknowns. Compaction calls are separate from regular-input series. Per observer: 64 series, 64 input points and 16 compact events per series, plus 20 unassigned requests. Snapshot sorting detects overlapping requests outside the request path; it does not infer a linear branch from parallel work. No persistence or background task is introduced.
999
+
1000
+ The optional read-only `/_ccdx/ui/context` endpoint reuses loopback/Host/dashboard-header checks and rejects a conflicting Origin. It combines independent Responses and Messages observer snapshots only when requested. `context.js` owns the Usage subview and consumes the existing refresh controller; hidden views issue no context reads. Ordinary status and TUI snapshots do not serialize the retained series. Existing usage/history, auth/config ownership, prediction and image paths retain their behavior.
package/docs/README.md CHANGED
@@ -4,6 +4,7 @@
4
4
  - [Reference](REFERENCE.md): commands, settings, diagnostics, images and native suggestions.
5
5
  - [Architecture](ARCHITECTURE.md): module ownership and runtime boundaries.
6
6
  - [State orchestration](STATE_REFACTOR_PLAN.md): implemented boundaries, preservation checks and deferred work.
7
+ - [1.3.1](RELEASE_1.3.1.md): bounded context observations and anchored WebUI details.
7
8
  - [1.3.0](RELEASE_1.3.0.md): scope, compatibility changes and verification.
8
9
 
9
10
  CLI help describes the installed package. The running service can be an older version until its next normal restart.
package/docs/REFERENCE.md CHANGED
@@ -52,13 +52,23 @@ For scripts, source access accepts `--apps codex,claude-app` with `--edit`; edit
52
52
 
53
53
  An app model file contains `deployments: [{"source":"github","model":"<model-id>"}]`, with optional `default_model` and `auto_sync`. An explicit empty array clears the default and pauses access. A file without `deployments` is rejected. Unavailable saved selections remain visible until the user changes them.
54
54
 
55
+ ## Context observations
56
+
57
+ **Usage → Context** shows reported input, declared model windows, cache reuse and observed gateway compactions from this process. It leaves missing values unknown. Input share is reported input divided by the declared window; it is not a measurement of every item currently held by the client. Reused input still occupies context.
58
+
59
+ Only explicit, bounded session IDs can link requests. Local display identifiers replace native IDs and titles; account/profile, app, source, model and declared subagent identities remain separate. Unidentified requests appear individually. Concurrent observations are points rather than a connected conversation curve. Compaction records cover observed Responses compact calls, not every client-side summary, and their elapsed time includes the whole gateway request. No before/after size is invented from summary output tokens.
60
+
61
+ Each protocol observer retains at most 64 series of 64 request points and 16 compaction records, plus 20 unidentified requests. These numeric observations are memory-only and reset on restart. The page reads them on demand through the existing dashboard refresh controller; ordinary status payloads do not include them. There is no prompt storage, text tokenization, transcript scan, extra provider request, content breakdown or compression control.
62
+
55
63
  ## Sources and client access
56
64
 
65
+ Clicking the Web UI logo plays one brief rotation and keeps its Overview navigation. System reduced-motion preferences disable this effect. The header uses a link icon for the local connection; the request-flow total uses a circled ellipsis for active requests.
66
+
57
67
  Upgrades retain saved account bindings, source IDs, key references, model choices/defaults and capability overrides. Native account stores keep their existing owner; bookkeeping does not request another login. Unchanged client settings need no repeat save or synchronization. Explicit user changes and ordinary credential renewal keep their current behavior.
58
68
 
59
69
  Sources own accounts, API addresses, keys and model capabilities. Apps own visible models and defaults. Allowing an app to use a source does not select all its models. Selecting no models pauses that app. Settings owns service preferences and appearance, not model routing. An unchanged graph save keeps the file bytes and modification time; explicit sync, refresh and credential actions still run. Existing v1 configuration is backed up byte-for-byte before its first v2 write; reads do not migrate files.
60
70
 
61
- In the Web UI, **Model sources → Add API** saves the source and immediately reads its catalog. A failed read keeps the saved source and editor. Select supported models and their declared interfaces before assigning them to apps. Catalog details expand without shifting columns. API-editor capability details open below their model row; manual overrides are separate from reported metadata.
71
+ In the Web UI, **Model sources → Add API** saves the source and immediately reads its catalog. A failed read keeps the saved source and editor. Select supported models and their declared interfaces before assigning them to apps. Table details expand downward without shifting their controls or redistributing columns, including request metadata and check results. API-editor capability details open below their model row; manual overrides are separate from reported metadata.
62
72
 
63
73
  Manual APIs require HTTPS. Codex requires Responses; Claude requires Messages. CCDX does not invent an interface, token-count result, reasoning level or web-search capability absent from the source declaration. Returned maker/name metadata is displayed separately from the source name. Model IDs are not used to guess a maker.
64
74
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -175,6 +175,11 @@ export function createAdapterHandler(options = {}) {
175
175
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
176
176
  const httpErrors = createHttpFailureDiagnostics();
177
177
  const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
178
+ contextSnapshotFn: () => {
179
+ const snapshots = [streamPerformanceMetrics.contextSnapshot?.(), options.providerRuntime?.claudePerformance?.contextSnapshot?.()];
180
+ const combine = name => snapshots.flatMap((data, index) => (data?.[name] || []).map(entry => ({ ...entry, id: `${index}-${entry.id}` })));
181
+ return { source: "run_context", sessions: combine("sessions"), unassigned: combine("unassigned") };
182
+ },
178
183
  credentialsChanged: options.dashboardOptions?.credentialsChanged || (() => codexClient.invalidateCredentials?.()),
179
184
  ...(options.providerRuntime ? { providerCatalogFn: input => options.providerRuntime.dashboardCatalog(input),
180
185
  providerStateFn: () => options.providerRuntime.dashboardProviders(),
@@ -15,6 +15,7 @@ import { redactDiagnosticText } from "./diagnostic-text.mjs";
15
15
  import { decodedBodyLimitPreference } from "./user-settings.mjs";
16
16
  import { operationErrorDetails, transportErrorDetails } from "./operation-error.mjs";
17
17
  import { requestApplication } from "./request-application.mjs";
18
+ import { observeContextSession } from "./context-metrics.mjs";
18
19
 
19
20
  function send(res, code, value) {
20
21
  if (res.destroyed || res.writableEnded) return;
@@ -155,6 +156,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
155
156
  if (!countTokens) markRequestObservation({ max_output_tokens_requested: body.max_tokens });
156
157
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
157
158
  conversation = validateConversation?.(body, req.headers, selectedProvider);
159
+ if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
158
160
  terminalOrigin = "transport";
159
161
  const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
160
162
  onCountObservation(value) {
@@ -254,7 +256,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
254
256
  stats.active--;stats[outcome]++;
255
257
  const usageRecord = buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json",
256
258
  client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude", provider: selectedProvider.id });
257
- markRequestObservation({ input_tokens: usageRecord?.usage?.input_tokens, output_tokens: usageRecord?.usage?.output_tokens });
259
+ markRequestObservation({ input_tokens: usageRecord?.usage?.input_tokens, output_tokens: usageRecord?.usage?.output_tokens,
260
+ cached_input_tokens: usageRecord?.usage?.cached_input_tokens });
258
261
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
259
262
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, stopReason, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
260
263
  tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode, rejectionReason });
@@ -0,0 +1,63 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
2
+ import { currentRequestContext } from "./request-context.mjs";
3
+
4
+ const salt = randomBytes(32);
5
+ const bounded = value => typeof value === "string" && value.length > 0 && value.length <= 512 && !/[\u0000-\u001f\u007f]/.test(value);
6
+ const count = value => Number.isSafeInteger(value) && value >= 0 ? value : null;
7
+
8
+ // Presentation-only correlation. Never infer identity from prompts or retain an ID.
9
+ export function observeContextSession(body, headers = {}, provider, protocol = "responses") {
10
+ const tracker = currentRequestContext()?.streamPerformance;
11
+ if (!tracker?.observeSession) return;
12
+ let session = headers.session_id || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
13
+ if (!session && typeof body?.metadata?.user_id === "string" && body.metadata.user_id.length <= 2048) {
14
+ try { session = JSON.parse(body.metadata.user_id)?.session_id; }
15
+ catch { session = /(?:^|_)session_([\w-]{8,128})$/.exec(body.metadata.user_id)?.[1]; }
16
+ }
17
+ if (!bounded(session)) return;
18
+ try {
19
+ const profile = provider?.profileId?.(protocol);
20
+ if (!bounded(profile)) return;
21
+ const agent = headers["x-claude-code-agent-id"];
22
+ const key = createHmac("sha256", salt).update(`${profile}\0${session}\0${bounded(agent) ? agent : ""}`).digest("hex");
23
+ tracker.observeSession(key);
24
+ } catch { /* Optional metadata cannot change request admission or routing. */ }
25
+ }
26
+
27
+ export function createContextMetrics() {
28
+ const sessions = new Map(), unassigned = [];
29
+ let sequence = 0;
30
+ return {
31
+ record({ session, application, provider, model, route, at, started, finished, request_id, outcome, context, cached_input_tokens }) {
32
+ const input = count(context.input_tokens), cached = count(cached_input_tokens);
33
+ const point = { at, order: started, request_id, outcome, input_tokens: input,
34
+ context_window_tokens: count(context.context_window_tokens) || null,
35
+ cached_input_tokens: input !== null && cached !== null && cached <= input ? cached : null,
36
+ elapsed_ms: Math.max(0, finished - started), finished };
37
+ const compact = route === "responses_compact";
38
+ if (!session) {
39
+ unassigned.push({ id: `request-${++sequence}`, application, provider, model, ...point, compact });
40
+ if (unassigned.length > 20) unassigned.shift();
41
+ return;
42
+ }
43
+ const key = `${application}\0${provider}\0${model}\0${session}`;
44
+ let entry = sessions.get(key);
45
+ if (!entry) entry = { id: `session-${++sequence}`, application, provider, model, points: [], compactions: [] };
46
+ sessions.delete(key);sessions.set(key, entry);
47
+ const list = compact ? entry.compactions : entry.points;
48
+ list.push(point);if (list.length > (compact ? 16 : 64)) list.shift();
49
+ if (sessions.size > 64) sessions.delete(sessions.keys().next().value);
50
+ },
51
+ snapshot() {
52
+ const project = entry => {
53
+ const points = entry.points.map(point => ({ ...point })).sort((a, b) => a.order - b.order);
54
+ let end = -Infinity, concurrent = false;
55
+ for (const point of points) { if (point.order < end) concurrent = true;end = Math.max(end, point.finished); }
56
+ return { ...entry, points, concurrent, compactions: entry.compactions.map(point => ({ ...point })).sort((a, b) => a.order - b.order) };
57
+ };
58
+ return { source: "run_context", sessions: [...sessions.values()].reverse().map(project),
59
+ unassigned: unassigned.slice().reverse().map(point => ({ ...point })),
60
+ limits: { sessions: 64, points: 64, compactions: 16, unassigned: 20 } };
61
+ },
62
+ };
63
+ }
@@ -59,6 +59,7 @@
59
59
  if (settingsViews.includes(next)) void loadSettings();
60
60
  if (next === "models") { void refreshCatalog();void dashboardRefresh.refresh("auth"); }
61
61
  if (next === "usage") { void dashboardRefresh.refresh("usage");usageView.revealChart(); } else usageView.stopMotion();
62
+ globalThis.ccdxContextView?.routeChanged();
62
63
  if (next === "requests") renderContext();
63
64
  if (next === "system") { void dashboardRefresh.refresh("animation");void dashboardRefresh.refresh("updates"); }
64
65
  preferences?.render();
@@ -0,0 +1,124 @@
1
+ (() => {
2
+ const root = document.getElementById("usage-context-pane");
3
+ if (!root) return;
4
+ const el = id => document.getElementById(id), ns = "http://www.w3.org/2000/svg";
5
+ const language = globalThis.ccdxLanguage;
6
+ const label = (node, key, values) => language.set(node, key, values);
7
+ const valid = value => Number.isSafeInteger(value) && value >= 0;
8
+ const number = value => valid(value) ? value.toLocaleString() : "—";
9
+ const ratio = (input, total) => valid(input) && valid(total) && total > 0 ? `${(input / total * 100).toFixed(1)}%` : "—";
10
+ const visible = () => document.visibilityState === "visible" && !root.closest("[hidden]");
11
+ let entries = [], selected = null, known = false;
12
+ const name = entry => language.format(entry.identified ? "context_conversation" : "context_request", { id: entry.id.split("-").at(-1) });
13
+ const app = entry => language.format(`flow_app_${entry.application}`);
14
+ const latest = entry => entry.points.at(-1) || entry.compactions.at(-1) || {};
15
+ const time = value => globalThis.ccdxTime?.format(value) || "—";
16
+ function cell(row, value) { const cell = document.createElement("td");cell.textContent = value;row.append(cell);return cell; }
17
+ function chart(entry) {
18
+ const host = el("context-history-chart");host.replaceChildren();
19
+ const points = entry.points;
20
+ if (!points.some(point => valid(point.input_tokens))) { label(host, "context_no_input");return; }
21
+ if (!entry.identified) { label(host, "context_unassigned");return; }
22
+ const width = host.clientWidth;if (!width) return;
23
+ const height = 210, left = 64, right = 12, top = 25, bottom = 35;
24
+ const measured = Math.max(...points.map(point => valid(point.input_tokens) ? point.input_tokens : 0), 1);
25
+ const maximum = Math.max(measured, latest(entry).context_window_tokens || 0);
26
+ const x = index => left + (width - left - right) * index / Math.max(1, points.length - 1);
27
+ const y = value => top + (height - top - bottom) * (1 - value / maximum);
28
+ const svg = document.createElementNS(ns, "svg");svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
29
+ svg.setAttribute("role", "img");svg.setAttribute("aria-label", language.format("context_history"));host.append(svg);
30
+ const shape = (tag, attributes, text) => {
31
+ const node = document.createElementNS(ns, tag);
32
+ for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value);
33
+ if (text !== undefined) node.textContent = text;svg.append(node);return node;
34
+ };
35
+ for (let index = 0; index <= 2; index++) {
36
+ const value = maximum * index / 2, py = y(value);
37
+ shape("line", { x1: left, x2: width - right, y1: py, y2: py, class: "context-grid" });
38
+ shape("text", { x: left - 8, y: py + 4, "text-anchor": "end" }, Math.round(value).toLocaleString());
39
+ }
40
+ shape("text", { x: left, y: 12 }, "tokens");
41
+ let path = "", continuing = false;
42
+ points.forEach((point, index) => {
43
+ if (!valid(point.input_tokens)) { continuing = false;return; }
44
+ path += `${continuing ? "L" : "M"}${x(index)} ${y(point.input_tokens)} `;continuing = true;
45
+ const dot = shape("circle", { cx: x(index), cy: y(point.input_tokens), r: 3, class: "context-point" });
46
+ const title = document.createElementNS(ns, "title");title.textContent = `${time(point.at)} · ${number(point.input_tokens)} tokens`;dot.append(title);
47
+ });
48
+ if (!entry.concurrent) shape("path", { d: path, class: "context-line" });
49
+ for (const index of new Set([0, Math.floor((points.length - 1) / 2), points.length - 1])) {
50
+ shape("text", { x: x(index), y: height - 14, "text-anchor": index === 0 ? "start" : "end" }, String(index + 1));
51
+ }
52
+ for (const compact of entry.compactions) {
53
+ const index = points.findIndex(point => point.order >= compact.order);
54
+ if (index < 0 || compact.outcome !== "completed") continue;
55
+ const px = x(index);shape("line", { x1: px, x2: px, y1: top, y2: height - bottom, class: "context-compact" });
56
+ shape("text", { x: Math.min(width - right - 35, Math.max(left + 35, px)), y: top - 8, "text-anchor": "middle" }, language.format("context_compact_event"));
57
+ }
58
+ }
59
+ function render() {
60
+ if (!visible()) return;
61
+ const body = el("context-sessions");body.replaceChildren();
62
+ for (const entry of entries) {
63
+ const row = document.createElement("tr"), button = document.createElement("button");button.type = "button";
64
+ button.className = "context-session";label(button, entry.identified ? "context_conversation" : "context_request", { id: entry.id.split("-").at(-1) });
65
+ button.setAttribute("aria-pressed", String(selected === entry.id));
66
+ button.addEventListener("click", () => { selected = entry.id;render(); });cell(row, "").append(button);
67
+ cell(row, app(entry));cell(row, entry.model || "—");const point = latest(entry);
68
+ cell(row, ratio(point.input_tokens, point.context_window_tokens));body.append(row);
69
+ }
70
+ const entry = entries.find(entry => entry.id === selected);
71
+ el("context-selection").hidden = !entry;
72
+ if (!entry) {
73
+ if (known) { const row = document.createElement("tr"), empty = cell(row, language.format("context_empty"));empty.colSpan = 4;body.append(row); }
74
+ return;
75
+ }
76
+ label(el("context-selection-title"), entry.identified ? "context_conversation" : "context_request", { id: entry.id.split("-").at(-1) });
77
+ el("context-selection-source").textContent = entry.provider === "github" ? "GitHub Copilot" : entry.provider === "m365" ? "Microsoft 365" : globalThis.ccdxConnectionNames?.[entry.provider] || language.format("flow_source_unknown");
78
+ const point = latest(entry);
79
+ el("context-latest-input").textContent = number(point.input_tokens);
80
+ el("context-window").textContent = valid(point.context_window_tokens) && point.context_window_tokens > 0 ? number(point.context_window_tokens) : language.format("context_unknown_window");
81
+ el("context-share").textContent = ratio(point.input_tokens, point.context_window_tokens);
82
+ el("context-reuse").textContent = ratio(point.cached_input_tokens, point.input_tokens);
83
+ label(el("context-history-note"), entry.concurrent ? "context_concurrent" : "context_request_order");chart(entry);
84
+ const compactions = el("context-compactions");compactions.replaceChildren();
85
+ for (const compact of entry.compactions) {
86
+ const row = document.createElement("tr");cell(row, time(compact.at));const result = cell(row, "");
87
+ label(result, ["completed", "incomplete", "failed", "cancelled"].includes(compact.outcome) ? compact.outcome : "unknown");
88
+ cell(row, Number.isFinite(compact.elapsed_ms) ? `${(compact.elapsed_ms / 1000).toFixed(1)} s` : "—");compactions.append(row);
89
+ }
90
+ if (!entry.compactions.length) { const row = document.createElement("tr"), empty = cell(row, language.format("context_no_compactions"));empty.colSpan = 3;compactions.append(row); }
91
+ }
92
+ const tokensTab = el("usage-tokens-tab"), contextTab = el("usage-context-tab");
93
+ function select(context) {
94
+ root.hidden = !context;el("usage-tokens-pane").hidden = context;
95
+ tokensTab.setAttribute("aria-selected", String(!context));contextTab.setAttribute("aria-selected", String(context));
96
+ tokensTab.tabIndex = context ? -1 : 0;contextTab.tabIndex = context ? 0 : -1;
97
+ render();window.dispatchEvent(new CustomEvent("ccdx:context-view"));
98
+ }
99
+ tokensTab.addEventListener("click", () => select(false));contextTab.addEventListener("click", () => select(true));
100
+ for (const tab of [tokensTab, contextTab]) tab.addEventListener("keydown", event => {
101
+ if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
102
+ event.preventDefault();const context = event.key === "Home" ? false : event.key === "End" ? true : root.hidden;
103
+ select(context);(context ? contextTab : tokensTab).focus();
104
+ });
105
+ contextTab.tabIndex = -1;
106
+ new ResizeObserver(() => { const entry = entries.find(entry => entry.id === selected);if (entry && visible()) chart(entry); }).observe(el("context-history-chart"));
107
+ new MutationObserver(render).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
108
+ globalThis.ccdxContextView = {
109
+ visible,
110
+ apply(data) {
111
+ if (!Array.isArray(data.sessions) || !Array.isArray(data.unassigned)) throw Error("Invalid context snapshot");
112
+ entries = [...data.sessions.slice(0, 128).map(entry => ({ ...entry, identified: true })),
113
+ ...data.unassigned.slice(0, 40).map(point => ({ ...point, identified: false, concurrent: false,
114
+ points: point.compact ? [] : [point], compactions: point.compact ? [point] : [] }))];
115
+ entries.sort((a, b) => Date.parse(latest(b).at) - Date.parse(latest(a).at));
116
+ if (!entries.some(entry => entry.id === selected)) selected = entries[0]?.id || null;
117
+ known = true;render();
118
+ },
119
+ state(state) {
120
+ label(el("context-view-state"), state.error ? "context_read_failed" : state.pending ? "reading" : "context_scope");
121
+ },
122
+ routeChanged() { render();if (visible()) window.dispatchEvent(new CustomEvent("ccdx:context-view")); },
123
+ };
124
+ })();
@@ -114,7 +114,7 @@
114
114
  root.dataset.state = !fresh ? "unknown" : total ? "active" : "idle";
115
115
  const state = el("flow-state");
116
116
  if (fresh && total === 0) label(state, "flow_idle");
117
- else globalThis.ccdxIcons?.set(state, !fresh ? "flow_status_unknown" : "flow_total", !fresh ? "unavailable" : "running", { count: total });
117
+ else globalThis.ccdxIcons?.set(state, !fresh ? "flow_status_unknown" : "flow_total", !fresh ? "unavailable" : "progress", { count: total });
118
118
  label(el("flow-caption"), !fresh ? "flow_status_unknown" : omitted ? "flow_omitted" : selected ? "flow_related_count" : total ? "flow_group_scope" : "flow_no_active",
119
119
  { count: rows.filter(related).length, omitted, apps: apps.length, models: allModels.length });
120
120
  el("flow-clear").hidden = !selected;
@@ -1,11 +1,15 @@
1
1
  (() => {
2
2
  const shapes = { ok: ["path", { d: "m8 12 2.5 2.5L16 9" }], running: ["path", { d: "m10 8 6 4-6 4Z" }],
3
+ connected: ["path", { d: "M9 17H7a5 5 0 0 1 0-10h2m6 0h2a5 5 0 0 1 0 10h-2M8 12h8" }],
4
+ progress: ["path", { d: "M8 12h.01M12 12h.01M16 12h.01" }],
3
5
  warning: ["path", { d: "M12 7.5v5m0 3.5h.01" }], unavailable: ["path", { d: "M8 12h8" }] };
4
6
  function icon(kind = "unknown") {
5
7
  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
6
8
  for (const [key, value] of Object.entries({ viewBox: "0 0 24 24", "aria-hidden": "true", focusable: "false", class: "state-icon" })) svg.setAttribute(key, value);
7
- const circle = document.createElementNS(svg.namespaceURI, "circle");
8
- circle.setAttribute("cx", "12");circle.setAttribute("cy", "12");circle.setAttribute("r", "9");svg.append(circle);
9
+ if (kind !== "connected") {
10
+ const circle = document.createElementNS(svg.namespaceURI, "circle");
11
+ circle.setAttribute("cx", "12");circle.setAttribute("cy", "12");circle.setAttribute("r", "9");svg.append(circle);
12
+ }
9
13
  if (shapes[kind]) { const [tag, attributes] = shapes[kind], shape = document.createElementNS(svg.namespaceURI, tag);
10
14
  for (const [key, value] of Object.entries(attributes)) shape.setAttribute(key, value);svg.append(shape); }
11
15
  return svg;
@@ -17,6 +17,7 @@
17
17
  <script src="/activity.js" defer></script>
18
18
  <script src="/flow.js" defer></script>
19
19
  <script src="/usage.js" defer></script>
20
+ <script src="/context.js" defer></script>
20
21
  <script src="/updates.js" defer></script>
21
22
  <script src="/animation.js" defer></script>
22
23
  <script src="/ui.js" defer></script>
@@ -286,6 +287,8 @@
286
287
  </details>
287
288
  </div>
288
289
  <div data-view="usage" hidden>
290
+ <div class="context-tabs" role="tablist" aria-label="Usage view" data-i18n-label="context_tabs"><button type="button" id="usage-tokens-tab" role="tab" aria-selected="true" aria-controls="usage-tokens-pane" data-i18n="context_tokens">Tokens</button><button type="button" id="usage-context-tab" role="tab" aria-selected="false" aria-controls="usage-context-pane" data-i18n="context_title">Context</button></div>
291
+ <div id="usage-tokens-pane" role="tabpanel" aria-labelledby="usage-tokens-tab">
289
292
  <div class="section-actions usage-source-controls"><label><span data-i18n="source_entire_page">Source / entire page</span><select id="usage-provider"><option value="" data-i18n="all_providers">All providers</option></select></label><button id="refresh-usage" type="button" data-i18n="refresh_usage">Refresh usage</button></div>
290
293
 
291
294
  <details id="usage-analytics" class="panel dashboard-section analytics-section">
@@ -314,6 +317,15 @@
314
317
 
315
318
  </details>
316
319
  </div>
320
+ <div id="usage-context-pane" role="tabpanel" aria-labelledby="usage-context-tab" hidden>
321
+ <section class="panel dashboard-section"><h2 data-i18n="context_activity">Conversations &amp; requests</h2><p id="context-view-state" class="table-note" role="status"></p><div class="table-wrap"><table class="context-sessions"><thead><tr><th data-i18n="context_item">Conversation / request</th><th data-i18n="client">App</th><th data-i18n="model">Model</th><th data-i18n="context_share">Input share</th></tr></thead><tbody id="context-sessions"></tbody></table></div></section>
322
+ <section id="context-selection" class="panel dashboard-section" aria-labelledby="context-selection-title" hidden><div class="panel-heading"><h2 id="context-selection-title"></h2><span id="context-selection-source"></span></div>
323
+ <dl class="context-metrics"><div><dt data-i18n="context_latest_input">Latest input</dt><dd id="context-latest-input">—</dd></div><div><dt data-i18n="model_window">Model window</dt><dd id="context-window">—</dd></div><div><dt data-i18n="context_share">Input share</dt><dd id="context-share">—</dd></div><div><dt data-i18n="context_reuse">Cache reuse</dt><dd id="context-reuse">—</dd></div></dl>
324
+ <div class="panel-heading"><h3 data-i18n="context_history">Input history</h3><span id="context-history-note"></span></div><div id="context-history-chart" class="context-history-chart"></div>
325
+ <details class="tool-details" open><summary data-i18n="context_compactions">Compactions</summary><div class="table-wrap"><table><thead><tr><th data-i18n="time">Time</th><th data-i18n="outcome">Result</th><th data-i18n="context_elapsed">Elapsed</th></tr></thead><tbody id="context-compactions"></tbody></table></div></details>
326
+ </section>
327
+ </div>
328
+ </div>
317
329
  <div data-view="requests" hidden>
318
330
  <section class="panel dashboard-section" id="request-flow" data-state="unknown">
319
331
  <div class="panel-heading"><h2 data-i18n="request_flow">REQUEST FLOW</h2><span id="flow-state" role="status" aria-live="polite" data-i18n="flow_status_unknown">Status unavailable</span></div>
@@ -1,5 +1,28 @@
1
1
  (() => {
2
2
  const translations = {
3
+ "context_tabs": ["Usage view", "统计视图"],
4
+ "context_unknown_window": ["Unknown", "未知"],
5
+ "context_compact_event": ["Compaction", "压缩"],
6
+ "context_tokens": ["Tokens", "用量"],
7
+ "context_title": ["Context", "上下文"],
8
+ "context_activity": ["Conversations & requests", "会话与请求"],
9
+ "context_item": ["Conversation / request", "会话/请求"],
10
+ "context_share": ["Input share", "输入占比"],
11
+ "context_latest_input": ["Latest input", "最近输入"],
12
+ "context_reuse": ["Cache reuse", "缓存复用"],
13
+ "context_history": ["Input history", "输入变化"],
14
+ "context_compactions": ["Gateway compactions", "网关压缩"],
15
+ "context_elapsed": ["Elapsed", "耗时"],
16
+ "context_conversation": ["Conversation {id}", "会话 {id}"],
17
+ "context_request": ["Request {id}", "请求 {id}"],
18
+ "context_empty": ["No records in this run.", "本次运行暂无记录。"],
19
+ "context_no_input": ["Input usage unavailable.", "未获得输入用量。"],
20
+ "context_unassigned": ["No conversation ID; shown as one request.", "未识别会话,仅显示此请求。"],
21
+ "context_no_compactions": ["No observed compactions.", "未观测到压缩。"],
22
+ "context_concurrent": ["Concurrent requests", "并发请求"],
23
+ "context_request_order": ["Request order", "请求顺序"],
24
+ "context_scope": ["This run · Reported metadata", "本次运行 · 上报数据"],
25
+ "context_read_failed": ["Read failed. Previous data kept.", "读取失败,保留上次数据。"],
3
26
  "model_id": ["Model ID", "模型 ID"],
4
27
  "catalog_scope": ["Catalog scope", "目录说明"],
5
28
  "issue_brief": ["{cause} · {model} · {time}", "{cause} · {model} · {time}"],
@@ -133,6 +133,10 @@ details > summary::-webkit-details-marker { display: none; }
133
133
  details > summary::marker { content: ""; }
134
134
  details > summary::before { content: ""; width: 14px; height: 14px; align-self: center; background: currentColor; mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='m6 9 6 6 6-6' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat; transition: transform 160ms cubic-bezier(.25,1,.5,1); }
135
135
  details[open]:not([data-disclosure-closing]) > summary::before { transform: rotate(180deg); }
136
+ /* Expanded metadata contributes height, not a new preferred table-column width. */
137
+ tr:has(> td details) > td { vertical-align: top; }
138
+ td details { white-space: normal; }
139
+ td details > :is(dl, p, pre, div, ul, ol), #connection-model-detail { contain: inline-size; min-inline-size: 0; overflow-wrap: anywhere; }
136
140
  @media (prefers-reduced-motion: reduce) { details > summary::before { transition: none; } }
137
141
  .client-sync-state { margin: 12px 0; font-size: 12px; color: var(--text); }
138
142
  .source-impact { min-width: 0; }
@@ -451,7 +455,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
451
455
 
452
456
  .state-label { display:inline-flex; align-items:center; gap:8px; max-width:100%; vertical-align:middle; white-space:normal; }
453
457
  .state-icon { width:16px; height:16px; flex:none; fill:none; stroke:currentColor; stroke-width:1.6; stroke-linecap:round; stroke-linejoin:round; }
454
- .state-label.state-ok, .state-label.state-running { color:var(--accent); }
458
+ .state-label.state-ok, .state-label.state-running, .state-label.state-connected, .state-label.state-progress { color:var(--accent); }
455
459
  .state-label.state-warning { color:var(--bad); }
456
460
  .state-label.state-unavailable, .state-label.state-unknown { color:var(--muted); }
457
461
  .state-label > span { color:inherit; white-space:normal; }
@@ -628,3 +632,25 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
628
632
  .preferences-dialog dt { color:var(--muted); }.preferences-dialog dd { margin:0; }
629
633
  .preferences-dialog .section-actions { justify-content:flex-end; margin-top:24px; }
630
634
  @media(max-width:640px) { .preferences-row { gap:14px; flex-wrap:wrap; }.preferences-row > div:first-child { flex:1; min-width:150px; }.preferences-dialog { padding:20px; }.preferences-dialog dl > div { grid-template-columns:1fr; gap:3px; } }
635
+
636
+ /* Context observes requests without changing client behavior. */
637
+ .context-tabs { display:flex;gap:8px;margin-bottom:18px; }
638
+ .context-tabs button { min-width:80px;text-align:center; }
639
+ .context-tabs button[aria-selected="true"], .context-session[aria-pressed="true"] { color:var(--surface);background:var(--accent);border-color:var(--accent); }
640
+ .context-sessions { table-layout:fixed;min-width:420px; }
641
+ .context-sessions th:first-child { width:27%; }
642
+ .context-sessions th:nth-child(2) { width:23%; }
643
+ .context-sessions th:nth-child(3) { width:32%; }
644
+ .context-sessions th:last-child, .context-sessions td:last-child { text-align:right; }
645
+ .context-session { text-transform:none;max-width:100%;overflow-wrap:anywhere; }
646
+ .context-metrics { display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin:26px 0; }
647
+ .context-metrics dt { color:var(--muted);font-size:11px; }
648
+ .context-metrics dd { margin:8px 0 0;font-size:23px;font-variant-numeric:tabular-nums; }
649
+ .context-history-chart { min-height:210px;color:var(--muted);margin-top:14px; }
650
+ .context-history-chart svg { width:100%;height:210px;display:block; }
651
+ .context-history-chart text { font-size:11px;fill:var(--muted); }
652
+ .context-grid { stroke:var(--border);stroke-width:1; }
653
+ .context-line { fill:none;stroke:var(--accent);stroke-width:1.6; }
654
+ .context-point { fill:var(--accent); }
655
+ .context-compact { stroke:var(--muted);stroke-width:1;stroke-dasharray:3 5; }
656
+ @media (max-width:640px) { .context-metrics { grid-template-columns:repeat(2,minmax(0,1fr));gap:18px; } .context-metrics dd { font-size:21px; } }
@@ -27,7 +27,7 @@ const statusResourceKey = () => ["codex", "claude", "models", "usage", "requests
27
27
  const refreshStatus = () => dashboardRefresh.refresh(statusResourceKey(), { force: true });
28
28
  const refresh = refreshStatus;
29
29
 
30
- function animateRefresh() {
30
+ function animateLogo() {
31
31
  const icon = element("status-icon");
32
32
  if (!icon || reducedMotion.matches || !icon.animate) return;
33
33
  for (const animation of icon.getAnimations?.() || []) animation.cancel();
@@ -35,9 +35,10 @@ function animateRefresh() {
35
35
  { duration: 450, easing: "cubic-bezier(0.25, 1, 0.5, 1)" });
36
36
  }
37
37
  element("refresh").addEventListener("click", () => {
38
- animateRefresh();
38
+ animateLogo();
39
39
  dashboardRefresh.refreshVisible({ force: true });
40
40
  });
41
+ document.querySelector(".sidebar-brand").addEventListener("click", animateLogo);
41
42
 
42
43
  const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
43
44
  const animationView = globalThis.ccdxViewBoundary.create("animation-settings", () => globalThis.ccdxDashboardAnimation.create({ element, phrase, localize, text, reducedMotion,
@@ -256,7 +257,7 @@ function statusState(state) {
256
257
  text("connection", state.pending && !state.value ? "reading" : state.error ? "unavailable_eb0be" : "service_reachable");
257
258
  element("connection").className = `badge ${state.pending ? "neutral" : state.error ? "bad" : "good"}`;
258
259
  globalThis.ccdxIcons?.set(element("connection"), state.pending && !state.value ? "reading" : state.error ? "unavailable_eb0be" : "service_reachable",
259
- state.pending && !state.value ? "unknown" : state.error ? "unavailable" : "running");
260
+ state.pending && !state.value ? "unknown" : state.error ? "unavailable" : "connected");
260
261
  if (state.error) refreshTime(element("updated"), state);
261
262
  for (const node of timestamps.get("status")) refreshTime(node, state);
262
263
  }
@@ -269,6 +270,12 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
269
270
  element("refresh").setAttribute("aria-busy", String(busy));
270
271
  },
271
272
  resources: {
273
+ context: {
274
+ visible: () => globalThis.ccdxContextView?.visible() === true,
275
+ load: ({ signal }) => readDashboard("/_ccdx/ui/context", { signal, timeout: 5000, source: "run_context" }),
276
+ apply: data => globalThis.ccdxContextView?.apply(data),
277
+ state: state => globalThis.ccdxContextView?.state(state),
278
+ },
272
279
  updates: {
273
280
  visible: () => !element("version-updates").closest("[hidden]"),
274
281
  load: ({ signal }) => readDashboard("/_ccdx/ui/updates", { signal, timeout: 20000, source: "release_status" }),
@@ -458,7 +465,8 @@ for (const link of document.querySelectorAll("[data-source-link]")) link.addEven
458
465
  const id = link.dataset.sourceLink === "codex" ? providerEntries.find(provider => provider.clients?.some(client => client.id === "codex" && client.selected))?.id : link.dataset.sourceLink;
459
466
  if (providerEntries.some(provider => provider.id === id)) chooseProvider(id);
460
467
  });
468
+ window.addEventListener("ccdx:context-view", () => { if (globalThis.ccdxContextView?.visible()) void dashboardRefresh.refresh("context"); });
461
469
  loadAnimation();
462
470
  refresh();
463
471
  loadAuth();
464
- animateRefresh();
472
+ animateLogo();
@@ -148,6 +148,7 @@ export async function handleDashboardApi(req, res, pathname, {
148
148
  providerStateFn,
149
149
  providerAccountsFn,
150
150
  connectionsFn,
151
+ contextSnapshotFn,
151
152
  updateStatusFn,
152
153
  serviceControl,
153
154
  applyAnimation,
@@ -164,6 +165,11 @@ export async function handleDashboardApi(req, res, pathname, {
164
165
  return;
165
166
  }
166
167
 
168
+ if (pathname === "/_ccdx/ui/context") {
169
+ if (req.method !== "GET") { sendJson(res, 405, { error: "Use GET" });return; }
170
+ if (req.headers.origin && !sameOrigin(req)) { sendJson(res, 403, { error: "Context requires the same-origin dashboard" });return; }
171
+ sendJson(res, 200, contextSnapshotFn?.() || { source: "run_context", sessions: [], unassigned: [] });return;
172
+ }
167
173
  if (["/_ccdx/ui/account", "/_ccdx/ui/checks"].includes(pathname)) {
168
174
  return tools.handle(req, res, pathname, sendJson, sameOrigin);
169
175
  }
package/src/dashboard.mjs CHANGED
@@ -19,6 +19,7 @@ const ASSETS = new Map([
19
19
  ["/activity.js", ["./dashboard/activity.js", "text/javascript; charset=utf-8"]],
20
20
  ["/flow.js", ["./dashboard/flow.js", "text/javascript; charset=utf-8"]],
21
21
  ["/usage.js", ["./dashboard/usage.js", "text/javascript; charset=utf-8"]],
22
+ ["/context.js", ["./dashboard/context.js", "text/javascript; charset=utf-8"]],
22
23
  ["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
23
24
  ["/icons.js", ["./dashboard/icons.js", "text/javascript; charset=utf-8"]],
24
25
  ["/disclosure.js", ["./dashboard/disclosure.js", "text/javascript; charset=utf-8"]],
@@ -1,5 +1,5 @@
1
- export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js"]);
2
- export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections"]);
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js"]);
2
+ export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections", "/_ccdx/ui/context"]);
3
3
 
4
4
  export function isOptionalRoute(method, pathname) {
5
5
  return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
@@ -1,4 +1,5 @@
1
1
  import { defaultGithubProvider } from "./providers/github.mjs";
2
+ import { observeContextSession } from "./context-metrics.mjs";
2
3
  import {
3
4
  createRequestAbort,
4
5
  logRequestFailure,
@@ -218,6 +219,7 @@ export function createResponsesHandler(options) {
218
219
  if (provider.id !== "github") openAIModelEnv = { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" };
219
220
  }
220
221
  options.validateConversation?.(parsed, req.headers, provider);
222
+ observeContextSession(parsed, req.headers, provider);
221
223
  activeDeadline = now() + upstreamTimeoutMs;
222
224
  activeTimeoutReason = "responses_prepare_timeout";
223
225
  abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
@@ -503,6 +505,7 @@ export function createResponsesCompactHandler(options) {
503
505
  if (provider.id !== "github") openAIModelEnv = { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" };
504
506
  }
505
507
  options.validateConversation?.(parsed, req.headers, provider);
508
+ observeContextSession(parsed, req.headers, provider);
506
509
  activeDeadline = now() + upstreamTimeoutMs;
507
510
  activeTimeoutReason = "responses_prepare_timeout";
508
511
  abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
@@ -2,6 +2,7 @@ import { performance } from "node:perf_hooks";
2
2
  import { currentRequestContext } from "./request-context.mjs";
3
3
  import { isProviderId } from "./provider-metadata.mjs";
4
4
  import { applicationLabel } from "./request-application.mjs";
5
+ import { createContextMetrics } from "./context-metrics.mjs";
5
6
 
6
7
  const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
7
8
  const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
@@ -215,6 +216,7 @@ function routeSnapshot(route) {
215
216
  export function createStreamPerformanceMetrics({ now = () => performance.now(), wallNow = () => new Date().toISOString(), routeNames = PERFORMANCE_ROUTES } = {}) {
216
217
  const routes = Object.fromEntries(routeNames.map((name) => [name, createRoutePerformance()]));
217
218
  const recentRequests = [];
219
+ const contexts = createContextMetrics();
218
220
  const activeRequests = new Map();
219
221
  let activeTotal = 0, activeSequence = 0;
220
222
 
@@ -234,6 +236,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
234
236
  let failed = false;
235
237
  let finished = false;
236
238
  let model = "other";
239
+ let session = null;
240
+ let cachedInput = null;
237
241
  let provider = null;
238
242
  let sourceStats = null;
239
243
  let terminalOutcome = null;
@@ -323,10 +327,12 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
323
327
  model = modelLabel(value, configured);
324
328
  },
325
329
  setProvider: assignProvider,
330
+ observeSession(key) { if (!finished && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) session = key; },
326
331
  attemptCount() { return attempts; },
327
332
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
328
333
  observeContext(values) {
329
334
  if (finished || !values || typeof values !== "object") return;
335
+ if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
330
336
  for (const key of [...Object.keys(context), "capability_revision", "capability_constraints"]) {
331
337
  const value = values[key];
332
338
  if (["capability_revision", "capability_constraints"].includes(key)) {
@@ -379,6 +385,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
379
385
  for (const stage of PREPARATION_STAGES) observe(sourceStats.preparation[stage], preparationMs[stage]);
380
386
  }
381
387
  const finishedAt = now();
388
+ contexts.record({ session, application: client, provider, model, route: routeName, at, started: requestStartedAt,
389
+ finished: finishedAt, request_id: safeRequestId, outcome, context, cached_input_tokens: cachedInput });
382
390
  // Only scalar, allowlisted metadata survives the request; never retain payloads.
383
391
  recentRequests.push({
384
392
  request_id: safeRequestId, application: client,
@@ -427,6 +435,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
427
435
  },
428
436
  };
429
437
  },
438
+ contextSnapshot: () => contexts.snapshot(),
430
439
  snapshot() {
431
440
  return {
432
441
  by_route: Object.fromEntries(routeNames.map((name) => [name, routeSnapshot(routes[name])])),
@@ -223,7 +223,8 @@ export function recordUsage(record) {
223
223
 
224
224
  export function recordResponsesUsage(args) {
225
225
  const response = args.response || args.event?.response || args.event;
226
- markRequestObservation({ input_tokens: response?.usage?.input_tokens });
226
+ markRequestObservation({ input_tokens: response?.usage?.input_tokens,
227
+ cached_input_tokens: response?.usage?.input_tokens_details?.cached_tokens ?? response?.usage?.cached_input_tokens });
227
228
  return recordUsage(buildResponsesUsageRecord(args));
228
229
  }
229
230