codex-copilot-dx 1.2.21 → 1.2.23

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.
Files changed (47) hide show
  1. package/README.md +7 -7
  2. package/bin/cli.mjs +77 -14
  3. package/docs/ARCHITECTURE.md +94 -3
  4. package/docs/REFERENCE.md +142 -6
  5. package/package.json +2 -1
  6. package/src/account-tools.mjs +1 -1
  7. package/src/adapter.mjs +23 -6
  8. package/src/api-catalog-refresh.mjs +6 -2
  9. package/src/api-secrets.mjs +28 -9
  10. package/src/auth.mjs +2 -0
  11. package/src/bounded-result-cache.mjs +12 -0
  12. package/src/claude-gateway.mjs +19 -3
  13. package/src/cli-status.mjs +2 -2
  14. package/src/client-gateway-keys.mjs +7 -3
  15. package/src/client-integration.mjs +3 -0
  16. package/src/connection-runtime.mjs +25 -6
  17. package/src/conversation-source-guard.mjs +3 -1
  18. package/src/dashboard/console.js +12 -2
  19. package/src/dashboard/flow.js +62 -33
  20. package/src/dashboard/index.html +8 -0
  21. package/src/dashboard/language.js +47 -0
  22. package/src/dashboard/status.js +29 -8
  23. package/src/dashboard/ui.css +18 -2
  24. package/src/dashboard/ui.js +4 -4
  25. package/src/dashboard/view-boundary.js +41 -0
  26. package/src/dashboard-tools.mjs +1 -0
  27. package/src/dashboard.mjs +26 -5
  28. package/src/image-mcp.mjs +3 -0
  29. package/src/image-references.mjs +9 -0
  30. package/src/local-tools.mjs +1 -1
  31. package/src/m365-settings.mjs +5 -0
  32. package/src/nightly-update.mjs +107 -0
  33. package/src/optional-routes.mjs +19 -5
  34. package/src/provider-runtime.mjs +3 -2
  35. package/src/providers/api-token-count.mjs +61 -0
  36. package/src/providers/api.mjs +17 -7
  37. package/src/release-install.mjs +24 -12
  38. package/src/request-context.mjs +8 -0
  39. package/src/response-failures.mjs +25 -5
  40. package/src/response-history.mjs +50 -0
  41. package/src/responses-handler.mjs +3 -0
  42. package/src/service-control.mjs +9 -3
  43. package/src/service-supervisor.mjs +168 -0
  44. package/src/service-worker.mjs +87 -0
  45. package/src/stream-performance.mjs +3 -1
  46. package/src/terminal-console.mjs +1 -0
  47. package/src/user-settings.mjs +15 -0
package/src/adapter.mjs CHANGED
@@ -12,6 +12,7 @@ import { createRequestId, runWithRequestContext, currentRequestContext } from ".
12
12
  import { requestApplication } from "./request-application.mjs";
13
13
  import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
14
14
  import { status } from "./status.mjs";
15
+ import { exportResponseHistory, importResponseHistory } from "./response-history.mjs";
15
16
  import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
16
17
  import { ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH } from "./running-adapter.mjs";
17
18
  import { createManagementHandler, isManagementRoute } from "./management-routes.mjs";
@@ -264,6 +265,9 @@ export function createAdapterHandler(options = {}) {
264
265
  return providerHandlers.get(provider);
265
266
  }
266
267
  const dispatch = async (req, res, pathname) => {
268
+ if (options.isDraining?.() && ![ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH].includes(pathname)) {
269
+ res.setHeader("Retry-After", "1");sendJsonError(res, httpError("CCDX is switching versions; retry shortly", 503));return;
270
+ }
267
271
  if (pathname.startsWith("/anthropic/")) {
268
272
  if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
269
273
  || Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Claude requires native local clients", 403));return; }
@@ -416,12 +420,13 @@ export function createAdapterHandler(options = {}) {
416
420
  if (requestFinished) return;
417
421
  requestFinished = true;
418
422
  if (trackRequest && statusCode >= 400) {
419
- try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model,
423
+ try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model || context?.requestedModel,
420
424
  method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
421
425
  target: ["/v1/responses", "/v1/responses/compact", "/anthropic/v1/messages", "/anthropic/v1/messages/count_tokens", "/anthropic/v1/models", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
422
- request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.(),
426
+ request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts,
423
427
  attempt_timings: streamPerformance?.attemptTimings?.(),
424
- requested_model: context?.requestedModel, provider: context?.provider,
428
+ requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
429
+ capability_cached: context?.countObservation?.cached, shared_upstream: context?.countObservation?.shared,
425
430
  })); } catch {}
426
431
  }
427
432
  try { complete({ statusCode, aborted }); } catch {}
@@ -462,13 +467,14 @@ export function createAdapterHandler(options = {}) {
462
467
  showRequestId: options.showRequestId === true,
463
468
  includeHttpErrorDetails: options.includeHttpErrorDetails === true || process.env.CCDX_HTTP_ERROR_DETAILS === "1",
464
469
  streamPerformance,
470
+ upstreamAttempts: 0,
465
471
  provider: undefined,
466
472
  finishProvider: undefined,
467
473
  historyNamespace: undefined,
468
474
  historyTransferNamespace: undefined,
469
475
  onHistoryStored: undefined,
470
476
  clientHeaders: undefined,
471
- onHttpError: evidence => { httpEvidence = evidence; },
477
+ onHttpError: evidence => { httpEvidence = { ...httpEvidence, ...evidence }; },
472
478
  };
473
479
  const result = runWithRequestContext(context, () => dispatchRequest(req, res, pathname));
474
480
  if (result && typeof result.then === "function") {
@@ -482,13 +488,20 @@ export function createAdapterHandler(options = {}) {
482
488
  }
483
489
  };
484
490
  handler.snapshot = statusSnapshot;
491
+ handler.busy = () => optionalRoutes.busy() || options.providerRuntime?.busy?.() === true;
492
+ handler.exportState = () => ({ version: 1, history: exportResponseHistory(), optional: optionalRoutes.exportState() });
493
+ handler.importState = async state => {
494
+ if (state?.version !== 1) throw new Error("Unsupported service-state version");
495
+ importResponseHistory(state.history);await optionalRoutes.importState(state.optional);
496
+ };
485
497
  handler.cleanup = () => optionalRoutes.dispose();
486
498
  return handler;
487
499
  }
488
500
 
489
501
  // Public server entry point.
490
502
 
491
- export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
503
+ export async function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
504
+ const handoffState = options.handoffState;options = { ...options };delete options.handoffState;
492
505
  const ownsTerminalActivity = !Object.hasOwn(options, "terminalActivity");
493
506
  const terminalActivity = ownsTerminalActivity
494
507
  ? createTerminalActivityIndicator({ theme: options.terminalAnimationTheme })
@@ -496,11 +509,15 @@ export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
496
509
  const handler = createAdapterHandler({ ...options, terminalActivity, imageMcpHostname: host });
497
510
  const server = http.createServer(handler);
498
511
  server.ccdxSnapshot = handler.snapshot;
512
+ server.ccdxBusy = handler.busy;
513
+ server.ccdxExportState = handler.exportState;
514
+ server.ccdxImportState = handler.importState;
515
+ if (handoffState) await handler.importState(handoffState);
499
516
  const cleanupTerminalActivity = () => {
500
517
  if (ownsTerminalActivity) terminalActivity?.cleanup?.();
501
518
  handler.cleanup?.();
502
519
  };
503
- server.once("close", cleanupTerminalActivity);
520
+ server.on("close", cleanupTerminalActivity);
504
521
 
505
522
  server.on("upgrade", (req, socket) => {
506
523
  // The responses_websockets upgrade expects a server-push protocol that this
@@ -21,7 +21,8 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
21
21
  if (old?.revision === version && !old.controller.signal.aborted) return old.promise;
22
22
  if (old) cancel(id);
23
23
  const cached = reads.get(id), age = cached ? now() - cached.at : Infinity;
24
- if (cached?.revision === version && age >= 0 && age < (force || cached.error ? 60000 : 30 * 60000)) {
24
+ const retryDelay = cached?.error ? [60000, 5 * 60000, 30 * 60000, 2 * 60 * 60000][Math.min((cached.failures || 1) - 1, 3)] : 0;
25
+ if (cached?.revision === version && age >= 0 && age < Math.max(cached.retryAfterMs || 0, force ? 60000 : cached.error ? retryDelay : 30 * 60000)) {
25
26
  if (cached.error) throw cached.error;
26
27
  await commit(id, cached.models, version, new Date(cached.at).toISOString(), () => current(id, version));
27
28
  onState(id, { state: "ready", checked_at: new Date(cached.at).toISOString() });return cached.models;
@@ -48,7 +49,9 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
48
49
  const code = /^ccdx_[a-z0-9_]+$/.test(error.code || "") ? error.code : "ccdx_api_catalog_unavailable";
49
50
  const failure = accessError(code, [401, 403, 409].includes(error.statusCode) ? error.statusCode : 502);
50
51
  if (active()) {
51
- reads.set(id, { revision: version, at: now(), error: failure });
52
+ reads.set(id, { revision: version, at: now(), error: failure,
53
+ retryAfterMs: Number.isFinite(error.retryAfterMs) ? Math.max(0, Math.min(error.retryAfterMs, 86400000)) : 0,
54
+ failures: cached?.revision === version ? Math.min((cached.failures || 0) + 1, 4) : 1 });
52
55
  onState(id, { state: "stale", code, checked_at: new Date(now()).toISOString() });
53
56
  }
54
57
  throw failure;
@@ -57,6 +60,7 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
57
60
  return flight.promise;
58
61
  }
59
62
  return {
63
+ busy: () => pending.size > 0,
60
64
  refresh, cancel, invalidate,
61
65
  refreshAll(ids) {
62
66
  if (closed) return Promise.resolve();
@@ -25,7 +25,8 @@ export function checkedApiKey(key) {
25
25
  if (typeof key !== "string" || !/^[\x21-\x7e]{8,4096}$/.test(key)) throw accessError("ccdx_api_key_invalid");return key;
26
26
  }
27
27
  export function createApiSecretStore({ platform = process.platform, env = process.env, run = secretProcess, ...options } = {}) {
28
- const cache = new Map(), folder = path.join(path.dirname(accessSettingsPath({ ...options, env })), "api-secrets");
28
+ const cache = new Map(), reads = new Map(), folder = path.join(path.dirname(accessSettingsPath({ ...options, env })), "api-secrets");
29
+ const forget = id => { cache.delete(id);reads.delete(id); };
29
30
  const ref = id => { if (!/^[a-f0-9]{32}$/.test(id)) throw accessError("ccdx_api_key_invalid");return id; };
30
31
  const powershell = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
31
32
  const ps = async (script, input) => run(powershell, ["-NoProfile", "-NonInteractive", "-Command",
@@ -33,6 +34,9 @@ export function createApiSecretStore({ platform = process.platform, env = proces
33
34
  return {
34
35
  async get(id) {
35
36
  ref(id);if (cache.has(id)) return cache.get(id);
37
+ if (reads.has(id)) return reads.get(id).promise;
38
+ const flight = {};
39
+ flight.promise = Promise.resolve().then(async () => {
36
40
  let key;
37
41
  if (platform === "darwin") key = await run("/usr/bin/security", ["find-generic-password", "-s", SERVICE, "-a", id, "-w"], "", env);
38
42
  else if (platform === "win32") {
@@ -40,10 +44,13 @@ export function createApiSecretStore({ platform = process.platform, env = proces
40
44
  if (!/^[A-Za-z0-9+/]{64,65536}={0,2}$/.test(encrypted) || encrypted.length % 4) throw accessError("ccdx_api_secret_unavailable", 503);
41
45
  key = await ps("$null=[Reflection.Assembly]::LoadWithPartialName('System.Security');$b=[Convert]::FromBase64String([Console]::In.ReadLine());$p=[Security.Cryptography.ProtectedData]::Unprotect($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Write([Text.Encoding]::UTF8.GetString($p))", encrypted);
42
46
  } else key = await run("/usr/bin/secret-tool", ["lookup", "service", SERVICE, "reference", id], "", env);
43
- checkedApiKey(key);cache.set(id, key);return key;
47
+ checkedApiKey(key);if (reads.get(id) === flight) cache.set(id, key);return key;
48
+ }).finally(() => { if (reads.get(id) === flight) reads.delete(id); });
49
+ reads.set(id, flight);return flight.promise;
44
50
  },
45
51
  async set(id, key) {
46
- ref(id);checkedApiKey(key);
52
+ ref(id);checkedApiKey(key);forget(id);
53
+ try {
47
54
  if (platform === "darwin") {
48
55
  const quote = value => '"' + value.replace(/[\\"]/g, "\\$&") + '"';
49
56
  await run("/usr/bin/security", ["-i"], `add-generic-password -a ${quote(id)} -s ${quote(SERVICE)} -w ${quote(key)}\n`, env);
@@ -56,14 +63,26 @@ export function createApiSecretStore({ platform = process.platform, env = proces
56
63
  if (!/^[A-Za-z0-9+/]{64,65536}={0,2}$/.test(encrypted) || encrypted.length % 4) throw accessError("ccdx_api_secret_unavailable", 503);
57
64
  fs.mkdirSync(folder, { recursive: true, mode: 0o700 });atomicWriteFileSync(path.join(folder, id), encrypted, { mode: 0o600 });
58
65
  } else await run("/usr/bin/secret-tool", ["store", "--label=CCDX API", "service", SERVICE, "reference", id], key, env);
59
- cache.set(id, key);
66
+ } catch (error) { forget(id);throw error; }
67
+ forget(id);cache.set(id, key);
60
68
  },
61
69
  async remove(id) {
62
- ref(id);cache.delete(id);
63
- if (platform === "darwin") await run("/usr/bin/security", ["delete-generic-password", "-s", SERVICE, "-a", id], "", env);
64
- else if (platform === "win32") fs.rmSync(path.join(folder, id), { force: true });
65
- else await run("/usr/bin/secret-tool", ["clear", "service", SERVICE, "reference", id], "", env);
70
+ ref(id);forget(id);
71
+ try {
72
+ if (platform === "darwin") await run("/usr/bin/security", ["delete-generic-password", "-s", SERVICE, "-a", id], "", env);
73
+ else if (platform === "win32") fs.rmSync(path.join(folder, id), { force: true });
74
+ else await run("/usr/bin/secret-tool", ["clear", "service", SERVICE, "reference", id], "", env);
75
+ } finally { forget(id); }
76
+ },
77
+ close() { cache.clear();reads.clear(); },
78
+ exportState(allowed) { return [...cache].filter(([id]) => allowed.includes(id)); },
79
+ importState(values, allowed) {
80
+ if (!Array.isArray(values) || values.length > 16 || new Set(values.map(pair => pair?.[0])).size !== values.length) throw accessError("ccdx_api_secret_unavailable", 503);
81
+ for (const pair of values) {
82
+ if (!Array.isArray(pair) || pair.length !== 2 || !allowed.includes(pair[0])) throw accessError("ccdx_api_secret_unavailable", 503);
83
+ ref(pair[0]);checkedApiKey(pair[1]);
84
+ }
85
+ for (const [id, key] of values) { forget(id);cache.set(id, key); }
66
86
  },
67
- close() { cache.clear(); },
68
87
  };
69
88
  }
package/src/auth.mjs CHANGED
@@ -339,6 +339,7 @@ export async function ensureAuth({
339
339
  githubIdentityTimeoutMs = DEFAULT_GITHUB_IDENTITY_TIMEOUT_MS,
340
340
  sleepImpl = sleep,
341
341
  now = Date.now,
342
+ interactive = true,
342
343
  } = {}) {
343
344
  const GITHUB_TOKEN_PATH = githubTokenPath(home);
344
345
  if (fs.existsSync(GITHUB_TOKEN_PATH)) {
@@ -350,6 +351,7 @@ export async function ensureAuth({
350
351
  log(status("warn", "GitHub token file is empty"));
351
352
  }
352
353
 
354
+ if (!interactive) throw new Error("Saved GitHub sign-in is unavailable; unattended login was skipped");
353
355
  await withFileLock(githubTokenLockPath(home), async () => {
354
356
  const savedToken = readSavedGithubToken(home);
355
357
  if (savedToken) {
@@ -61,6 +61,18 @@ export function createByteLruCache({ maxBytes }) {
61
61
  misses = 0;
62
62
  evictions = 0;
63
63
  },
64
+ exportEntries() { return [...entries].map(([key, entry]) => [key, entry.value]); },
65
+ importEntries(values) {
66
+ if (!Array.isArray(values) || values.length > 10000) throw new Error("Invalid cache handoff");
67
+ const seen = new Set();let size = 0;
68
+ for (const pair of values) {
69
+ if (!Array.isArray(pair) || pair.length !== 2 || pair.some(value => typeof value !== "string") || seen.has(pair[0])) throw new Error("Invalid cache handoff");
70
+ seen.add(pair[0]);size += byteLength(pair[0]) + byteLength(pair[1]);
71
+ if (size > limit) throw new Error("Cache handoff exceeds this version's limit");
72
+ }
73
+ entries.clear();bytes = 0;
74
+ for (const [key, value] of values) { const size = byteLength(key) + byteLength(value);entries.set(key, { value, bytes: size });bytes += size; }
75
+ },
64
76
  stats() {
65
77
  return {
66
78
  entries: entries.size,
@@ -7,7 +7,8 @@ import { createRequestAdmission } from "./request-admission.mjs";
7
7
  import { loadRuntimeConfig } from "./runtime-config.mjs";
8
8
  import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
9
9
  import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
10
- import { runWithRequestContext, currentRequestContext } from "./request-context.mjs";
10
+ import { runWithRequestContext, currentRequestContext, observeRequestedModel } from "./request-context.mjs";
11
+ import { upstreamErrorEvidence } from "./response-failures.mjs";
11
12
  import { createStreamPerformanceMetrics, isMessagesOutputDelta } from "./stream-performance.mjs";
12
13
  import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
13
14
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
@@ -17,6 +18,8 @@ import { requestApplication } from "./request-application.mjs";
17
18
 
18
19
  function send(res, code, value) {
19
20
  if (res.destroyed || res.writableEnded) return;
21
+ const context = currentRequestContext();
22
+ if (code >= 400) context?.onHttpError?.({ code: value?.error?.code, origin: context.errorOrigin || "client_validation" });
20
23
  res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
21
24
  }
22
25
  const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
@@ -113,17 +116,21 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
113
116
  const parent = currentRequestContext();
114
117
  if (parent) parent.provider = provider.id;
115
118
  const countTokens = pathname.endsWith("/count_tokens"), requestId = parent?.requestId || randomUUID();
116
- const tracker = countTokens ? null : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
119
+ const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
117
120
  if (!resolveRequest) tracker?.setProvider(provider.id);
118
121
  const abort = createRequestAbort(req, res);
119
122
  let release = () => {}, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
120
123
  let terminalOrigin = "client_validation", failureStatus = null;
121
124
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
122
- await runWithRequestContext({ requestId, provider: selectedProvider.id, route: "messages", streamPerformance: tracker }, async () => {
125
+ const context = parent || { requestId };
126
+ context.provider = selectedProvider.id;context.application = requestApplication(req.headers, "claude");
127
+ context.streamPerformance = tracker;context.route = countTokens ? "messages_count_tokens" : "messages";
128
+ await runWithRequestContext(context, async () => {
123
129
  try {
124
130
  release = await acquireRequest(req, { signal: abort.signal });
125
131
  abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
126
132
  let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
133
+ observeRequestedModel(body);
127
134
  if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
128
135
  send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
129
136
  }
@@ -140,10 +147,15 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
140
147
  if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
141
148
  if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
142
149
  stats.last_model = model;
150
+ context.model = configuredModel || model;
143
151
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
144
152
  validateConversation?.(body, req.headers, selectedProvider);
145
153
  terminalOrigin = "transport";
146
154
  const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
155
+ onCountObservation(value) {
156
+ context.countObservation = { ...context.countObservation, ...value };
157
+ if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
158
+ },
147
159
  onUpstreamStart() { abort.setTimeout(streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs, "upstream_timeout"); } });
148
160
  body = null;
149
161
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
@@ -156,6 +168,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
156
168
  const raw = await readBoundedResponseText(upstream, { maxBytes: upstream.ok ? config.maxUpstreamResponsesResponseBytes : MAX_UPSTREAM_ERROR_BODY_BYTES,
157
169
  label: "Claude gateway response", signal: abort.signal });
158
170
  let value;try { value = JSON.parse(raw); } catch {}
171
+ if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
172
+ origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
159
173
  if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
160
174
  model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
161
175
  sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
@@ -195,10 +209,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
195
209
  outcome = detail.source === "cancelled" ? "cancelled" : "failed";
196
210
  const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
197
211
  failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
212
+ context.errorOrigin = terminalOrigin;
198
213
  const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
199
214
  const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
200
215
  log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
201
216
  tracker?.setErrorOrigin(terminalOrigin);
217
+ context.onHttpError?.({ code: detail.code, origin: terminalOrigin });
202
218
  if (outcome === "cancelled") return;
203
219
  if (!res.headersSent) {
204
220
  const value = apiError(error.code || abort.reason || "ccdx_gateway_error", message);
@@ -200,9 +200,9 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
200
200
  if (data.http_errors) {
201
201
  lines.push(status("info", `HTTP failures: ${count(data.http_errors.total)} observed (separate from model terminal events)`));
202
202
  const categories = data.http_errors.by_category;
203
- if (categories) lines.push(status("info", `HTTP categories: ${count(categories.inference)} inference, ${count(categories.protocol)} unsupported MCP methods, ${count(categories.route)} unmatched routes, ${count(categories.other)} other`));
203
+ if (categories) lines.push(status("info", `HTTP categories: ${count(categories.inference)} generation, ${count(categories.capability)} token counts, ${count(categories.protocol)} unsupported MCP methods, ${count(categories.route)} unmatched routes, ${count(categories.other)} other`));
204
204
  for (const failure of (data.http_errors.actionable_recent || []).slice(-3).reverse()) {
205
- lines.push(status("warn", `HTTP ${count(failure.http_status)} ${terminalCell(failure.model)} ${terminalCell(failure.code)}${failure.parameter ? ` param=${terminalCell(failure.parameter)}` : ""}; ${terminalCell(failure.origin)}; ${count(failure.upstream_attempts)} attempts`));
205
+ lines.push(status("warn", `HTTP ${count(failure.http_status)} ${terminalCell(failure.model)} ${terminalCell(failure.code)}${failure.reason ? ` reason=${terminalCell(failure.reason)}` : ""}${failure.parameter ? ` param=${terminalCell(failure.parameter)}` : ""}; ${terminalCell(failure.origin)}; ${count(failure.upstream_attempts)} attempts`));
206
206
  }
207
207
  }
208
208
  lines.push(status("info", `Models: ${count(models.models)} total; Copilot token ${copilot.token_cached ? `cached (${duration(copilot.token_expires_in_ms)} remaining)` : "not cached"}`));
@@ -6,8 +6,13 @@ import { readBoundedFileSync } from "./bounded-file.mjs";
6
6
  import { withFileLockSync } from "./lock.mjs";
7
7
  import { atomicWriteFileSync } from "./atomic-file.mjs";
8
8
 
9
- export function readClientGatewayKeys(options = {}) {
9
+ export function readClientGatewayKeys({ create = true, ...options } = {}) {
10
10
  const file = path.join(path.dirname(accessSettingsPath(options)), "client-gateway-keys.json");
11
+ const checked = value => {
12
+ if (!value || Object.keys(value).length !== CLIENT_IDS.length || CLIENT_IDS.some(id => !/^[a-f0-9]{64}$/.test(value[id]))) throw accessError("ccdx_client_keys_invalid", 409);
13
+ return value;
14
+ };
15
+ if (!create) return checked(JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 2048 })));
11
16
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
12
17
  return withFileLockSync(`${file}.lock`, () => {
13
18
  let value;
@@ -17,8 +22,7 @@ export function readClientGatewayKeys(options = {}) {
17
22
  value = Object.fromEntries(CLIENT_IDS.map(id => [id, randomBytes(32).toString("hex")]));
18
23
  atomicWriteFileSync(file, JSON.stringify(value) + "\n", { mode: 0o600 });
19
24
  }
20
- if (!value || Object.keys(value).length !== CLIENT_IDS.length || CLIENT_IDS.some(id => !/^[a-f0-9]{64}$/.test(value[id]))) throw accessError("ccdx_client_keys_invalid", 409);
21
- return value;
25
+ return checked(value);
22
26
  });
23
27
  }
24
28
  export function gatewayClient(headers, keys) {
@@ -121,6 +121,9 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
121
121
  return { active, state: active ? "active" : native ? "paused" : "needs_setup" };
122
122
  },
123
123
  snapshot() { return { prediction: { ...prediction.snapshot(), active: native?.enabled?.() === true } }; },
124
+ busy: () => Boolean(operation),
125
+ bridgeHealthy: () => native?.healthy?.() === true,
126
+ pauseForUpdate() { return serialize("pause", async () => { await native?.close();native = null; }); },
124
127
  async close() { closed = true;try { await operation; } finally { await native?.close();native = null; } },
125
128
  };
126
129
  }
@@ -20,8 +20,8 @@ import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from
20
20
  const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
21
21
  export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
22
22
  secretStore, createApi = createApiProvider, configureClaude = configureClaudeClients, restoreClaude = restoreClaudeClients,
23
- configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, now = Date.now, log = () => {} } = {}) {
24
- const options = { home, env, platform }, secrets = secretStore || createApiSecretStore(options);
23
+ configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, preserveClientConfiguration, now = Date.now, log = () => {} } = {}) {
24
+ const options = { home, env, platform, preserveClientConfiguration }, secrets = secretStore || createApiSecretStore(options);
25
25
  const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
26
26
  let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
27
27
  const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
@@ -31,7 +31,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
31
31
  commit: (...args) => enqueue(() => applyCatalog(...args)),
32
32
  onState: (id, state) => state ? discoveries.set(id, state) : discoveries.delete(id) });
33
33
  const capabilitySupport = inspectClaudeCapabilitySupport(options);
34
- let sharedSync = null, syncFlight = null, syncAgain = false;const syncTargets = new Set();
34
+ let sharedSync = null, syncFlight = null, syncAgain = false, operations = 0;const syncTargets = new Set();
35
35
  function cleanSecrets(id) {
36
36
  const refs = retiredSecrets.get(id);if (!refs) return;
37
37
  for (const ref of refs) {
@@ -75,7 +75,15 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
75
75
  }
76
76
  function resolveDeployment(id, model) {
77
77
  const value = plan(id), record = value.routes.get(model);
78
- if (!record) throw accessError("ccdx_api_model_unavailable");
78
+ if (!record) {
79
+ const selected = binding(id), configured = selected.deployments || [{ source: selected.source, model: selected.model }];
80
+ const matches = configured.filter(item => item.model === model || deploymentModelId(item.source, item.model) === model);
81
+ const reason = !selected.enabled ? "ccdx_client_source_disabled" : matches.length > 1 ? "ccdx_model_ambiguous"
82
+ : matches.length && !permitted(id, matches[0].source) ? "ccdx_client_source_disabled"
83
+ : matches.length ? "ccdx_model_catalog_unavailable" : "ccdx_model_not_selected";
84
+ const error = accessError("ccdx_api_model_unavailable");error.jsonBody.error.reason = reason;
85
+ currentRequestContext()?.onHttpError?.({ code: error.code, origin: "client_validation", reason });throw error;
86
+ }
79
87
  const provider = requireSource(id, record.source);
80
88
  if (provider !== record.provider) { plans.delete(id);return resolveDeployment(id, model); }
81
89
  return record;
@@ -131,6 +139,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
131
139
  }
132
140
  async function performClientSync(targets) {
133
141
  if (!managed || closed) return;
142
+ if (options.preserveClientConfiguration?.()) { for (const id of targets) setup[id] = "preserved";return; }
134
143
  const codex = binding("codex"), compiledCodex = plan("codex");
135
144
  const explicit = Array.isArray(codex.deployments), native = explicit ? codex.deployments.length > 0 && codex.deployments.every(item => item.source === "github") : codex.source === "github";
136
145
  if (targets.has("codex")) try {
@@ -191,8 +200,8 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
191
200
  save(next);await syncClients(CLIENT_IDS.filter(client => binding(client).source === id || binding(client).deployments?.some(model => model.source === id)));
192
201
  }
193
202
  }
194
- function enqueue(work) { const job = serial.then(work);serial = job.catch(() => {});return job; }
195
- const refreshApis = () => !closed && managed ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id)) : Promise.resolve();
203
+ function enqueue(work) { operations++;const job = serial.then(work).finally(() => { operations--; });serial = job.catch(() => {});return job; }
204
+ const refreshApis = () => !closed && managed && !preserveClientConfiguration?.() ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id)) : Promise.resolve();
196
205
  async function change(input) {
197
206
  if (closed) throw accessError("ccdx_connections_closed", 503);
198
207
  if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "model", "auto_review_model", "auto_review_effort", "deployments", "default_model", "auto_sync"])) throw accessError("ccdx_connections_action_invalid");
@@ -315,6 +324,16 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
315
324
  ...legacy,
316
325
  source: getSource,
317
326
  connections: snapshot,
327
+ privateScopes: id => [...new Set(plan(id).models.map(model => model.source_id))].sort().map(source => [source, getSource(source).profileId(id === "codex" ? "responses" : "messages")]),
328
+ validateLocalKeys() {
329
+ if (managed && CLIENT_IDS.some(id => binding(id).enabled && plan(id).models.some(model => model.source_id.startsWith("api_") || id !== "codex" && settings.claude_private_keys))) keys = readClientGatewayKeys({ ...options, create: false });
330
+ },
331
+ exportPrivateState: () => {
332
+ const credentials = secrets.exportState?.(settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)) || [];
333
+ return { credentials, bytes: credentials.reduce((sum, [ref, key]) => sum + 2 * Buffer.byteLength(ref + key) + 64, 0) };
334
+ },
335
+ importPrivateState: state => secrets.importState?.(state?.credentials || [], settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)),
336
+ busy: () => operations > 0 || active.size > 0 || Boolean(syncFlight) || catalogRefresh.busy() || legacy.snapshot().m365.account_change_in_flight === true || legacy.snapshot().m365.state === "checking",
318
337
  syncClients,
319
338
  async manageConnections(input) {
320
339
  if (!input) return snapshot();
@@ -22,7 +22,9 @@ export function createConversationSourceGuard(options = {}) {
22
22
  const identified = typeof session === "string" && session.length > 0 && session.length <= 512 && !/[\u0000-\u001f\u007f]/.test(session);
23
23
  const first = items.find(item => item?.role === "user"), input = identified ? `session\0${session}` : first ? `first\0${JSON.stringify(first)}` : typeof body.input === "string" ? `first\0${body.input}` : null;
24
24
  if (!input) return;
25
- const key = hash(client + "\0" + input), owner = hash(profile);
25
+ const agent = headers["x-claude-code-agent-id"];
26
+ const child = identified && ["claude_app", "claude_code"].includes(client) && typeof agent === "string" && /^[\w-]{1,128}$/.test(agent) ? `\0agent\0${agent}` : "";
27
+ const key = hash(client + "\0" + input + child), owner = hash(profile);
26
28
  if (cache?.[key] === owner) return;
27
29
  if (cache?.[key] && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
28
30
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
@@ -105,6 +105,10 @@
105
105
  window.addEventListener("ccdx:providers", () => { syncSources();if (current === "codex") void loadSourceModels(); });
106
106
  function applySettings(data) {
107
107
  settings = data;
108
+ const nightly = data.nightly_update;
109
+ el("nightly-update").checked = nightly?.enabled === true;el("nightly-update").disabled = false;
110
+ el("nightly-rules").hidden = nightly?.enabled !== true;
111
+ label(el("nightly-state"), !nightly?.enabled ? "nightly_off" : nightly.effect === "next_start" ? "nightly_next_start" : `nightly_${nightly.phase || "watching"}`);
108
112
  el("terminal-color-theme").value = data.color_theme || "green";
109
113
  el("terminal-color-theme").disabled = settingsPending;
110
114
  el("terminal-color-sample").dataset.terminalPalette = data.color_theme || "green";
@@ -181,7 +185,7 @@
181
185
  syncAccountControls();
182
186
  const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-enabled")];
183
187
  controls.forEach(input => { input.disabled = true; });
184
- const note = el(body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
188
+ const note = el(body.action === "nightly_update" ? "nightly-state" : body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
185
189
  : body.action.startsWith("history_") ? "effect-history" : body.action === "prediction_fix" ? "prediction-note"
186
190
  : body.operation === "switch" ? "source-control-note" : body.operation === "auto-review" ? "review-control-note"
187
191
  : body.operation === "account" ? "m365-account-note" : "m365-control-note");
@@ -279,12 +283,13 @@
279
283
  model: el("source-model").value, ...(settings?.providers?.codex_provider === provider ? {} : {
280
284
  auto_review_model: el("source-review").value, auto_review_effort: el("source-review-effort").value || null }) } : {}) }, el("apply-source"));
281
285
  });
286
+ el("nightly-update").addEventListener("change", () => void change({ action: "nightly_update", enabled: el("nightly-update").checked }, el("nightly-update")));
282
287
  el("save-review").addEventListener("click", () => void change({ action: "provider", operation: "auto-review", provider: el("source-provider").value,
283
288
  model: el("source-review").value, auto_review_effort: el("source-review-effort").value || null }, el("save-review")));
284
289
  // Only the small in-memory status snapshot is read at this cadence. Catalogs
285
290
  // and retained usage keep their existing on-demand, bounded refresh policy.
286
291
  function schedule() {
287
- clearTimeout(timer);if (stopped) return;
292
+ clearTimeout(timer);if (stopped || document.visibilityState !== "visible" || !dashboardRefresh.automatic) return;
288
293
  timer = setTimeout(async () => {
289
294
  if (document.visibilityState === "visible" && dashboardRefresh.automatic) {
290
295
  await dashboardRefresh.refresh("status", { force: true });
@@ -297,6 +302,11 @@
297
302
  }, 2000);
298
303
  }
299
304
  window.addEventListener("hashchange", navigate);
305
+ document.addEventListener("visibilitychange", () => {
306
+ if (!stopped && document.visibilityState === "visible" && dashboardRefresh.automatic) void dashboardRefresh.refresh("status", { force: true });
307
+ schedule();
308
+ });
309
+ el("auto-refresh").addEventListener("click", schedule);
300
310
  el("refresh").addEventListener("click", () => { if (settingsViews.includes(current)) void loadSettings(); });
301
311
  window.addEventListener("pagehide", () => { stopped = true;clearTimeout(timer); });
302
312
  window.addEventListener("pageshow", () => { stopped = false;schedule(); });