codex-copilot-dx 1.3.1 → 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.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.
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
 
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
@@ -998,3 +1004,13 @@ The CLI keeps only command/version/status fundamentals before its early command
998
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.
999
1005
 
1000
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,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.2](RELEASE_1.3.2.md): protected App keys, bounded diagnostics and coalesced usage reads.
7
8
  - [1.3.1](RELEASE_1.3.1.md): bounded context observations and anchored WebUI details.
8
9
  - [1.3.0](RELEASE_1.3.0.md): scope, compatibility changes and verification.
9
10
 
package/docs/REFERENCE.md CHANGED
@@ -56,12 +56,16 @@ An app model file contains `deployments: [{"source":"github","model":"<model-id>
56
56
 
57
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
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
+
59
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.
60
62
 
61
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.
62
64
 
63
65
  ## Sources and client access
64
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
+
65
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.
66
70
 
67
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.
@@ -76,6 +80,8 @@ A running request stays with its original source, credential revision and capabi
76
80
 
77
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.
78
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
+
79
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.
80
86
 
81
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.
@@ -562,7 +568,7 @@ Editing references are opaque IDs bound to the provider configuration, not paths
562
568
  - CCDX binds to loopback by default. Non-loopback hosts are rejected unless `CCDX_ALLOW_LAN=1` is set explicitly.
563
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.
564
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.
565
- - 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.
566
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.
567
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.
568
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.
@@ -704,3 +710,9 @@ MIT
704
710
  | `CCDX_LOG_PATH` | Optional diagnostic log path |
705
711
 
706
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.1",
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/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. */ }
@@ -16,6 +16,19 @@ import { decodedBodyLimitPreference } from "./user-settings.mjs";
16
16
  import { operationErrorDetails, transportErrorDetails } from "./operation-error.mjs";
17
17
  import { requestApplication } from "./request-application.mjs";
18
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
+ }
19
32
 
20
33
  function send(res, code, value) {
21
34
  if (res.destroyed || res.writableEnded) return;
@@ -123,6 +136,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
123
136
  if (!resolveRequest) tracker?.setProvider(provider.id);
124
137
  const abort = createRequestAbort(req, res);
125
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;
126
140
  let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
127
141
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
128
142
  const context = parent || { requestId };
@@ -143,17 +157,24 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
143
157
  const resolved = await resolveRequest(body, req);
144
158
  selectedProvider = resolved.provider;finishProvider = resolved.finish || finishProvider;
145
159
  configuredModel = resolved.model;clientModel = body.model === configuredModel ? null : body.model;
160
+ selectedCapability = resolved.capability;
146
161
  body = { ...body, model: configuredModel };tracker?.setProvider(selectedProvider.id);
147
162
  const context = currentRequestContext();if (context) context.provider = selectedProvider.id;
148
163
  }
149
164
  if (desktopAliases) body = desktopMessages(body);
150
165
  model = body.model;streamed = !countTokens && body.stream === true;
151
- 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
+ }
152
170
  if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
153
171
  if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
154
172
  stats.last_model = model;
155
173
  context.model = configuredModel || model;
156
- 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
+ }
157
178
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
158
179
  conversation = validateConversation?.(body, req.headers, selectedProvider);
159
180
  if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
@@ -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;
@@ -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
  }
@@ -1,5 +1,6 @@
1
1
  (() => {
2
2
  const translations = {
3
+ "client_key_encrypted_kept": ["Key kept encrypted; access not checked.", "密钥保持加密,访问未验证。"],
3
4
  "context_tabs": ["Usage view", "统计视图"],
4
5
  "context_unknown_window": ["Unknown", "未知"],
5
6
  "context_compact_event": ["Compaction", "压缩"],
@@ -356,14 +356,15 @@ export async function handleDashboardApi(req, res, pathname, {
356
356
  return;
357
357
  }
358
358
  }
359
+ const abort = createRequestAbort(req, res);
359
360
  try {
360
361
  const analysis = analytics && !usageSummaryFn
361
- ? await analyzeUsageLogs(undefined, { timeZone: query.get("time_zone") || "UTC", provider }) : null;
362
- const summary = analysis?.summary || await (usageSummaryFn || (options => summarizeUsageLogs(undefined, options)))({ provider, ...(analytics ? { onRecord: analytics.record } : {}) });
363
- 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() } : {}) });
364
365
  } catch {
365
- sendJson(res, 500, { error: "Could not read local usage summary" });
366
- }
366
+ if (!abort.signal.aborted) sendJson(res, 500, { error: "Could not read local usage summary" });
367
+ } finally { abort.cleanup(); }
367
368
  return;
368
369
  }
369
370
 
@@ -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,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,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";
@@ -369,15 +370,16 @@ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord
369
370
  const SUMMARY_CACHE_MAX_BYTES = 256 * 1024;
370
371
  const SUMMARY_CACHE_SETTLED_MS = 2000;
371
372
  let cachedSummary = null;
373
+ const activeSummaries = createAbortAwareSingleflight();
372
374
 
373
- export async function usageSummaryVersion(filePath) {
375
+ export async function usageSummaryVersion(filePath, { settled = true } = {}) {
374
376
  try {
375
377
  const files = await Promise.all([rotatedFilePath(filePath), filePath].map(async (file) => {
376
378
  try {
377
379
  const stat = await fs.promises.stat(file, { bigint: true });
378
380
  if (!stat.isFile()) return null;
379
381
  const recent = Math.max(Number(stat.mtimeMs), Number(stat.ctimeMs));
380
- if (Date.now() - recent < SUMMARY_CACHE_SETTLED_MS) return null;
382
+ if (settled && Date.now() - recent < SUMMARY_CACHE_SETTLED_MS) return null;
381
383
  return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
382
384
  } catch (error) {
383
385
  if (error?.code === "ENOENT") return "missing";
@@ -388,14 +390,17 @@ export async function usageSummaryVersion(filePath) {
388
390
  } catch { return null; } // Uncacheable metadata never replaces the normal read/error path.
389
391
  }
390
392
 
391
- export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "" } = {}) {
393
+ export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "", signal } = {}) {
392
394
  if (provider && !isProviderId(provider)) throw new Error("Usage provider must be a valid provider ID");
393
395
  if (onRecord || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, provider });
394
396
  const fileVersion = await usageSummaryVersion(filePath);
395
397
  const version = fileVersion === null ? null : `${fileVersion}\0${provider}`;
396
398
  if (version === null) {
397
399
  cachedSummary = null;
398
- 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 }));
399
404
  }
400
405
  if (cachedSummary?.version === version) return structuredClone(await cachedSummary.promise);
401
406
  const entry = { version, promise: null };