codex-copilot-dx 1.3.0 → 1.3.2

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.2/install.sh), then `sh install.sh`.
19
+ - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.2/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
 
package/bin/cli.mjs CHANGED
@@ -448,7 +448,8 @@ try {
448
448
  const predictionSetup = codexEnabled && !serviceWorker?.warming ? runInBackground(() => earlyIntegration.start()) : Promise.resolve(null);
449
449
  const m365Setup = runInBackground(() => providerRuntime.start());
450
450
  if (providerRuntime.selection().codex === "github") {
451
- try { await ensureAuth({ log: startupLogger("Sign-in"), interactive: serviceWorker?.preserving !== true }); }
451
+ try { await ensureAuth({ log: startupLogger("Sign-in"), interactive: serviceWorker?.preserving !== true,
452
+ onImportedAuth: imported => profileRuntime.codexClient.reuseVerifiedAuth(imported) }); }
452
453
  catch (error) { if (serviceWorker?.preserving) throw error;console.warn(startupCheck("warn", "Sign-in", "Sign-in unavailable. Use the dashboard or ccdx source github login; saved credentials kept.")); }
453
454
  } else {
454
455
  if (providerRuntime.selection().codex === "m365") await m365Setup;
@@ -316,6 +316,12 @@ Copilot OAuth and noninteractive GitHub CLI token retrieval. Provider-specific
316
316
  readers do not validate or write credentials. The auth facade enforces bounded
317
317
  GitHub/Copilot validation, account matching and ambiguity handling. Saved-token
318
318
  startup does not scan sources or make new validation calls.
319
+ An optional `ensureAuth` import callback hands verified discovery results to the
320
+ startup client's `reuseVerifiedAuth`. The session rechecks the saved credential
321
+ and identity, expiry and existing cache/flight/account binding before using the
322
+ existing cache writer. Rejected handoffs leave normal refresh behavior intact.
323
+ No service-token file, shared global handoff cache, new endpoint or configuration
324
+ field is introduced; the auth facade still imports no runtime/client module.
319
325
 
320
326
  `windows-command.mjs` owns exact npm-generated CCDX PowerShell launcher cleanup.
321
327
  Best-effort Windows startup, the verified updater target and explicit doctor
@@ -931,6 +937,8 @@ The connection snapshot's read-only source_impacts reports actual selected consu
931
937
 
932
938
  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
939
 
940
+ 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.
941
+
934
942
  `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
943
 
936
944
 
@@ -988,3 +996,21 @@ Source-catalog tables keep fixed column geometry while native disclosures expand
988
996
  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
997
 
990
998
  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.
999
+
1000
+ ### Context observations
1001
+
1002
+ `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.
1003
+
1004
+ `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.
1005
+
1006
+ 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.
1007
+
1008
+ Messages window observation belongs to `claude-gateway.mjs`, independently of the source. It consumes the resolved route's capability snapshot first; legacy paths reuse the model already selected for alias resolution or look up cached model metadata through the existing capability interpreter. An explicit unknown snapshot does not fall back to another catalog value. Provider-applied observations may still report the actual request policy, as before. Optional metadata failures do not reject inference, and count-token probes do not create context observations. No additional network call, body scan, global cache or client configuration write is introduced.
1009
+
1010
+ ### Protected App keys and bounded control-plane work
1011
+
1012
+ `claude-client-config.mjs` recognizes the App's versioned encrypted representation only for an expected local key already owned by its journal. It does not decrypt, compare encrypted bytes with plaintext as authentication proof, adopt a foreign key or rewrite the encrypted field. Model operations continue through the existing per-field journal checks, preserving user edits and restore behavior. A transient `credential_state` accompanies the corresponding App sync observation, is cleared on the next targeted sync, and is shown only in the existing sync result. No storage schema or configuration template is added.
1013
+
1014
+ `boundedDiagnosticText` is a presentation-only boundary: a fixed input budget precedes terminal normalization/redaction, then UTF-16 surrogate boundaries are preserved at the existing output limits. `redactDiagnosticText` itself is unchanged because validators also use its exact result. Protocol bodies and retry classifiers do not consume the bounded diagnostic copy.
1015
+
1016
+ `usageSummaryVersion` retains its default settled-file semantics. Its explicit unsettled read mode exposes only an observed file identity for in-flight coalescing. Usage summary and analytics readers reuse the existing abort-aware singleflight and release completed flights; they do not add a persistent ledger/index. Filters and, for analytics, time zone/calendar date scope the key. Each caller still gets an isolated aggregate. HTTP usage readers forward cancellation to active-query waiters and avoid writes to cancelled responses. The underlying bounded scan may finish; it publishes no active-file cache entry.
package/docs/README.md CHANGED
@@ -4,6 +4,8 @@
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.2](RELEASE_1.3.2.md): protected App keys, bounded diagnostics and coalesced usage reads.
8
+ - [1.3.1](RELEASE_1.3.1.md): bounded context observations and anchored WebUI details.
7
9
  - [1.3.0](RELEASE_1.3.0.md): scope, compatibility changes and verification.
8
10
 
9
11
  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,27 @@ 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
+ Messages observes the selected model's effective capability snapshot after alias resolution. Legacy connections use cached catalog metadata when no snapshot is supplied. Missing or invalid windows remain unknown; no size is inferred from model names. Existing provider-applied capability observations keep their priority. This adds neither catalog refresh nor inference calls, and does not change request bodies, replies or token-count probes.
60
+
61
+ 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.
62
+
63
+ 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.
64
+
55
65
  ## Sources and client access
56
66
 
67
+ When Claude App encrypts a CCDX-owned gateway key, synchronization keeps the encrypted value and can still update owned model fields. The expected local key must match CCDX's ownership record; foreign profiles, addresses, rotated keys and user edits are not adopted. The sync result can report that the key was kept encrypted without claiming verified access. No system keystore decryption or extra permission is used.
68
+
69
+ 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.
70
+
57
71
  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
72
 
59
73
  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
74
 
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.
75
+ 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
76
 
63
77
  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
78
 
@@ -66,6 +80,8 @@ A running request stays with its original source, credential revision and capabi
66
80
 
67
81
  Codex selections containing only GitHub models keep native OpenAI mode and readable names. Other selections use the client's private local gateway credential. Paused access is rejected before credential validation. CCDX does not write or clear native ChatGPT sign-in data. When models are missing after a client update, check the selected models and run `ccdx doctor`; fully quit and reopen the app before changing credentials.
68
82
 
83
+ Old conversations keep their recorded provider identity. Codex 0.166 requires the currently selected provider to match that identity; a per-resume override does not bypass this check. Continue a legacy custom-provider chat with its original provider selected. CCDX retains the inactive, unchanged legacy provider table and does not silently rewrite chat metadata or switch the global native default back to a custom provider.
84
+
69
85
  Claude App and Claude Code use separate keys on `http://127.0.0.1:2026/anthropic`. Compatibility aliases are internal; visible model names follow source metadata. Client synchronization respects manual/managed fields and records ownership for restoration. Already-running clients may need a normal restart.
70
86
 
71
87
  Claude App can continue an existing conversation on another selected, authorized source when complete Messages history is available. Unfinished tool turns, unavailable attachments and company-account isolation are checked before transfer. Opaque signed or compacted history is not transferable between services. Codex and Claude Code keep their existing continuation rules. A 409 is a history/isolation conflict; it does not by itself mean the selected model is unavailable.
@@ -552,7 +568,7 @@ Editing references are opaque IDs bound to the provider configuration, not paths
552
568
  - CCDX binds to loopback by default. Non-loopback hosts are rejected unless `CCDX_ALLOW_LAN=1` is set explicitly.
553
569
  - Enabling LAN binding exposes a Copilot-backed API to other reachable machines. Provide your own host firewall and network isolation; do not expose the listener to an untrusted network.
554
570
  - Inference POSTs reject any browser `Origin` header before reading the body or contacting upstream, including simple `text/plain` requests. Native Codex/Node requests without Origin and deliberately enabled native LAN clients keep their existing access. This is not authentication or protection against untrusted local native programs.
555
- - Explicit auth tools store GitHub OAuth credentials at `~/.local/share/ccdx/github_token`, with precedence over the compatible legacy `~/.local/share/copilot-api/github_token` store. Short-lived Copilot service tokens remain in process memory and are refreshed as needed. See Account and repair tools for safe replacement/sign-out behavior.
571
+ - Explicit auth tools store GitHub OAuth credentials at `~/.local/share/ccdx/github_token`, with precedence over the compatible legacy `~/.local/share/copilot-api/github_token` store. Short-lived Copilot service tokens remain in process memory and are refreshed as needed. First-time local discovery hands its verified service token to the startup client when the saved credential and account match and more than a minute of validity remains, avoiding a duplicate exchange. Existing cached tokens, refreshes in flight and account bindings are retained. See Account and repair tools for safe replacement/sign-out behavior.
556
572
  - The optional image API credential is stored separately with mode `0600` only after `ccdx app codex image setup`; it is never placed in Codex configuration or diagnostic output.
557
573
  - Runtime status and usage records retain metadata by default; explicitly enabled HTTP error excerpts can contain private context. Diagnostic logging records status and error messages; it is not a general redaction layer for arbitrary error text. See Debug logging before sharing logs.
558
574
  - Request/response bodies, request-admission queues, retained history, image work, SSE buffers, log queues, retries, and shutdown have explicit limits. These component limits are not a single process-wide memory ceiling; completed image files are persistent user artifacts, not an automatically evicted cache.
@@ -694,3 +710,9 @@ MIT
694
710
  | `CCDX_LOG_PATH` | Optional diagnostic log path |
695
711
 
696
712
  Internal supervisor and installer environment fields are not user settings.
713
+
714
+ ## Diagnostic and usage read bounds
715
+
716
+ Diagnostic presentation omits input longer than 16,384 UTF-16 code units before normalization or credential scanning. Ordinary identifiers/messages retain budgets of 200/500 UTF-16 code units (400 for operation details), clipped only at complete surrogate boundaries. Oversized diagnostics retain structured status, error and request identifiers; original HTTP/SSE payloads are not changed. The general-purpose credential recognizer keeps its original semantics.
717
+
718
+ Usage queries for recently written logs may share an in-flight aggregate only when observed device/inode/size/mtime/ctime identities and query filters match. Those results are not kept after the scan. The existing two-second settled-file rule and bounded caches remain. Appends, rewrites, replacement, rotation, provider filters, time zone and calendar date retain independent identities. Custom warning callbacks bypass sharing. Cancelling one waiter does not stop other waiters; a bounded scan already started may complete without retaining its result.
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.2",
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(),
package/src/auth.mjs CHANGED
@@ -340,6 +340,7 @@ export async function ensureAuth({
340
340
  sleepImpl = sleep,
341
341
  now = Date.now,
342
342
  interactive = true,
343
+ onImportedAuth,
343
344
  } = {}) {
344
345
  const GITHUB_TOKEN_PATH = githubTokenPath(home);
345
346
  if (fs.existsSync(GITHUB_TOKEN_PATH)) {
@@ -360,7 +361,10 @@ export async function ensureAuth({
360
361
  }
361
362
 
362
363
  const imported = await importDiscoveredGithubToken({ home, env, fetchImpl, signal, log, lock: false });
363
- if (imported) return;
364
+ if (imported) {
365
+ await onImportedAuth?.(imported);
366
+ return;
367
+ }
364
368
 
365
369
  log(status("wait", "No usable GitHub token found. Starting device login..."));
366
370
 
@@ -242,16 +242,20 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
242
242
  else {
243
243
  let meta, profile;
244
244
  try { meta = read(paths.meta).value;profile = read(paths.profile).value; } catch { result.app = "configuration_unavailable"; }
245
+ const sealedOwnedKey = typeof profile?.inferenceGatewayApiKey === "string"
246
+ && profile.inferenceGatewayApiKey.trimStart().startsWith("__sealed__:v1:")
247
+ && owns(paths.profile, ["inferenceGatewayApiKey"], apiKey);
245
248
  if (!meta) { /* Code setup remains independent. */ }
246
249
  else if (meta.hybridPointer || meta.appliedId && meta.appliedId !== M365_CLAUDE_PROFILE_ID
247
250
  || profile.inferenceProvider && profile.inferenceProvider !== "gateway"
248
251
  || profile.inferenceGatewayBaseUrl && profile.inferenceGatewayBaseUrl !== baseUrl
249
252
  && !owns(paths.profile, ["inferenceGatewayBaseUrl"], profile.inferenceGatewayBaseUrl)
250
- || profile.inferenceGatewayApiKey && profile.inferenceGatewayApiKey !== apiKey && !owns(paths.profile, ["inferenceGatewayApiKey"], profile.inferenceGatewayApiKey)) result.app = "preserved";
253
+ || profile.inferenceGatewayApiKey && profile.inferenceGatewayApiKey !== apiKey && !owns(paths.profile, ["inferenceGatewayApiKey"], profile.inferenceGatewayApiKey) && !sealedOwnedKey) result.app = "preserved";
251
254
  else {
252
255
  add(paths.profile, ["inferenceProvider"], "gateway");
253
256
  add(paths.profile, ["inferenceGatewayBaseUrl"], baseUrl);
254
- add(paths.profile, ["inferenceGatewayApiKey"], apiKey);
257
+ if (sealedOwnedKey) result.app_credential = "encrypted_unverified";
258
+ else add(paths.profile, ["inferenceGatewayApiKey"], apiKey);
255
259
  add(paths.profile, ["inferenceGatewayAuthScheme"], "bearer");
256
260
  let previousModels = [];
257
261
  try { previousModels = JSON.parse(profile.inferenceModels || "[]"); } catch { /* Ownership reconciliation preserves a user-modified field. */ }
@@ -15,6 +15,20 @@ 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";
19
+ import { catalogCapabilities } from "./model-capabilities.mjs";
20
+
21
+ function observeMessagesWindow(provider, model, capability, entry) {
22
+ try {
23
+ if (capability == null) {
24
+ entry ||= resolveClaudeModel(provider.models("claude"), model);
25
+ capability = entry?.protocol_capabilities?.messages ?? entry?.capability;
26
+ }
27
+ if (capability == null && !entry) return;
28
+ const values = capability == null ? catalogCapabilities(entry) : capability.values;
29
+ markRequestObservation({ context_window_tokens: values?.context_window });
30
+ } catch { /* Optional catalog metadata must not change inference availability. */ }
31
+ }
18
32
 
19
33
  function send(res, code, value) {
20
34
  if (res.destroyed || res.writableEnded) return;
@@ -122,6 +136,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
122
136
  if (!resolveRequest) tracker?.setProvider(provider.id);
123
137
  const abort = createRequestAbort(req, res);
124
138
  let release = () => {}, conversation, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
139
+ let selectedModel, selectedCapability;
125
140
  let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
126
141
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
127
142
  const context = parent || { requestId };
@@ -142,19 +157,27 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
142
157
  const resolved = await resolveRequest(body, req);
143
158
  selectedProvider = resolved.provider;finishProvider = resolved.finish || finishProvider;
144
159
  configuredModel = resolved.model;clientModel = body.model === configuredModel ? null : body.model;
160
+ selectedCapability = resolved.capability;
145
161
  body = { ...body, model: configuredModel };tracker?.setProvider(selectedProvider.id);
146
162
  const context = currentRequestContext();if (context) context.provider = selectedProvider.id;
147
163
  }
148
164
  if (desktopAliases) body = desktopMessages(body);
149
165
  model = body.model;streamed = !countTokens && body.stream === true;
150
- if (!resolveRequest) configuredModel = provider.configuredModels || desktopAliases ? resolveClaudeModel(provider.models("claude"), model, { desktopAliases })?.id : null;
166
+ if (!resolveRequest && (provider.configuredModels || desktopAliases)) {
167
+ selectedModel = resolveClaudeModel(provider.models("claude"), model, { desktopAliases });
168
+ configuredModel = selectedModel?.id;
169
+ }
151
170
  if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
152
171
  if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
153
172
  stats.last_model = model;
154
173
  context.model = configuredModel || model;
155
- if (!countTokens) markRequestObservation({ max_output_tokens_requested: body.max_tokens });
174
+ if (!countTokens) {
175
+ markRequestObservation({ max_output_tokens_requested: body.max_tokens });
176
+ observeMessagesWindow(selectedProvider, configuredModel || model, selectedCapability, selectedModel);
177
+ }
156
178
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
157
179
  conversation = validateConversation?.(body, req.headers, selectedProvider);
180
+ if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
158
181
  terminalOrigin = "transport";
159
182
  const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
160
183
  onCountObservation(value) {
@@ -254,7 +277,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
254
277
  stats.active--;stats[outcome]++;
255
278
  const usageRecord = buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json",
256
279
  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 });
280
+ markRequestObservation({ input_tokens: usageRecord?.usage?.input_tokens, output_tokens: usageRecord?.usage?.output_tokens,
281
+ cached_input_tokens: usageRecord?.usage?.cached_input_tokens });
258
282
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
259
283
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, stopReason, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
260
284
  tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode, rejectionReason });
@@ -85,6 +85,7 @@ export function createConnectionRuntime({
85
85
  summaries = new WeakMap(),
86
86
  sourceSecrets = new WeakMap(),
87
87
  setup = {},
88
+ credentialStates = {},
88
89
  lastClients = {};
89
90
  const retiredSecrets = new Map(),
90
91
  cleanups = new Set(),
@@ -316,6 +317,7 @@ export function createConnectionRuntime({
316
317
  name: CLIENT_NAMES[id],
317
318
  ...config.clients[id],
318
319
  setup: setup[id] || null,
320
+ ...(credentialStates[id] ? { credential_state: credentialStates[id] } : {}),
319
321
  ...(id === "codex" ? { memory_model: memoryModel.snapshot() } : {}),
320
322
  observed_at: lastClients[id] || null,
321
323
  };
@@ -561,6 +563,7 @@ export function createConnectionRuntime({
561
563
  defaultModel: Array.isArray(selected.deployments) ? compiled.defaultModel : undefined,
562
564
  });
563
565
  setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
566
+ if (id === "claude_app" && result.app_credential) credentialStates[id] = result.app_credential;
564
567
  }
565
568
  function syncSharedClaudeCapabilities(targets) {
566
569
  if (["claude_app", "claude_code"].some(id => setup[id] === "default_unavailable")) {
@@ -601,6 +604,7 @@ export function createConnectionRuntime({
601
604
  }
602
605
  async function performClientSync(targets, requested = new Set()) {
603
606
  if (!managed || closed) return;
607
+ for (const id of targets) delete credentialStates[id];
604
608
  if (options.preserveClientConfiguration?.()) {
605
609
  for (const id of targets) setup[id] = "preserved";
606
610
  return;
@@ -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
+ }
@@ -231,6 +231,7 @@ export function createCopilotClientRuntime({
231
231
  getApiBase: tokenSession.getApiBase,
232
232
  runtimeStatus,
233
233
  getCopilotToken: tokenSession.getToken,
234
+ reuseVerifiedAuth: tokenSession.reuseVerifiedAuth,
234
235
  invalidateCredentials: tokenSession.invalidateCredentials,
235
236
  resetTokenForTests: tokenSession.resetForTests,
236
237
  chatCompletions,
@@ -359,6 +359,24 @@ export function createCopilotTokenSession({
359
359
  return waitForSingleflight(flight, options.signal);
360
360
  }
361
361
 
362
+ async function reuseVerifiedAuth(imported, { home } = {}) {
363
+ const validation = imported?.validation, data = validation?.copilotTokenData;
364
+ if (imported?.imported !== true || validation?.ok !== true || typeof data?.token !== "string" || !data.token.trim()
365
+ || typeof data.expires_at !== "number" || !Number.isFinite(data.expires_at * 1000)) return false;
366
+ try {
367
+ const credentials = await loadCredentials(home), identity = normalizeGithubIdentity(validation);
368
+ const savedIdentity = credentials.identity || (typeof readProfileGithubIdentity === "function"
369
+ ? await readProfileGithubIdentity(credentials.token, { profile, home: resolveHome(home), tokenPath: resolveTokenPath(home) })
370
+ : usesDefaultTokenStore ? readGithubTokenMetadata(resolveHome(home), credentials.token) : null);
371
+ if (copilotToken || refreshFlight || data.expires_at * 1000 <= Date.now() + 60000
372
+ || credentials.token !== imported.token || !identity || !savedIdentity
373
+ || !githubIdentitiesEqual(savedIdentity, identity)
374
+ || githubIdentity && !githubIdentitiesEqual(githubIdentity, identity)) return false;
375
+ cacheTokenData(data, { sourceKey: credentials.sourceKey, githubToken: credentials.token, identity });
376
+ return true;
377
+ } catch { return false; } // Normal refresh remains responsible for credential/transport errors.
378
+ }
379
+
362
380
  function runtimeStatus(now = Date.now()) {
363
381
  let upstreamHost = "unknown";
364
382
  try { upstreamHost = new URL(apiBase).hostname; } catch {}
@@ -394,6 +412,7 @@ export function createCopilotTokenSession({
394
412
 
395
413
  return Object.freeze({
396
414
  getToken,
415
+ reuseVerifiedAuth,
397
416
  getApiBase: () => apiBase,
398
417
  runtimeStatus,
399
418
  invalidateCredentials,
@@ -224,6 +224,7 @@
224
224
  const wrap = node("div", undefined, "table-wrap");wrap.append(table);result.append(wrap);
225
225
  const note = node("p", undefined, "hint");words(note, "cap_preview_scope");result.append(note);
226
226
  const sync = preview?.shared || c.model_plan?.sync;
227
+ if (c.credential_state === "encrypted_unverified") { const kept = node("p", undefined, "hint");words(kept, "client_key_encrypted_kept");result.append(kept); }
227
228
  if (sync) { const status = node("p", undefined, "hint");words(status, "cap_sync_" + sync.state);result.append(status);
228
229
  for (const limitation of sync.limitations || []) { const line = node("p", undefined, "hint");words(line, "cap_limit_" + limitation.code);if (limitation.model) line.prepend(limitation.model + ": ");result.append(line); }
229
230
  }
@@ -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,29 @@
1
1
  (() => {
2
2
  const translations = {
3
+ "client_key_encrypted_kept": ["Key kept encrypted; access not checked.", "密钥保持加密,访问未验证。"],
4
+ "context_tabs": ["Usage view", "统计视图"],
5
+ "context_unknown_window": ["Unknown", "未知"],
6
+ "context_compact_event": ["Compaction", "压缩"],
7
+ "context_tokens": ["Tokens", "用量"],
8
+ "context_title": ["Context", "上下文"],
9
+ "context_activity": ["Conversations & requests", "会话与请求"],
10
+ "context_item": ["Conversation / request", "会话/请求"],
11
+ "context_share": ["Input share", "输入占比"],
12
+ "context_latest_input": ["Latest input", "最近输入"],
13
+ "context_reuse": ["Cache reuse", "缓存复用"],
14
+ "context_history": ["Input history", "输入变化"],
15
+ "context_compactions": ["Gateway compactions", "网关压缩"],
16
+ "context_elapsed": ["Elapsed", "耗时"],
17
+ "context_conversation": ["Conversation {id}", "会话 {id}"],
18
+ "context_request": ["Request {id}", "请求 {id}"],
19
+ "context_empty": ["No records in this run.", "本次运行暂无记录。"],
20
+ "context_no_input": ["Input usage unavailable.", "未获得输入用量。"],
21
+ "context_unassigned": ["No conversation ID; shown as one request.", "未识别会话,仅显示此请求。"],
22
+ "context_no_compactions": ["No observed compactions.", "未观测到压缩。"],
23
+ "context_concurrent": ["Concurrent requests", "并发请求"],
24
+ "context_request_order": ["Request order", "请求顺序"],
25
+ "context_scope": ["This run · Reported metadata", "本次运行 · 上报数据"],
26
+ "context_read_failed": ["Read failed. Previous data kept.", "读取失败,保留上次数据。"],
3
27
  "model_id": ["Model ID", "模型 ID"],
4
28
  "catalog_scope": ["Catalog scope", "目录说明"],
5
29
  "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
  }
@@ -350,14 +356,15 @@ export async function handleDashboardApi(req, res, pathname, {
350
356
  return;
351
357
  }
352
358
  }
359
+ const abort = createRequestAbort(req, res);
353
360
  try {
354
361
  const analysis = analytics && !usageSummaryFn
355
- ? await analyzeUsageLogs(undefined, { timeZone: query.get("time_zone") || "UTC", provider }) : null;
356
- const summary = analysis?.summary || await (usageSummaryFn || (options => summarizeUsageLogs(undefined, options)))({ provider, ...(analytics ? { onRecord: analytics.record } : {}) });
357
- sendJson(res, 200, { source: "local_usage_log", provider: provider || "all", providers: summary.providers, ...usageTable(summary), ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
362
+ ? await analyzeUsageLogs(undefined, { timeZone: query.get("time_zone") || "UTC", provider, signal: abort.signal }) : null;
363
+ const summary = analysis?.summary || await (usageSummaryFn || (options => summarizeUsageLogs(undefined, { ...options, signal: abort.signal })))({ provider, ...(analytics ? { onRecord: analytics.record } : {}) });
364
+ if (!abort.signal.aborted) sendJson(res, 200, { source: "local_usage_log", provider: provider || "all", providers: summary.providers, ...usageTable(summary), ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
358
365
  } catch {
359
- sendJson(res, 500, { error: "Could not read local usage summary" });
360
- }
366
+ if (!abort.signal.aborted) sendJson(res, 500, { error: "Could not read local usage summary" });
367
+ } finally { abort.cleanup(); }
361
368
  return;
362
369
  }
363
370
 
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,3 +1,5 @@
1
+ import { terminalCell } from "./terminal-text.mjs";
2
+
1
3
  // Diagnostics are not a copy of the upstream payload. Keep useful error text,
2
4
  // but remove common credential forms and explicitly labelled content echoes.
3
5
  export function redactDiagnosticText(value) {
@@ -16,3 +18,13 @@ export function redactDiagnosticText(value) {
16
18
  .replace(/(encrypted(?: function output)? content\s+)[A-Za-z0-9+/_=-]{24,}/gi, "$1[redacted]")
17
19
  .replace(/\b[A-Za-z0-9+/_=-]{96,}\b/g, "[redacted]");
18
20
  }
21
+
22
+ // Bound work before scanning a diagnostic copy. The raw protocol response is untouched.
23
+ export function boundedDiagnosticText(value, { maxChars = 500, fallback = "Operation failed", overflow = "Diagnostic text omitted (too long)" } = {}) {
24
+ const raw = value === null || value === undefined ? fallback : String(value);
25
+ if (raw.length > 16 * 1024) return overflow;
26
+ const text = redactDiagnosticText(terminalCell(raw, { fallback }));
27
+ let end = Math.min(maxChars, text.length);
28
+ if (end > 0 && end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) && /[\uDC00-\uDFFF]/.test(text[end])) end--;
29
+ return text.slice(0, end);
30
+ }
@@ -1,4 +1,4 @@
1
- import { redactDiagnosticText } from "./diagnostic-text.mjs";
1
+ import { boundedDiagnosticText } from "./diagnostic-text.mjs";
2
2
 
3
3
  const TRANSPORT_CODES = new Set([
4
4
  "ECONNRESET", "ECONNREFUSED", "ECONNABORTED", "EPIPE", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "EPERM", "EACCES",
@@ -37,7 +37,7 @@ export function operationErrorDetails(error, { reason } = {}) {
37
37
  else if (/ENOTFOUND|ECONN|EAI_/.test(code)) source = "network";
38
38
  else if (/HTTP|http/.test(code) || status >= 400) source = "upstream";
39
39
  return { code: /^[A-Za-z0-9_-]{1,80}$/.test(code) ? code : "unknown", source,
40
- message: redactDiagnosticText(String(error?.message || "Operation failed")).slice(0, 400),
40
+ message: boundedDiagnosticText(error?.message || "Operation failed", { maxChars: 400 }),
41
41
  status };
42
42
  }
43
43
 
@@ -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,5 +1,4 @@
1
- import { terminalCell } from "./terminal-text.mjs";
2
- import { redactDiagnosticText } from "./diagnostic-text.mjs";
1
+ import { boundedDiagnosticText, redactDiagnosticText } from "./diagnostic-text.mjs";
3
2
  import { currentRequestContext } from "./request-context.mjs";
4
3
  import { isProviderId } from "./provider-metadata.mjs";
5
4
  import { transportErrorDetails } from "./operation-error.mjs";
@@ -7,14 +6,11 @@ import { transportErrorDetails } from "./operation-error.mjs";
7
6
  const DEFAULT_RECENT_FAILURES = 10;
8
7
 
9
8
  function safeIdentifier(value, fallback = "unknown") {
10
- const text = redactDiagnosticText(terminalCell(value, { fallback }));
11
- return text.slice(0, 200);
9
+ return boundedDiagnosticText(value, { maxChars: 200, fallback, overflow: fallback });
12
10
  }
13
11
 
14
12
  function safeFailureMessage(value) {
15
- let text = terminalCell(value, { fallback: "Response failed without an error message" });
16
- text = redactDiagnosticText(text);
17
- return text.slice(0, 500);
13
+ return boundedDiagnosticText(value, { fallback: "Response failed without an error message" });
18
14
  }
19
15
 
20
16
  function upstreamRequestId(headers) {
@@ -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])])),
@@ -1,23 +1,27 @@
1
1
  import { summarizeUsageLogs, usageLogPath, usageSummaryVersion } from "./usage-store.mjs";
2
2
  import { createUsageAnalytics } from "./usage-analytics.mjs";
3
+ import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
3
4
 
4
5
  const MAX_ENTRIES = 2;
5
6
  const MAX_BYTES = 2 * 1024 * 1024;
6
7
  const cache = new Map();
8
+ const activeReads = createAbortAwareSingleflight();
7
9
 
8
10
  // Only bounded, settled-file aggregates survive. No record index or payload cache.
9
- export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "" } = {}) {
11
+ export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", signal } = {}) {
10
12
  const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider });
11
13
  const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
12
14
  const version = warn === console.error ? await usageSummaryVersion(filePath) : null;
13
- const key = version === null ? null : `${version}\0${provider}\0${zone.resolvedOptions().timeZone}\0${zone.format(new Date(now))}`;
15
+ const query = `${provider}\0${zone.resolvedOptions().timeZone}\0${zone.format(new Date(now))}`;
16
+ const key = version === null ? null : `${version}\0${query}`;
17
+ const activeVersion = version === null && warn === console.error ? await usageSummaryVersion(filePath, { settled: false }) : null;
14
18
  if (key && cache.has(key)) return structuredClone(await cache.get(key).promise);
15
19
  if (key) {
16
20
  for (const [old, entry] of cache) if (entry.version !== version) cache.delete(old);
17
21
  while (cache.size >= MAX_ENTRIES) cache.delete(cache.keys().next().value);
18
22
  } else cache.clear();
19
23
  const entry = { version, bytes: 0, promise: null };
20
- entry.promise = (async () => {
24
+ const collect = async () => {
21
25
  let warned = false;
22
26
  const summary = await summarizeUsageLogs(filePath, {
23
27
  provider,
@@ -39,7 +43,8 @@ export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "
39
43
  }
40
44
  }
41
45
  return result;
42
- })();
46
+ };
47
+ entry.promise = activeVersion ? activeReads.run(`${activeVersion}\0${query}`, collect, { signal }) : collect();
43
48
  if (key) cache.set(key, entry);
44
49
  try { return structuredClone(await entry.promise); }
45
50
  catch (error) { if (cache.get(key) === entry) cache.delete(key); throw error; }
@@ -1,5 +1,6 @@
1
1
  import { isProviderId } from "./provider-metadata.mjs";
2
2
  import fs from "node:fs";
3
+ import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
3
4
  import { markRequestObservation } from "./stream-performance.mjs";
4
5
  import os from "node:os";
5
6
  import path from "node:path";
@@ -223,7 +224,8 @@ export function recordUsage(record) {
223
224
 
224
225
  export function recordResponsesUsage(args) {
225
226
  const response = args.response || args.event?.response || args.event;
226
- markRequestObservation({ input_tokens: response?.usage?.input_tokens });
227
+ markRequestObservation({ input_tokens: response?.usage?.input_tokens,
228
+ cached_input_tokens: response?.usage?.input_tokens_details?.cached_tokens ?? response?.usage?.cached_input_tokens });
227
229
  return recordUsage(buildResponsesUsageRecord(args));
228
230
  }
229
231
 
@@ -368,15 +370,16 @@ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord
368
370
  const SUMMARY_CACHE_MAX_BYTES = 256 * 1024;
369
371
  const SUMMARY_CACHE_SETTLED_MS = 2000;
370
372
  let cachedSummary = null;
373
+ const activeSummaries = createAbortAwareSingleflight();
371
374
 
372
- export async function usageSummaryVersion(filePath) {
375
+ export async function usageSummaryVersion(filePath, { settled = true } = {}) {
373
376
  try {
374
377
  const files = await Promise.all([rotatedFilePath(filePath), filePath].map(async (file) => {
375
378
  try {
376
379
  const stat = await fs.promises.stat(file, { bigint: true });
377
380
  if (!stat.isFile()) return null;
378
381
  const recent = Math.max(Number(stat.mtimeMs), Number(stat.ctimeMs));
379
- if (Date.now() - recent < SUMMARY_CACHE_SETTLED_MS) return null;
382
+ if (settled && Date.now() - recent < SUMMARY_CACHE_SETTLED_MS) return null;
380
383
  return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
381
384
  } catch (error) {
382
385
  if (error?.code === "ENOENT") return "missing";
@@ -387,14 +390,17 @@ export async function usageSummaryVersion(filePath) {
387
390
  } catch { return null; } // Uncacheable metadata never replaces the normal read/error path.
388
391
  }
389
392
 
390
- export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "" } = {}) {
393
+ export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "", signal } = {}) {
391
394
  if (provider && !isProviderId(provider)) throw new Error("Usage provider must be a valid provider ID");
392
395
  if (onRecord || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, provider });
393
396
  const fileVersion = await usageSummaryVersion(filePath);
394
397
  const version = fileVersion === null ? null : `${fileVersion}\0${provider}`;
395
398
  if (version === null) {
396
399
  cachedSummary = null;
397
- return summarizeUsageLogFiles(filePath, { warn, provider });
400
+ const activeVersion = await usageSummaryVersion(filePath, { settled: false });
401
+ if (!activeVersion) return summarizeUsageLogFiles(filePath, { warn, provider });
402
+ return structuredClone(await activeSummaries.run(`${activeVersion}\0${provider}`,
403
+ () => summarizeUsageLogFiles(filePath, { warn, provider }), { signal }));
398
404
  }
399
405
  if (cachedSummary?.version === version) return structuredClone(await cachedSummary.promise);
400
406
  const entry = { version, promise: null };