codex-copilot-dx 1.1.1 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +10 -11
  2. package/bin/cli.mjs +23 -23
  3. package/docs/ARCHITECTURE.md +40 -6
  4. package/docs/REFERENCE.md +128 -94
  5. package/package.json +6 -4
  6. package/src/auth-device-flow.mjs +1 -1
  7. package/src/auth-status.mjs +1 -1
  8. package/src/auto-review-model.mjs +2 -2
  9. package/src/claude-client-lifecycle.mjs +33 -0
  10. package/src/claude-gateway.mjs +15 -6
  11. package/src/cli-auth.mjs +6 -6
  12. package/src/cli-cache.mjs +5 -5
  13. package/src/cli-image.mjs +1 -1
  14. package/src/cli-m365.mjs +5 -5
  15. package/src/cli-models.mjs +2 -2
  16. package/src/cli-options.mjs +26 -26
  17. package/src/cli-status.mjs +6 -1
  18. package/src/dashboard/console.js +112 -38
  19. package/src/dashboard/index.html +122 -90
  20. package/src/dashboard/language.js +791 -362
  21. package/src/dashboard/status.js +53 -41
  22. package/src/dashboard/ui.css +13 -0
  23. package/src/dashboard/ui.js +31 -28
  24. package/src/dashboard/usage.js +16 -16
  25. package/src/dashboard-api.mjs +2 -0
  26. package/src/doctor.mjs +4 -4
  27. package/src/http-transport.mjs +3 -2
  28. package/src/launcher.mjs +8 -8
  29. package/src/native-prediction.mjs +3 -3
  30. package/src/operation-error.mjs +12 -7
  31. package/src/package-update.mjs +43 -11
  32. package/src/prediction-retirement.mjs +2 -7
  33. package/src/provider-metadata.mjs +2 -1
  34. package/src/provider-registry.mjs +19 -0
  35. package/src/provider-runtime.mjs +42 -33
  36. package/src/provider-settings.mjs +2 -1
  37. package/src/release-install.mjs +192 -0
  38. package/src/response-failures.mjs +2 -1
  39. package/src/service-control.mjs +7 -8
  40. package/src/startup-ui.mjs +17 -9
  41. package/src/stream-performance.mjs +29 -1
  42. package/src/terminal-console.mjs +43 -15
  43. package/src/usage-store.mjs +10 -5
  44. package/src/user-settings.mjs +16 -3
  45. package/src/version.mjs +2 -6
  46. package/src/windows-command.mjs +13 -1
@@ -0,0 +1,192 @@
1
+ // Also shipped as the standalone bootstrap helper. Keep imports built-in only.
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { createRequire } from "node:module";
6
+ import { Readable } from "node:stream";
7
+ import { createHash } from "node:crypto";
8
+ import { gunzipSync } from "node:zlib";
9
+ import { execFileSync } from "node:child_process";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
+
12
+ export const RELEASE_BASE = "https://github.com/DaleXiao/codex-copilot-dx/releases/download";
13
+ export function stableVersion(tag) {
14
+ const match = typeof tag === "string" && tag.length <= 64 && /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(tag);
15
+ return match && match.slice(1).every(part => Number.isSafeInteger(Number(part))) ? match.slice(1).join(".") : null;
16
+ }
17
+ // Use the downloader already shipped with the selected npm, rather than adding
18
+ // a second runtime dependency or bypassing its proxy/CA/offline settings.
19
+ export function createNpmReleaseFetch(npmCli, { env = process.env, exec = execFileSync } = {}) {
20
+ try {
21
+ const npmFetch = createRequire(npmCli)("make-fetch-happen");
22
+ const keys = ["https-proxy", "proxy", "noproxy", "cafile", "strict-ssl", "offline"];
23
+ const output = exec(process.execPath, [npmCli, "config", "get", "--global", ...keys], {
24
+ env, encoding: "utf8", timeout: 5000, maxBuffer: 128 * 1024, stdio: ["ignore", "pipe", "pipe"] });
25
+ const values = Object.fromEntries(output.trim().split(/\r?\n/).map(line => /^(https-proxy|proxy|noproxy|cafile|strict-ssl|offline)=(.*)$/.exec(line)).filter(Boolean).map(match => [match[1], match[2]]));
26
+ if (values.offline === "true") throw new Error("offline");
27
+ const present = value => value && !["null", "undefined"].includes(value) ? value : undefined;
28
+ const caFile = present(values.cafile);let ca;
29
+ if (caFile) {
30
+ if (!fs.statSync(caFile).isFile() || fs.statSync(caFile).size > 1024 * 1024) throw new Error("CA file");
31
+ ca = fs.readFileSync(caFile, "utf8");
32
+ }
33
+ return async (url, options = {}) => {
34
+ try {
35
+ const response = await npmFetch(url, { ...options, retry: 0, cache: "no-store", ca,
36
+ proxy: present(values["https-proxy"]) || present(values.proxy) || env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY,
37
+ noProxy: present(values.noproxy) || env.no_proxy || env.NO_PROXY,
38
+ strictSSL: values["strict-ssl"] !== "false" });
39
+ const body = [204, 205, 304].includes(response.status) ? null : Readable.toWeb(Readable.from(response.body));
40
+ const result = new Response(body, { status: response.status, headers: Object.fromEntries(response.headers) });
41
+ Object.defineProperty(result, "url", { value: response.url });return result;
42
+ } catch { throw new Error("Release download failed. Check the configured npm proxy, CA file and approved GitHub access; no fallback was attempted."); }
43
+ };
44
+ } catch (error) {
45
+ if (error.message === "offline") throw new Error("npm offline mode is enabled. Use an approved local Release package/cache; no download was started.");
46
+ throw new Error("Could not use this npm's download component or network settings. Keep its proxy/CA policy; use an approved local Release package or a complete supported npm distribution.");
47
+ }
48
+ }
49
+
50
+ export async function releaseBytes(url, { fetchImpl = fetch, maxBytes, timeoutMs = 60000 } = {}) {
51
+ const response = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.timeout(timeoutMs), headers: { "User-Agent": "codex-copilot-dx", Accept: "application/octet-stream" } });
52
+ const final = response.url && new URL(response.url);
53
+ if (!response.ok || final && (final.protocol !== "https:" || !["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"].includes(final.hostname))) {
54
+ await response.body?.cancel();throw new Error(`Release download refused (HTTP ${response.status}). Check company proxy, certificates and approved download access. No fallback was attempted.`);
55
+ }
56
+ const chunks = [];let size = 0;
57
+ try {
58
+ for await (const chunk of response.body || []) {
59
+ size += chunk.length;if (size > maxBytes) throw new Error("Release download exceeds its size limit");chunks.push(chunk);
60
+ }
61
+ return Buffer.concat(chunks, size);
62
+ } catch (error) { throw new Error("Release download did not finish; the existing installation was preserved", { cause: error }); }
63
+ }
64
+ export function releaseChecksum(manifest, name) {
65
+ const lines = manifest.toString("utf8").split(/\r?\n/).filter(line => line.endsWith(` ${name}`));
66
+ if (lines.length !== 1 || !/^[a-f0-9]{64} [\w.-]+$/.test(lines[0])) throw new Error("Release checksum is missing or invalid");
67
+ return lines[0].slice(0, 64);
68
+ }
69
+ export function packageMetadata(bytes) {
70
+ const tar = gunzipSync(bytes, { maxOutputLength: 64 * 1024 * 1024 });
71
+ let metadata;
72
+ for (let offset = 0; offset + 512 <= tar.length;) {
73
+ const header = tar.subarray(offset, offset + 512), name = header.subarray(0, 100).toString().replace(/\0.*$/s, "");
74
+ if (!name) break;
75
+ const sizeText = header.subarray(124, 136).toString().replace(/\0.*$/s, "").trim();
76
+ if (!/^[0-7]+$/.test(sizeText)) throw new Error("Invalid release package header");
77
+ const size = Number.parseInt(sizeText, 8);
78
+ if (!Number.isSafeInteger(size) || offset + 512 + size > tar.length) throw new Error("Invalid release package size");
79
+ if (name === "package/package.json") {
80
+ if (metadata || size > 65536 || ![0, 48].includes(header[156])) throw new Error("Invalid release package metadata");
81
+ metadata = JSON.parse(tar.subarray(offset + 512, offset + 512 + size));
82
+ }
83
+ offset += 512 + Math.ceil(size / 512) * 512;
84
+ }
85
+ if (metadata?.name !== "codex-copilot-dx" || !stableVersion(metadata.version)) throw new Error("Release package identity is invalid");
86
+ return metadata;
87
+ }
88
+ export async function downloadRelease(tag, { fetchImpl = fetch, directory } = {}) {
89
+ const version = stableVersion(tag);if (!version) throw new Error("A valid stable GitHub release tag is required");
90
+ const name = `codex-copilot-dx-${version}.tgz`, base = `${RELEASE_BASE}/v${version}`;
91
+ const manifest = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536 });
92
+ const expected = releaseChecksum(manifest, name);
93
+ const bytes = await releaseBytes(`${base}/${name}`, { fetchImpl, maxBytes: 16 * 1024 * 1024 });
94
+ if (createHash("sha256").update(bytes).digest("hex") !== expected) throw new Error("Release checksum mismatch; no installation was started");
95
+ if (packageMetadata(bytes).version !== version) throw new Error("Release package version does not match its tag");
96
+ const file = path.join(directory, name);fs.writeFileSync(file, bytes, { flag: "wx", mode: 0o600 });return { file, name, version };
97
+ }
98
+
99
+ // Preserve only this package and its command entries. Never snapshot credentials
100
+ // or change npm settings. A busy/readonly Windows installation fails in place.
101
+ export function protectInstallation({ target, prefix, platform = process.platform } = {}) {
102
+ if (!target || !prefix) return { commit() {}, rollback() {} };
103
+ const parent = path.dirname(target);fs.mkdirSync(parent, { recursive: true });
104
+ const lock = path.join(parent, ".ccdx-install.lock");let fd;
105
+ try { fd = fs.openSync(lock, "wx", 0o600); } catch { throw new Error("Another install may be running. Check the CCDX install lock before retrying."); }
106
+ let backup;
107
+ try { backup = fs.mkdtempSync(path.join(parent, ".ccdx-backup-")); }
108
+ catch (error) { fs.closeSync(fd);fs.unlinkSync(lock);throw error; }
109
+ const entries = [target, ...["ccdx", "codex-copilot-dx"].flatMap(name => platform === "win32"
110
+ ? [name, `${name}.cmd`, `${name}.ps1`].map(file => path.join(prefix, file)) : [path.join(prefix, "bin", name)])];
111
+ const saved = [];
112
+ const clean = () => { fs.rmSync(backup, { recursive: true, force: true });fs.closeSync(fd);fs.unlinkSync(lock); };
113
+ try {
114
+ entries.forEach((file, index) => {
115
+ let stat;try { stat = fs.lstatSync(file); } catch (error) { if (error.code !== "ENOENT") throw error; }
116
+ if (file === target && stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error("The npm target is linked or not a regular installation; use its owning installer");
117
+ const copy = path.join(backup, String(index));
118
+ if (stat) fs.cpSync(file, copy, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true });
119
+ saved.push({ file, copy, existed: Boolean(stat) });
120
+ });
121
+ } catch (error) { clean();throw error; }
122
+ let finalized = false;
123
+ return {
124
+ commit() {
125
+ finalized = true;
126
+ try { clean(); }
127
+ catch { console.error(`CCDX was installed, but backup cleanup needs attention: ${backup}; check ${lock} before retrying.`); }
128
+ },
129
+ rollback() {
130
+ if (finalized) return;
131
+ try {
132
+ for (const { file, copy, existed } of saved) {
133
+ fs.rmSync(file, { recursive: true, force: true });
134
+ if (existed) fs.cpSync(copy, file, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true });
135
+ }
136
+ clean();
137
+ } catch (error) {
138
+ fs.closeSync(fd);
139
+ throw new Error(`Restore could not finish. Previous package and commands remain at ${backup}; do not delete the install lock until restored.`, { cause: error });
140
+ }
141
+ },
142
+ };
143
+ }
144
+
145
+ export function verifyPackageRuntime(target, version, { brokerRequired = false } = {}) {
146
+ const code = `const {createRequire}=require('node:module');const r=createRequire(${JSON.stringify(path.join(target, "package.json"))});const pkg=r('./package.json');if(pkg.name!=='codex-copilot-dx'||pkg.version!==${JSON.stringify(version)})throw Error('Version mismatch');r('sharp')({create:{width:1,height:1,channels:3,background:'white'}}).png().toBuffer().then(()=>{${brokerRequired ? "if(!r('@azure/msal-node-runtime').msalNodeRuntime)throw Error('Native broker unavailable');" : ""}}).catch(e=>{console.error(e.message);process.exitCode=1});`;
147
+ execFileSync(process.execPath, ["-e", code], { timeout: 30000, stdio: ["ignore", "pipe", "pipe"] });
148
+ const output = execFileSync(process.execPath, [path.join(target, "bin", "cli.mjs"), "version"], { encoding: "utf8", timeout: 15000, stdio: ["ignore", "pipe", "pipe"] });
149
+ if (!output.includes(`ccdx v${version} `)) throw new Error("Installed command version could not be verified");
150
+ }
151
+
152
+ export async function writePrivateLaunchers({ prefix, target }) {
153
+ const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
154
+ const windows = process.platform === "win32"
155
+ ? await import(pathToFileURL(path.join(target, "src", "windows-command.mjs")).href) : null;
156
+ for (const name of ["ccdx", "codex-copilot-dx"]) {
157
+ const cli = path.join(target, "bin", name === "ccdx" ? "cli.mjs" : "codex-copilot-dx.mjs");
158
+ if (windows) {
159
+ fs.writeFileSync(path.join(prefix, `${name}.cmd`), windows.privateWindowsCommand({ node: process.execPath, cli, prefix }));
160
+ } else {
161
+ const file = path.join(prefix, "bin", name);fs.rmSync(file, { force: true });
162
+ fs.writeFileSync(file, `#!/bin/sh\nPATH=${quote(path.dirname(process.execPath))}:"$PATH"\nexport PATH\nCCDX_PRIVATE_INSTALL_PREFIX=${quote(prefix)}\nexport CCDX_PRIVATE_INSTALL_PREFIX\nif [ -z "\${npm_config_prefix:-}\${NPM_CONFIG_PREFIX:-}" ]; then npm_config_prefix=${quote(prefix)}; export npm_config_prefix; fi\nexec ${quote(process.execPath)} ${quote(cli)} "$@"\n`, { mode: 0o755 });
163
+ }
164
+ }
165
+ if (windows && windows.inspectWindowsCommand({ packageRoot: target, repair: true }).status !== "ready") throw new Error("Private Windows commands could not be verified");
166
+ }
167
+
168
+ async function bootstrap() {
169
+ const [tag, prefix, npmCli, ...flags] = process.argv.slice(2);
170
+ const permission = flags.includes("--allow-remote"), privateRuntime = flags.includes("--private-runtime");
171
+ if (!stableVersion(tag) || !prefix || !path.isAbsolute(prefix) || !npmCli || !path.isAbsolute(npmCli) || flags.some(flag => !["--allow-remote", "--private-runtime"].includes(flag))) throw new Error("Use: node ccdx-install.mjs vVERSION /absolute/prefix /absolute/npm-cli.js [--allow-remote]");
172
+ const target = path.join(prefix, ...(process.platform === "win32" ? [] : ["lib"]), "node_modules", "codex-copilot-dx");
173
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "ccdx-install-"));let transaction;
174
+ try {
175
+ const release = await downloadRelease(tag, { directory, fetchImpl: createNpmReleaseFetch(npmCli) });
176
+ transaction = protectInstallation({ target, prefix });
177
+ const npmVersion = execFileSync(process.execPath, [npmCli, "--version"], { encoding: "utf8", timeout: 10000 }).trim();
178
+ const args = [npmCli, "install", "--global", "--prefix", prefix, "--ignore-scripts", "--no-audit", "--no-fund"];
179
+ if (permission && Number(npmVersion.split(".")[0]) >= 12) args.push("--allow-remote=all");
180
+ args.push(release.file);
181
+ execFileSync(process.execPath, args, { stdio: "inherit", timeout: 300000 });
182
+ verifyPackageRuntime(target, release.version, { brokerRequired: ["darwin", "win32"].includes(process.platform) });
183
+ if (privateRuntime || process.platform === "win32") await writePrivateLaunchers({ prefix, target });
184
+ transaction.commit();transaction = null;
185
+ console.log(`Installed CCDX ${release.version}. Existing services keep running until restarted.`);
186
+ } catch (error) {
187
+ transaction?.rollback();throw new Error("Installation failed. Previous CCDX package and commands were restored. Check approved registry, proxy, certificates and npm policy; dependencies still need registry access.", { cause: error });
188
+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }
189
+ }
190
+ if (process.argv[1] && path.basename(process.argv[1]) === "ccdx-install.mjs" && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
191
+ try { await bootstrap(); } catch (error) { console.error(error.message);if (error.cause) console.error(error.cause.message);process.exitCode = 1; }
192
+ }
@@ -1,6 +1,7 @@
1
1
  import { terminalCell } from "./terminal-text.mjs";
2
2
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
3
3
  import { currentRequestContext } from "./request-context.mjs";
4
+ import { isProviderId } from "./provider-metadata.mjs";
4
5
 
5
6
  const DEFAULT_RECENT_FAILURES = 10;
6
7
 
@@ -41,7 +42,7 @@ export function responseFailureDetails(event, eventType = event?.type, {
41
42
  return {
42
43
  at: new Date().toISOString(),
43
44
  request_id: currentRequestContext()?.requestId || null,
44
- ...(["github", "m365"].includes(provider) ? { provider } : {}),
45
+ ...(isProviderId(provider) ? { provider } : {}),
45
46
  event_type: safeIdentifier(eventType || "response.failed"),
46
47
  model: safeIdentifier(response?.model || model),
47
48
  code: safeIdentifier(error?.code || "unknown_error"),
@@ -1,4 +1,4 @@
1
- import { readUserSettings, servicePreferences, writeServicePreference, terminalAnimationPreference,
1
+ import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
2
2
  writeTerminalAnimationTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib } from "./user-settings.mjs";
3
3
  import { readImageProviderConfig } from "./image-provider-config.mjs";
4
4
  import { readPredictionSettings } from "./native-prediction-profile.mjs";
@@ -10,12 +10,11 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
10
10
  const options = { env, home };
11
11
  let serial = Promise.resolve();
12
12
  function snapshot() {
13
- readUserSettings({ ...options, strict: true });
14
- const saved = servicePreferences(options), prediction = clientIntegration?.snapshot().prediction;
13
+ const { saved, theme, historyLimit } = serviceSettingsSnapshot(options), prediction = clientIntegration?.snapshot().prediction;
15
14
  let imageConfigured = false, predictionConfigured = false;
16
15
  try { imageConfigured = Boolean(readImages()); } catch {}
17
16
  try { predictionConfigured = readPrediction().enabled === true; } catch {}
18
- return { source: "service_settings", saved, theme: terminalAnimationPreference(options).theme,
17
+ return { source: "service_settings", saved, theme,
19
18
  effective: {
20
19
  terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
21
20
  state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
@@ -23,14 +22,14 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
23
22
  image_enabled: { value: saved.image_enabled && imageConfigured, state: imageConfigured ? "next_call" : "needs_setup", configured: imageConfigured },
24
23
  prediction_enabled: { value: prediction?.active === true, state: !predictionConfigured ? "needs_setup"
25
24
  : prediction?.environment?.status === "needs_app_relaunch" ? "needs_app_relaunch" : prediction?.bridge !== "running" ? "needs_service_restart" : "next_config_request", configured: predictionConfigured },
26
- }, history: { ...responseHistoryLimitPreference(options), ...cacheRuntimeSnapshot().response_history },
25
+ }, history: { ...historyLimit, ...cacheRuntimeSnapshot().response_history },
27
26
  providers: providerRuntime?.snapshot() || null, terminal: terminal?.snapshot?.() || null };
28
27
  }
29
28
  async function apply(input) {
30
29
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
31
30
  const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"],
32
31
  history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
33
- provider: ["action", "operation", "provider", "model", "auto_review_model"] }[input.action];
32
+ provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort"] }[input.action];
34
33
  if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
35
34
  if (input.action === "preference") {
36
35
  writeServicePreference(input.key, input.value, options);
@@ -50,9 +49,9 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
50
49
  try { writeResponseHistoryLimitMib(input.mib, options); } catch (error) { setHistoryCacheLimit(before);throw error; }
51
50
  } else if (input.action === "history_clean") cleanRuntimeCaches({ history: true });
52
51
  else {
53
- if (!providerRuntime || !["on", "off", "switch"].includes(input.operation)) throw new Error("Invalid provider operation");
52
+ if (!providerRuntime || !["on", "off", "switch", "auto-review"].includes(input.operation)) throw new Error("Invalid provider operation");
54
53
  if (input.operation === "on" && env.CCDX_M365 === "0") throw new Error("Microsoft 365 is disabled by CCDX_M365=0");
55
- await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model });
54
+ await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort, effort: input.auto_review_effort });
56
55
  }
57
56
  return snapshot();
58
57
  }
@@ -26,7 +26,7 @@ export function startupCheck(kind, name, detail) {
26
26
  }
27
27
 
28
28
  export function startupReady({ baseUrl, commandName = "ccdx", reused = false } = {}) {
29
- return ["", startupCheck("ok", "Ready", reused ? "Using the existing CCDX adapter" : "Core service available"), "",
29
+ return ["", startupCheck("ok", "Ready", reused ? "Using the running service" : "Local service ready"), "",
30
30
  `Web UI ${baseUrl}`, `Help ${commandName} help`, ...(!reused ? ["Stop Ctrl+C"] : []), ""].join("\n");
31
31
  }
32
32
 
@@ -40,15 +40,15 @@ export function startupLogger(name, output = console.log) {
40
40
  }
41
41
 
42
42
  export function predictionStartupCheck(prediction) {
43
- if (!prediction?.configured) return startupCheck("info", "Prediction", "Off");
43
+ if (!prediction?.configured) return startupCheck("info", "Suggestions", "Off");
44
44
  const environment = prediction.environment?.status;
45
45
  const problem = ["unavailable", "needs_service_restart", "needs_app_relaunch"].includes(environment);
46
46
  let detail = prediction.bridge !== "running" ? prediction.bridge === "recovering" ? "Bridge recovering" : "Bridge unavailable"
47
47
  : prediction.active === false ? "Paused; trust and route retained"
48
- : `Running; App route ${prediction.launch_route === "verified" ? "verified" : prediction.launch_route === "persisted" ? "saved, not verified" : "not verified"}; suggestion unchecked`;
48
+ : "Running; suggestion display not verified";
49
49
  if (problem) detail += environment === "needs_service_restart" ? "; restart CCDX" : environment === "needs_app_relaunch" ? "; relaunch Codex" : "; environment unavailable";
50
50
  const warning = prediction.bridge !== "running" || problem || prediction.launch_route === "unverified";
51
- const lines = [startupCheck(warning ? "warn" : "info", "Prediction", detail)];
51
+ const lines = [startupCheck(warning ? "warn" : "info", "Suggestions", detail)];
52
52
  if (prediction.bridge !== "running" && prediction.reason) lines.push(startupCheck("warn", "Reason", prediction.reason));
53
53
  if (warning) lines.push(startupCheck("info", "Details", "ccdx prediction status"));
54
54
  return lines.join("\n");
@@ -64,16 +64,24 @@ export function providerStartupSummary(data = {}) {
64
64
  const catalog = (name, value) => `${name} ${value.models ?? value.total} (${value.source})`;
65
65
  const m365State = { disabled: "off", unsupported: "unsupported", checking: "checking", idle: "not checked", unavailable: "unavailable", ready: "ready" }[ms?.state] || "unknown";
66
66
  const count = Number(githubFound) + Number(m365Found);
67
- const catalogs = `${count} catalog${count === 1 ? "" : "s"} found / ${githubFound ? catalog("GitHub", github) : github ? "GitHub not discovered" : "GitHub not checked"}; ${m365Found ? `${catalog("M365", ms.models)}${ms.state !== "ready" ? `, ${m365State}` : ""}` : `M365 ${m365State}`}`;
68
- const states = { configured: "configured", partially_preserved: "partly configured; custom settings kept", preserved: "custom/managed settings kept", not_installed: "not installed", configuration_unavailable: "config unreadable", not_configured: "not checked" };
67
+ const sourceLines = [`${count} source${count === 1 ? "" : "s"} with model lists`,
68
+ githubFound ? catalog("GitHub", github) : github ? "GitHub not discovered" : "GitHub not checked",
69
+ m365Found ? `${catalog("M365", ms.models)}${ms.state !== "ready" ? `, ${m365State}` : ""}` : `M365 ${m365State}`];
70
+ const catalogs = `${sourceLines[0]} / ${sourceLines.slice(1).join("; ")}`;
71
+ const states = { configured: "configured", restored: "settings restored", partially_preserved: "partly configured; custom settings kept", preserved: "custom/managed settings kept", not_installed: "not installed", configuration_unavailable: "config unreadable", not_configured: "not checked" };
69
72
  const client = id => states[ms?.claude?.clients?.[id]] || "not checked";
70
73
  const gatewayReason = ms?.claude?.reason === "m365_no_claude_models" ? "no Claude models" : m365State;
71
- const gateway = ms?.claude?.gateway === "running" ? "gateway running" : `gateway off (${gatewayReason})`;
74
+ const gateway = ms?.claude?.gateway === "running" ? "local service running" : `local service off (${gatewayReason})`;
72
75
  const claude = `Code: ${client("code")} / App: ${client("app")} / ${gateway}`;
73
- return { catalogs, claude, warning: Object.values(ms?.claude?.clients || {}).includes("configuration_unavailable") };
76
+ const shortStates = { configured: "set", restored: "restored", partially_preserved: "partial", preserved: "custom kept", not_installed: "not installed", configuration_unavailable: "unreadable" };
77
+ return { catalogs, claude, sourceLines, claudeLines: [`Claude Code: ${client("code")}`, `Claude App: ${client("app")}`, gateway],
78
+ compactSources: [`Lists ${count} / ${githubFound ? catalog("GitHub", github) : "GitHub not checked"}`, m365Found ? catalog("M365", ms.models) : `M365 ${m365State}`],
79
+ compactClaude: [`Code: ${shortStates[ms?.claude?.clients?.code] || "unchecked"} / App: ${shortStates[ms?.claude?.clients?.app] || "unchecked"}`,
80
+ ms?.claude?.gateway === "running" ? "Claude service: running" : `Claude service: off (${gatewayReason})`],
81
+ warning: Object.values(ms?.claude?.clients || {}).includes("configuration_unavailable") };
74
82
  }
75
83
 
76
84
  export function providerStartupChecks(data) {
77
85
  const summary = providerStartupSummary(data);
78
- return `${startupCheck("info", "Providers", summary.catalogs)}\n${startupCheck(summary.warning ? "warn" : "info", "Claude", summary.claude)}`;
86
+ return `${startupCheck("info", "Sources", summary.catalogs)}\n${startupCheck(summary.warning ? "warn" : "info", "Claude", summary.claude)}`;
79
87
  }
@@ -1,5 +1,6 @@
1
1
  import { performance } from "node:perf_hooks";
2
2
  import { currentRequestContext } from "./request-context.mjs";
3
+ import { isProviderId } from "./provider-metadata.mjs";
3
4
 
4
5
  const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
5
6
  const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
@@ -11,6 +12,7 @@ const TERMINAL_ORIGINS = new Set([
11
12
  ]);
12
13
  const MAX_MODEL_OUTCOME_LABELS = 32;
13
14
  const MAX_RECENT_REQUESTS = 20;
15
+ const MAX_PROVIDER_LABELS = 16;
14
16
  const PREPARATION_EDGES_MS = Object.freeze([1, 2, 5, 10, 20, 50, 100, 250, 500, 1_000, 5_000, 30_000, 120_000]);
15
17
  const TTFT_EDGES_MS = Object.freeze([
16
18
  100, 200, 300, 500, 700, 1_000, 1_400, 2_000, 2_800, 4_000,
@@ -146,6 +148,7 @@ function createRoutePerformance() {
146
148
  incompleteReasons: Object.create(null),
147
149
  terminalByModel: new Map(),
148
150
  terminalByOrigin: Object.create(null),
151
+ providers: new Map(),
149
152
  };
150
153
  }
151
154
 
@@ -162,6 +165,12 @@ function routeSnapshot(route) {
162
165
  by_model: Object.fromEntries([...route.terminalByModel].map(([model, counts]) => [model, { ...counts }])),
163
166
  by_origin: Object.fromEntries(Object.entries(route.terminalByOrigin).map(([origin, counts]) => [origin, { ...counts }])),
164
167
  },
168
+ by_provider: Object.fromEntries([...route.providers].map(([id, source]) => [id, {
169
+ requests: source.requests, active: source.active, finished: source.finished,
170
+ terminal_outcomes: { totals: { ...source.totals }, by_model: Object.fromEntries([...source.models].map(([model, counts]) => [model, { ...counts }])) },
171
+ request_ttft_ms: histogramSnapshot(source.ttft, "ms"),
172
+ preparation_ms: Object.fromEntries(PREPARATION_STAGES.map(stage => [stage, histogramSnapshot(source.preparation[stage], "ms")])),
173
+ }])),
165
174
  ttft_ms: histogramSnapshot(route.ttft, "ms"),
166
175
  tpot_us: histogramSnapshot(route.tpot, "us"),
167
176
  output_tokens_per_second: {
@@ -197,6 +206,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
197
206
  let finished = false;
198
207
  let model = "other";
199
208
  let provider = null;
209
+ let sourceStats = null;
200
210
  let terminalOutcome = null;
201
211
  let terminalOrigin = null;
202
212
  let incompleteReason = null;
@@ -212,6 +222,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
212
222
  let terminalAt = null;
213
223
  const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null };
214
224
  const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
225
+ const assignProvider = value => {
226
+ if (finished || sourceStats || !isProviderId(value)) return;
227
+ provider = value;
228
+ const label = route.providers.has(value) || route.providers.size < MAX_PROVIDER_LABELS ? value : "other";
229
+ if (!route.providers.has(label)) route.providers.set(label, { requests: 0, active: 0, finished: 0, totals: emptyOutcomes(), models: new Map(),
230
+ ttft: createHistogram(TTFT_EDGES_MS), preparation: Object.fromEntries(PREPARATION_STAGES.map(stage => [stage, createHistogram(PREPARATION_EDGES_MS)])) });
231
+ sourceStats = route.providers.get(label);sourceStats.requests++;sourceStats.active++;
232
+ };
215
233
 
216
234
  return {
217
235
  beginStage(stage) {
@@ -261,13 +279,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
261
279
  }
262
280
  },
263
281
  setOutputTokens(value) {
282
+ if (value === null || value === undefined) return;
264
283
  const tokens = Number(value);
265
284
  if (Number.isFinite(tokens) && tokens >= 0) outputTokens = tokens;
266
285
  },
267
286
  setModel(value) {
268
287
  model = modelLabel(value);
269
288
  },
270
- setProvider(value) { if (["github", "m365"].includes(value)) provider = value; },
289
+ setProvider: assignProvider,
271
290
  attemptCount() { return attempts; },
272
291
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
273
292
  observeContext(values) {
@@ -294,6 +313,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
294
313
  },
295
314
  finish({ failed: finishFailed = false, aborted = false, statusCode = 0 } = {}) {
296
315
  if (finished) return;
316
+ if (!sourceStats) assignProvider("unknown");
297
317
  finished = true;
298
318
  failed ||= finishFailed;
299
319
  const outcome = terminalOutcome || (aborted ? "cancelled" : "unknown");
@@ -309,6 +329,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
309
329
  route.terminalByModel.get(label)[outcome] += 1;
310
330
  route.terminalByOrigin[origin] ||= emptyOutcomes();
311
331
  route.terminalByOrigin[origin][outcome] += 1;
332
+ if (sourceStats) {
333
+ sourceStats.active--;sourceStats.finished++;sourceStats.totals[outcome]++;
334
+ const sourceModel = sourceStats.models.has(model) || sourceStats.models.size < MAX_MODEL_OUTCOME_LABELS ? model : "other";
335
+ if (!sourceStats.models.has(sourceModel)) sourceStats.models.set(sourceModel, emptyOutcomes());
336
+ sourceStats.models.get(sourceModel)[outcome]++;
337
+ if (firstOutputAt !== null) observe(sourceStats.ttft, Math.max(0, firstOutputAt - requestStartedAt));
338
+ for (const stage of PREPARATION_STAGES) observe(sourceStats.preparation[stage], preparationMs[stage]);
339
+ }
312
340
  const finishedAt = now();
313
341
  // Only scalar, allowlisted metadata survives the request; never retain payloads.
314
342
  recentRequests.push({
@@ -15,7 +15,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
15
15
  timers = { setTimeout, clearTimeout }, now = Date.now } = {}) {
16
16
  let running = false, timer = null, lines = 0, active = 0, frame = 0, lastRead = 0, data = {};
17
17
  let notices = 0, lastNotice = "", lastPrintedNotice = "", previous = [];
18
- let content = [], dirty = true;
18
+ let content = [], dirty = true, readFailed = false, updatedAt = null, fits = true;
19
19
  let current = { theme: DEFAULT_TERMINAL_ANIMATION_THEME, terminal_animation_enabled: true };
20
20
  let frameDelay = 1000;
21
21
  const tty = output.isTTY === true && errorOutput.isTTY === true && (!env.CI || flagOff(env.CI)) && env.TERM !== "dumb";
@@ -32,19 +32,29 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
32
32
  };
33
33
  const numbers = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
34
34
  const compact = value => numbers.format(Number(value) || 0);
35
- function table(width, usage, requests, inferenceActive, sum) {
35
+ const wrap = (value, width) => {
36
+ const rows = [];let row = "";
37
+ for (const word of terminalCell(value, { fallback: "" }).split(/\s+/)) {
38
+ if (row && displayWidth(`${row} ${word}`) > width) { rows.push(row);row = ""; }
39
+ row += `${row ? " " : ""}${word}`;
40
+ }
41
+ if (row) rows.push(clip(row, width));return rows;
42
+ };
43
+ function table(width, usage, requests, inferenceActive, sum, compactTitle = false) {
36
44
  const left = Math.floor((width - 3) / 2), right = width - 3 - left;
37
45
  const cell = (label, value, size) => {
38
- const number = value === undefined ? "" : compact(value), inner = size - 2;
46
+ const number = value === undefined ? "" : updatedAt === null && readFailed ? "—" : compact(value), inner = size - 2;
39
47
  const text = clip(label, Math.max(0, inner - displayWidth(number) - (number ? 1 : 0)));
40
48
  return ` ${text}${" ".repeat(Math.max(0, inner - displayWidth(text) - displayWidth(number)))}${number} `;
41
49
  };
42
50
  const row = (a, b) => `│${a}│${b}│`;
43
51
  const rule = (a, b, c) => `${a}${"─".repeat(left)}${b}${"─".repeat(right)}${c}`;
44
- const usageRows = [["Records", usage.records || 0], ["Input total", usage.input_tokens], ["Cache read", usage.cached_input_tokens],
45
- ["Output", usage.output_tokens], ["Partial records", usage.partial_records || 0], ["", undefined]];
46
- const requestRows = [["HTTP calls", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
47
- return [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell("Inference", undefined, right)), rule("├", "┼", "┤"),
52
+ const usageRows = [[left < 23 ? "Records" : "Usage records", usage.records || 0], ["Input", usage.input_tokens], [left < 23 ? "Reused" : "Reused input", usage.cached_input_tokens],
53
+ ["Output", usage.output_tokens], ["Partial usage", usage.partial_records || 0], ["", undefined]];
54
+ const requestRows = [["Requests", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
55
+ const title = compactTitle ? [`┌─ Usage ${"─".repeat(left - 8)}┬─ Inference ${"─".repeat(right - 12)}┐`]
56
+ : [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell("Inference", undefined, right)), rule("├", "┼", "┤")];
57
+ return [...title,
48
58
  ...usageRows.map(([label, value], index) => row(cell(label, value ?? (label ? 0 : undefined), left), cell(...requestRows[index], right))), rule("└", "┴", "┘")];
49
59
  }
50
60
  function render() {
@@ -68,16 +78,29 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
68
78
  const requests = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.total || 0), 0);
69
79
  const inferenceActive = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.active || 0), 0);
70
80
  const providers = providerStartupSummary(data);
71
- content = [`CCDX RUNNING / uptime ${Math.floor((data.uptime_ms || 0) / 60000)}m / ${baseUrl}`,
72
- `Providers / ${providers.catalogs}`, `Claude / ${providers.claude}`].map(line => clip(line, width));
81
+ const heading = readFailed ? updatedAt === null ? "CCDX / No data received" : `CCDX / ${width < 80 ? "Previous data" : "Showing previous data / updated"} / ${new Date(updatedAt).toLocaleTimeString("en-GB")}`
82
+ : `CCDX RUNNING / uptime ${Math.floor((data.uptime_ms || 0) / 60000)}m / ${baseUrl}`;
83
+ content = [clip(heading, width)];
84
+ for (const group of [[`Sources / ${providers.catalogs}`, providers.sourceLines], [`Claude / ${providers.claude}`, providers.claudeLines]]) {
85
+ content.push(...(displayWidth(group[0]) <= width ? [group[0]] : (group[1] || [group[0]]).flatMap(line => wrap(line, width))));
86
+ }
73
87
  content.push(...table(width, usage, requests, inferenceActive, sum));
74
- content.push(clip(`${notices} notices${lastNotice ? ` / latest: ${lastNotice}` : " / details in WebUI"}`, width));
88
+ content.push(clip(`${notices} notices${lastNotice ? ` · latest: ${lastNotice}` : " / details in WebUI"}`, width));
89
+ if (content.length + 1 >= (Number(output.rows) || 24)) {
90
+ const summaries = [...(providers.compactSources || ["Sources: not checked"]), ...(providers.compactClaude || ["Claude: not checked"])];
91
+ content = [clip(heading, width), ...summaries.flatMap(line => wrap(line, width)), ...table(width, usage, requests, inferenceActive, sum, true), content.at(-1)];
92
+ }
75
93
  dirty = false;
76
94
  }
77
95
  const body = [...content, `${motion} ${active ? "Working" : "Idle"}`];
96
+ fits = body.length < (Number(output.rows) || 24);
97
+ if (!fits) { frameDelay = 1000;return; }
78
98
  // Animation ticks update only the final line; data stays on its 1s cadence.
79
99
  let update = "";
80
- if (!lines) update = `${body.map(line => clear + line).join("\n")}\r`;
100
+ if (lines && lines !== body.length) {
101
+ update = `${lines > 1 ? `\x1b[${lines - 1}A` : ""}\r\x1b[J`;lines = 0;previous = [];
102
+ }
103
+ if (!lines) update += `${body.map(line => clear + line).join("\n")}\r`;
81
104
  else for (let index = 0; index < body.length; index++) {
82
105
  if (body[index] === previous[index]) continue;
83
106
  const offset = body.length - 1 - index;
@@ -89,7 +112,11 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
89
112
  function tick() {
90
113
  if (!running) return;
91
114
  if (now() - lastRead >= 1000 || !lastRead) {
92
- try { data = snapshot();current = { ...current, ...preferences() };if (!isTerminalAnimationTheme(current.theme)) current.theme = DEFAULT_TERMINAL_ANIMATION_THEME; } catch {}
115
+ try {
116
+ const next = snapshot(), nextPreferences = preferences();
117
+ data = next;current = { ...current, ...nextPreferences };readFailed = false;updatedAt = now();
118
+ if (!isTerminalAnimationTheme(current.theme)) current.theme = DEFAULT_TERMINAL_ANIMATION_THEME;
119
+ } catch { readFailed = true; }
93
120
  lastRead = now();
94
121
  dirty = true;
95
122
  }
@@ -97,7 +124,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
97
124
  timer = timers.setTimeout(tick, frameDelay);timer?.unref?.();
98
125
  }
99
126
  return {
100
- get enabled() { return supported() && !verbose; },
127
+ get enabled() { return supported() && fits && !verbose; },
101
128
  start() { if (running) return;running = true;tick(); },
102
129
  beginRequest() { active++;dirty = true;let done = false;return () => { if (!done) { done = true;active = Math.max(0, active - 1);dirty = true; } }; },
103
130
  log(method, args) {
@@ -105,9 +132,10 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
105
132
  if (verbose) { (method === "error" || method === "warn" ? errorOutput : output).write(`${message}\n`);return; }
106
133
  if (method !== "error" && method !== "warn" && !/^\[(WARN|ERR)\]/.test(message.trim())) return;
107
134
  notices++;lastNotice = message.replace(/\s+/g, " ").slice(0, 240);dirty = true;
108
- if (!supported() && lastNotice !== lastPrintedNotice) { errorOutput.write(`${lastNotice}\n`);lastPrintedNotice = lastNotice; }
135
+ if ((!supported() || !fits) && lastNotice !== lastPrintedNotice) { errorOutput.write(`${lastNotice}\n`);lastPrintedNotice = lastNotice; }
109
136
  },
110
- snapshot() { return { notices, last_notice: lastNotice || null, mode: verbose ? "verbose" : supported() ? "status" : "plain" }; },
137
+ snapshot() { return { notices, last_notice: lastNotice || null, mode: verbose ? "verbose" : supported() && fits ? "status" : "plain",
138
+ data_state: readFailed ? updatedAt === null ? "unavailable" : "stale" : updatedAt === null ? "unknown" : "current", updated_at: updatedAt === null ? null : new Date(updatedAt).toISOString() }; },
111
139
  apply(value) { if (value.theme && value.theme !== current.theme) frame = 0;current = { ...current, ...value };lastRead = 0; },
112
140
  cleanup() { running = false;if (timer) timers.clearTimeout(timer);timer = null;if (lines) output.write("\n");lines = 0;output.off?.("resize", resized); },
113
141
  };
@@ -25,8 +25,9 @@ let pendingBytes = 0;
25
25
  let droppedRecords = 0;
26
26
  let writeFailures = 0;
27
27
  const runtimeUsage = { since: new Date().toISOString(), records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 };
28
+ const runtimeUsageByProvider = new Map();
28
29
 
29
- export function runtimeUsageSnapshot() { return { ...runtimeUsage }; }
30
+ export function runtimeUsageSnapshot() { return { ...runtimeUsage, by_provider: Object.fromEntries([...runtimeUsageByProvider].map(([id, totals]) => [id, { ...totals }])) }; }
30
31
 
31
32
  export function usageLoggingStats() {
32
33
  return { pending_records: pendingRecords, pending_bytes: pendingBytes, dropped_records: droppedRecords,
@@ -185,11 +186,15 @@ function scheduleUsageWriteDrain() {
185
186
  export function recordUsage(record) {
186
187
  if (!record) return Promise.resolve();
187
188
  const usage = record.usage || {};
188
- runtimeUsage.records++;
189
- for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cacheReadTokens(usage)], ["output_tokens", usage.output_tokens]]) {
190
- if (Number.isFinite(value) && value >= 0) runtimeUsage[target] += value;
189
+ const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 16 ? provider : "other";
190
+ if (!runtimeUsageByProvider.has(label)) runtimeUsageByProvider.set(label, { records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 });
191
+ for (const totals of [runtimeUsage, runtimeUsageByProvider.get(label)]) {
192
+ totals.records++;
193
+ for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cacheReadTokens(usage)], ["output_tokens", usage.output_tokens]]) {
194
+ if (Number.isFinite(value) && value >= 0) totals[target] += value;
195
+ }
196
+ if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cacheReadTokens(usage) === undefined) totals.partial_records++;
191
197
  }
192
- if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cacheReadTokens(usage) === undefined) runtimeUsage.partial_records++;
193
198
  if (process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
194
199
  const filePath = usageLogPath();
195
200
  const line = `${JSON.stringify(record)}\n`;
@@ -116,7 +116,15 @@ export function savedAutoReviewModel(options = {}) {
116
116
 
117
117
  export function servicePreferences(options = {}) {
118
118
  const settings = readUserSettings({ ...options, strict: true });
119
- return Object.fromEntries(SERVICE_FLAGS.map(key => [key, settings[key] !== false]));
119
+ return serviceFlags(settings);
120
+ }
121
+ const serviceFlags = settings => Object.fromEntries(SERVICE_FLAGS.map(key => [key, settings[key] !== false]));
122
+
123
+ // One strict read gives each status update a coherent view; no stale cache.
124
+ export function serviceSettingsSnapshot(options = {}) {
125
+ const settings = readUserSettings({ ...options, strict: true });
126
+ return { saved: serviceFlags(settings), theme: animationPreference(settings).theme,
127
+ historyLimit: historyLimitPreference(settings, options.env || process.env) };
120
128
  }
121
129
 
122
130
  export function writeServicePreference(key, value, options = {}) {
@@ -150,17 +158,22 @@ export function savedTerminalAnimationTheme(options = {}) {
150
158
  }
151
159
 
152
160
  export function terminalAnimationPreference({ env = process.env, home = os.homedir() } = {}) {
153
- const savedTheme = savedTerminalAnimationTheme({ env, home });
161
+ return animationPreference(readUserSettings({ env, home }));
162
+ }
163
+ function animationPreference(settings) {
164
+ const savedTheme = isTerminalAnimationTheme(settings[TERMINAL_ANIMATION_KEY]) ? settings[TERMINAL_ANIMATION_KEY] : "";
154
165
  if (savedTheme) return { theme: savedTheme, source: "settings" };
155
166
  return { theme: DEFAULT_TERMINAL_ANIMATION_THEME, source: "default" };
156
167
  }
157
168
 
158
169
  export function responseHistoryLimitPreference({ env = process.env, home = os.homedir() } = {}) {
170
+ return historyLimitPreference(readUserSettings({ env, home }), env);
171
+ }
172
+ function historyLimitPreference(settings, env) {
159
173
  const environment = String(env.CCDX_RESPONSE_HISTORY_MAX_BYTES || "").trim();
160
174
  if (environment) {
161
175
  return { bytes: loadRuntimeConfig(env).responseHistoryMaxBytes, source: "environment" };
162
176
  }
163
- const settings = readUserSettings({ env, home });
164
177
  const mib = settings[RESPONSE_HISTORY_MAX_MIB_KEY];
165
178
  if (Number.isSafeInteger(mib)) return { bytes: mib * MIB, mib, source: "settings" };
166
179
  return { bytes: RESPONSE_HISTORY_DEFAULT_MIB * MIB, mib: RESPONSE_HISTORY_DEFAULT_MIB, source: "default" };