codex-copilot-dx 1.0.0 → 1.1.0

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/src/log.mjs CHANGED
@@ -54,18 +54,19 @@ export function configureLogging({
54
54
  } = {}) {
55
55
  const level = normalizeLogLevel(env.CCDX_LOG_LEVEL);
56
56
  const filePath = resolveLogPath(env.CCDX_LOG_PATH, { home });
57
- if (!filePath) return { level, filePath: null, cleanup: () => {} };
58
57
  if (consoleObj === console && globalInstall) {
59
58
  return { level, ...globalInstall };
60
59
  }
61
60
 
62
- fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
61
+ if (filePath) fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
62
+ let terminalSink = null;
63
63
 
64
64
  const methods = ["log", "warn", "error", "debug"];
65
65
  const originals = Object.fromEntries(methods.map((method) => [
66
66
  method,
67
67
  typeof consoleObj[method] === "function" ? consoleObj[method].bind(consoleObj) : () => {},
68
68
  ]));
69
+ const present = (method, args) => terminalSink ? terminalSink(method, args) : originals[method](...args);
69
70
  let writeFailed = false;
70
71
  const pending = [];
71
72
  let drain = null;
@@ -73,7 +74,7 @@ export function configureLogging({
73
74
  let pendingRecords = 0;
74
75
  let droppedRecords = 0;
75
76
  let writeFailures = 0;
76
- const stats = () => ({ enabled: true, pending_bytes: pendingBytes, pending_records: pendingRecords,
77
+ const stats = () => ({ enabled: Boolean(filePath), pending_bytes: pendingBytes, pending_records: pendingRecords,
77
78
  dropped_records: droppedRecords, write_failures: writeFailures,
78
79
  max_bytes: LOG_QUEUE_MAX_BYTES, max_records: LOG_QUEUE_MAX_RECORDS });
79
80
 
@@ -86,7 +87,7 @@ export function configureLogging({
86
87
  await appendLines(filePath, batch.map(({ payload }) => payload), debugLogMaxBytes(env));
87
88
  } catch (error) {
88
89
  writeFailures += 1;
89
- if (!writeFailed) originals.error(`codex-copilot-dx log write failed: ${redactDiagnosticText(error.message)}`);
90
+ if (!writeFailed) present("error", [`codex-copilot-dx log write failed: ${redactDiagnosticText(error.message)}`]);
90
91
  writeFailed = true;
91
92
  } finally {
92
93
  pendingRecords -= batch.length;
@@ -102,7 +103,7 @@ export function configureLogging({
102
103
  const bytes = Buffer.byteLength(payload);
103
104
  if (pendingRecords >= LOG_QUEUE_MAX_RECORDS || pendingBytes + bytes > LOG_QUEUE_MAX_BYTES) {
104
105
  droppedRecords += 1;
105
- if (droppedRecords === 1) originals.error("codex-copilot-dx log queue is full; excess file records are dropped, terminal output is unchanged (see ccdx status)");
106
+ if (droppedRecords === 1) present("error", ["codex-copilot-dx log queue is full; excess file records are dropped (see ccdx status)"]);
106
107
  return;
107
108
  }
108
109
  pending.push({ payload, bytes });
@@ -112,14 +113,14 @@ export function configureLogging({
112
113
  } catch (e) {
113
114
  if (writeFailed) return;
114
115
  writeFailed = true;
115
- originals.error(`codex-copilot-dx log write failed: ${redactDiagnosticText(e.message)}`);
116
+ present("error", [`codex-copilot-dx log write failed: ${redactDiagnosticText(e.message)}`]);
116
117
  }
117
118
  }
118
119
 
119
120
  for (const method of methods) {
120
121
  consoleObj[method] = (...args) => {
121
- originals[method](...args);
122
- append(args);
122
+ present(method, args);
123
+ if (filePath) append(args);
123
124
  };
124
125
  }
125
126
 
@@ -130,7 +131,7 @@ export function configureLogging({
130
131
  new Promise((resolve) => { timer = setTimeout(() => resolve(false), timeoutMs); }),
131
132
  ]);
132
133
  clearTimeout(timer);
133
- if (!completed) originals.error(`codex-copilot-dx log flush timed out after ${timeoutMs}ms`);
134
+ if (!completed) present("error", [`codex-copilot-dx log flush timed out after ${timeoutMs}ms`]);
134
135
  };
135
136
  const cleanup = () => {
136
137
  for (const method of methods) consoleObj[method] = originals[method];
@@ -138,8 +139,9 @@ export function configureLogging({
138
139
  return flush();
139
140
  };
140
141
 
141
- if (consoleObj === console) globalInstall = { filePath, cleanup, flush, stats };
142
- return { level, filePath, cleanup, flush, stats };
142
+ const setTerminalSink = sink => { terminalSink = typeof sink === "function" ? sink : null; };
143
+ if (consoleObj === console) globalInstall = { filePath, cleanup, flush, stats, setTerminalSink };
144
+ return { level, filePath, cleanup, flush, stats, setTerminalSink };
143
145
  }
144
146
 
145
147
  export function debugLog(message, env = process.env) {
@@ -6,8 +6,6 @@ import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
6
6
  import { readBoundedFileSync } from "./bounded-file.mjs";
7
7
  import { withFileLockSync } from "./lock.mjs";
8
8
 
9
- export const M365_GATEWAY_PORT = 2027;
10
-
11
9
  export function m365Paths({ home = os.homedir() } = {}) {
12
10
  const directory = path.join(home, ".local", "share", "codex-copilot-dx", "profiles", "m365");
13
11
  return { directory, settings: path.join(directory, "settings.json"), account: path.join(directory, "account.json"),
@@ -35,6 +35,7 @@ export function supervisePrediction({ native, restart, state, warning = () => {}
35
35
  check,
36
36
  healthy() { return !closed && current.healthy(); },
37
37
  enabled() { return !closed && current.enabled?.() !== false; },
38
+ setActive(value) { return !closed && (current.setActive?.(value) ?? false); },
38
39
  appCurrent() { return current.appCurrent?.() !== false; },
39
40
  inspectEnvironment() { return current.inspectEnvironment?.(); },
40
41
  routeProcessId() { return current.routeProcessId?.(); },
@@ -10,6 +10,7 @@ import { windowsProxyText, windowsPredictionAppProcesses } from "./native-predic
10
10
  import { updatePredictionRoute } from "./native-prediction-route.mjs";
11
11
  import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
12
12
  import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
13
+ import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
13
14
 
14
15
  function certificateDirectory(settings, paths) {
15
16
  if (!settings.credentialsDirectory) return paths.directory;
@@ -55,6 +56,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
55
56
  }
56
57
  if (action === "status") {
57
58
  output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (default: off)`);
59
+ if (settings.enabled && !servicePreferences(opts).prediction_enabled) output("Prediction configuration adaptation: paused by the WebUI preference; trust and route are retained.");
58
60
  output("Uses the conversation's model.");
59
61
  if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; bridge startup will recheck compatibility. Unsupported changes still require explicit setup.");
60
62
  if (runtimeSnapshot) {
@@ -142,6 +144,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
142
144
  }
143
145
  try { retirePredictionIntegration(opts); }
144
146
  catch (error) { output(`Legacy prediction cleanup skipped: ${error.message}`); }
147
+ if (!servicePreferences(opts).prediction_enabled) writeServicePreference("prediction_enabled", true, opts);
145
148
  output("Native predictions on. Restart ccdx to launch Codex with the local bridge.");
146
149
  output("Only chatgpt.com and ab.chatgpt.com use the App-only route. Their HTTPS traffic is decrypted locally; only prediction configuration is changed. No credentials are stored, no system certificate is installed, and client program files are unchanged.");
147
150
  output("Existing official prediction configuration is preserved. The conversation's model generates predictions through your configured CCDX API.");
@@ -189,9 +192,9 @@ export async function startNativePrediction({ env = process.env, platform = proc
189
192
  ]);
190
193
  // An in-memory switch is refreshed independently of request bodies and never
191
194
  // touches the model path. A failed read turns off this optional overlay.
192
- let enabled = true;
195
+ let enabled = servicePreferences(opts).prediction_enabled;
193
196
  const timer = setInterval(() => {
194
- try { enabled = readPredictionSettings(opts).enabled; state?.configure(enabled); }
197
+ try { const configured = readPredictionSettings(opts).enabled;enabled = configured && servicePreferences(opts).prediction_enabled;state?.configure(configured); }
195
198
  catch { enabled = false; }
196
199
  }, 1000);
197
200
  timer.unref();
@@ -248,6 +251,7 @@ export async function startNativePrediction({ env = process.env, platform = proc
248
251
  ...(platform === "win32" ? { profile: paths.profile } : {}),
249
252
  pacUrl: transport.pacUrl,
250
253
  enabled() { return enabled; },
254
+ setActive(value) { enabled = value === true && readPredictionSettings(opts).enabled;return enabled; },
251
255
  appCurrent() { return predictionAppMatches(settings.app); },
252
256
  inspectEnvironment() {
253
257
  const next = inspectPredictionEnvironment(opts);
@@ -5,7 +5,7 @@ import { responseHistoryStats } from "./response-history.mjs";
5
5
  import { loadRuntimeConfig } from "./runtime-config.mjs";
6
6
  import { decodedBodyLimitPreference } from "./user-settings.mjs";
7
7
  import { profileRouting } from "./profile-routing.mjs";
8
- import { usageLoggingStats } from "./usage-store.mjs";
8
+ import { usageLoggingStats, runtimeUsageSnapshot } from "./usage-store.mjs";
9
9
  import { debugLoggingStats } from "./log.mjs";
10
10
 
11
11
  export { ADAPTER_STATUS_PATH };
@@ -17,6 +17,9 @@ const ROUTE_NAMES = Object.freeze([
17
17
  "responses",
18
18
  "responses_compact",
19
19
  "models",
20
+ "messages",
21
+ "messages_count_tokens",
22
+ "claude_models",
20
23
  "image_mcp",
21
24
  "not_found",
22
25
  ]);
@@ -96,6 +99,9 @@ export function createRequestMetrics({ now = Date.now } = {}) {
96
99
  }
97
100
 
98
101
  export function classifyAdapterRoute(method, pathname) {
102
+ if (pathname === "/anthropic/v1/messages") return "messages";
103
+ if (pathname === "/anthropic/v1/messages/count_tokens") return "messages_count_tokens";
104
+ if (pathname === "/anthropic/v1/models") return "claude_models";
99
105
  if (method === "POST" && pathname === "/v1/responses") return "responses";
100
106
  if (method === "POST" && pathname === "/v1/responses/compact") return "responses_compact";
101
107
  if (method === "GET" && pathname === "/v1/models") return "models";
@@ -199,6 +205,7 @@ export function runtimeStatusPayload({
199
205
  image_generation: imageGeneration || null,
200
206
  client_integrations: clientIntegrations || null,
201
207
  logging: { usage: usageLoggingStats(), debug: debugLoggingStats() },
208
+ runtime_usage: runtimeUsageSnapshot(),
202
209
  image_history_pressure: imagePressure?.snapshot?.() || null,
203
210
  response_failures: responseFailures?.snapshot?.() || null,
204
211
  copilot: codexRuntime,
@@ -1,5 +1,5 @@
1
- export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js"]);
2
- export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers"]);
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js", "/console.js"]);
2
+ export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings"]);
3
3
 
4
4
  export function isOptionalRoute(method, pathname) {
5
5
  return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import { publicModelCatalog } from "./provider-metadata.mjs";
3
3
  import { createGithubProvider } from "./providers/github.mjs";
4
4
  import { readProviderSettings, writeProviderSettings } from "./provider-settings.mjs";
5
- import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey, M365_GATEWAY_PORT } from "./m365-settings.mjs";
5
+ import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey } from "./m365-settings.mjs";
6
6
 
7
7
  const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
8
8
  { code: reason, statusCode: 503 });
@@ -39,7 +39,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
39
39
  const desktopManaged = integration ? await integration.inspectClaudeDesktopPolicy(options) : false;
40
40
  if (closed || !enabled || source !== m365 || source.profileId() !== profile || !gateway) return;
41
41
  claudeReason = source.models("claude").length ? null : "m365_no_claude_models";
42
- clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${gateway.port}`,
42
+ clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${corePort}/anthropic`,
43
43
  apiKey: ensureM365GatewayKey(options), models: source.models("claude") });
44
44
  } catch { clients = { code: "configuration_unavailable", app: "configuration_unavailable" };claudeReason = "m365_claude_config_unavailable"; }
45
45
  })().finally(() => { clientSync = null; });
@@ -61,13 +61,12 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
61
61
  }
62
62
  await m365.refresh();if (closed || !enabled) return null;
63
63
  const claudeModels = m365.models("claude");
64
- claudeReason = !claudeModels.length ? "m365_no_claude_models" : corePort === M365_GATEWAY_PORT ? "m365_gateway_core_port_conflict" : null;
65
- if (claudeReason === "m365_gateway_core_port_conflict") log("warn", `Claude gateway skipped: port ${M365_GATEWAY_PORT} belongs to the configured core service; M365 GPT routing remains available`);
64
+ claudeReason = !claudeModels.length ? "m365_no_claude_models" : null;
66
65
  if (claudeModels.length && !claudeReason) try {
67
66
  const apiKey = ensureM365GatewayKey(options);
68
67
  if (!gateway) {
69
- const start = startGateway || (await import("./claude-gateway.mjs")).startClaudeGateway;
70
- const opened = await start({ provider: m365, apiKey, env, log,
68
+ const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
69
+ const opened = await start({ provider: m365, apiKey, port: corePort, env, log,
71
70
  onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
72
71
  if (closed || !enabled) { await opened.close();return null; }
73
72
  gateway = opened;
@@ -77,7 +76,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
77
76
  claudeReason = error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_claude_setup_unavailable";
78
77
  log("warn", `Claude setup unavailable: ${claudeReason}; M365 GPT routing is independent`);
79
78
  }
80
- reason = null;log("ok", `Microsoft 365 ready: ${claudeModels.length} Claude, ${m365.models("gpt").length} GPT models${gateway ? `; Claude gateway at http://127.0.0.1:${gateway.port}` : ""}`);
79
+ reason = null;log("ok", `Microsoft 365 ready: ${claudeModels.length} Claude, ${m365.models("gpt").length} GPT models${gateway ? `; Claude at http://127.0.0.1:${corePort}/anthropic` : ""}`);
81
80
  return m365;
82
81
  })().catch(error => {
83
82
  reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_unavailable";
@@ -93,7 +92,8 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
93
92
  reason: reason || m365?.snapshot().reason || null,
94
93
  preference: selection.m365 || null,
95
94
  active_requests: activeM365Requests,
96
- claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway?.port || null, clients: { ...clients },
95
+ claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway ? corePort : null,
96
+ base_url: gateway ? `http://127.0.0.1:${corePort}/anthropic` : null, clients: { ...clients },
97
97
  observed_clients: { ...lastClients }, requests: gateway?.snapshot?.() || null } } });
98
98
 
99
99
  function current() {
@@ -125,12 +125,12 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
125
125
  selection = next;return snapshot();
126
126
  }
127
127
  async function disable(remove) {
128
- if (remove && (activeM365Requests > 0 || gateway?.snapshot?.().active > 0)) {
129
- throw Object.assign(new Error("Microsoft 365 requests are active; finish them before removing its profile"), { code: "m365_profile_busy", statusCode: 409 });
128
+ if (activeM365Requests > 0 || gateway?.snapshot?.().active > 0) {
129
+ throw Object.assign(new Error("Microsoft 365 requests are active; finish them before disabling or removing its profile"), { code: "m365_profile_busy", statusCode: 409 });
130
130
  }
131
131
  await switchSource("github");
132
132
  updateM365Settings({ enabled: false }, options);enabled = false;
133
- m365?.close();await gateway?.close();gateway = null;
133
+ await gateway?.close();gateway = null;m365?.close();
134
134
  await pending;m365 = null;
135
135
  const restore = restoreClients || (await import("./claude-client-config.mjs")).restoreClaudeClients;
136
136
  const result = restore(options);clients = { code: result.preserved ? "preserved" : "restored", app: result.preserved ? "preserved" : "restored" };
@@ -146,6 +146,13 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
146
146
  }
147
147
  return {
148
148
  github, current, snapshot, start: startM365, refresh: () => startM365(true),
149
+ handleClaude(req, res) {
150
+ if (!enabled || !gateway?.handle) {
151
+ res.writeHead(503, { "Content-Type": "application/json", "Cache-Control": "no-store" });
152
+ res.end(JSON.stringify({ type: "error", error: { type: "api_error", code: claudeReason || reason || "m365_claude_unavailable", message: "Claude is unavailable; check the model service settings." } }));return;
153
+ }
154
+ return gateway.handle(req, res);
155
+ },
149
156
  selection: () => selection,
150
157
  dashboardProviders() {
151
158
  const state = snapshot(), service = githubClient.runtimeStatus?.() || {}, ms = state.m365;
@@ -163,7 +170,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
163
170
  ...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
164
171
  selected: enabled, state: clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
165
172
  last_request_at: lastClients[`claude_${id}`] || null }))],
166
- requests: ms.claude.requests },
173
+ requests: ms.claude.requests, request_scope: "Claude Messages" },
167
174
  ];
168
175
  },
169
176
  async dashboardCatalog({ provider = selection.codex } = {}) {
@@ -222,6 +229,6 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
222
229
  throw new Error("Unknown M365 action");
223
230
  });
224
231
  },
225
- async close() { closed = true;enabled = false;m365?.close();await gateway?.close();gateway = null;await pending; },
232
+ async close() { closed = true;enabled = false;await gateway?.close();gateway = null;m365?.close();await pending; },
226
233
  };
227
234
  }
@@ -141,7 +141,7 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
141
141
  return {
142
142
  record(details) {
143
143
  all.record(details);
144
- const category = ["responses", "responses_compact"].includes(details.route) ? "inference"
144
+ const category = ["responses", "responses_compact", "messages", "messages_count_tokens"].includes(details.route) ? "inference"
145
145
  : details.route === "image_mcp" && details.http_status === 405 ? "protocol"
146
146
  : details.route === "not_found" ? "route" : "other";
147
147
  counts[category]++;
@@ -0,0 +1,60 @@
1
+ import { readUserSettings, servicePreferences, writeServicePreference, terminalAnimationPreference,
2
+ writeTerminalAnimationTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib } from "./user-settings.mjs";
3
+ import { readImageProviderConfig } from "./image-provider-config.mjs";
4
+ import { readPredictionSettings } from "./native-prediction-profile.mjs";
5
+ import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
6
+ import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
7
+
8
+ export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
9
+ readImages = () => readImageProviderConfig({ env, home }), readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
10
+ const options = { env, home };
11
+ let serial = Promise.resolve();
12
+ function snapshot() {
13
+ readUserSettings({ ...options, strict: true });
14
+ const saved = servicePreferences(options), prediction = clientIntegration?.snapshot().prediction;
15
+ let imageConfigured = false, predictionConfigured = false;
16
+ try { imageConfigured = Boolean(readImages()); } catch {}
17
+ try { predictionConfigured = readPrediction().enabled === true; } catch {}
18
+ return { source: "service_settings", saved, theme: terminalAnimationPreference(options).theme,
19
+ effective: {
20
+ terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
21
+ state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
22
+ open_webui: { value: saved.open_webui, state: "next_start" },
23
+ image_enabled: { value: saved.image_enabled && imageConfigured, state: imageConfigured ? "next_call" : "needs_setup", configured: imageConfigured },
24
+ prediction_enabled: { value: prediction?.active === true, state: !predictionConfigured ? "needs_setup"
25
+ : 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 },
27
+ providers: providerRuntime?.snapshot() || null, terminal: terminal?.snapshot?.() || null };
28
+ }
29
+ async function apply(input) {
30
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
31
+ const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"],
32
+ history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
33
+ provider: ["action", "operation", "provider", "model", "auto_review_model"] }[input.action];
34
+ if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
35
+ if (input.action === "preference") {
36
+ writeServicePreference(input.key, input.value, options);
37
+ if (input.key === "prediction_enabled") clientIntegration?.setPredictionActive(input.value);
38
+ terminal?.apply?.({ ...servicePreferences(options) });
39
+ } else if (input.action === "animation") {
40
+ if (!isTerminalAnimationTheme(input.theme)) throw new Error("Select a listed animation theme");
41
+ writeTerminalAnimationTheme(input.theme, options);terminal?.apply?.({ theme: input.theme });
42
+ } else if (input.action === "prediction_fix") {
43
+ if (!clientIntegration) throw new Error("Prediction integration is unavailable");
44
+ await clientIntegration.fix();
45
+ } else if (input.action === "history_limit") {
46
+ if (responseHistoryLimitPreference(options).source === "environment") throw new Error("History limit is controlled by CCDX_RESPONSE_HISTORY_MAX_BYTES");
47
+ if (!Number.isSafeInteger(input.mib)) throw new Error("History limit must be an integer MiB value");
48
+ const before = cacheRuntimeSnapshot().response_history.maxBytes;
49
+ setHistoryCacheLimit(input.mib * 1024 * 1024);
50
+ try { writeResponseHistoryLimitMib(input.mib, options); } catch (error) { setHistoryCacheLimit(before);throw error; }
51
+ } else if (input.action === "history_clean") cleanRuntimeCaches({ history: true });
52
+ else {
53
+ if (!providerRuntime || !["on", "off", "switch"].includes(input.operation)) throw new Error("Invalid provider operation");
54
+ 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 });
56
+ }
57
+ return snapshot();
58
+ }
59
+ return { snapshot, action(input) { const operation = serial.then(() => apply(input));serial = operation.catch(() => {});return operation; } };
60
+ }
@@ -16,8 +16,8 @@ const ATOM = [
16
16
  export function startupBanner({ commandName = "ccdx", version, stream = process.stdout, env = process.env } = {}) {
17
17
  const title = `${terminalCell(commandName)} v${terminalCell(version)} by Dale Xiao`;
18
18
  const color = stream.isTTY === true && !Object.hasOwn(env, "NO_COLOR") && env.TERM !== "dumb";
19
- if (!color || Number(stream.columns || 80) < 72) return `${title}\nUse Codex App with GitHub Copilot`;
20
- const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Codex App + GitHub Copilot"]]);
19
+ if (!color || Number(stream.columns || 80) < 72) return `${title}\nLocal model services for Codex and Claude`;
20
+ const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Codex + Claude / local services"]]);
21
21
  return ATOM.map((line, i) => `\x1b[38;2;166;245;168m${line}\x1b[0m${labels.has(i) ? ` ${labels.get(i)}` : ""}`).join("\n");
22
22
  }
23
23
 
@@ -48,5 +48,6 @@ export function predictionStartupCheck(prediction) {
48
48
  const summary = startupCheck(route === "unverified" ? "warn" : "info", "Prediction", route === "verified"
49
49
  ? "Bridge running; App route verified; suggestion not checked"
50
50
  : "Bridge running; App route not verified; suggestion not checked");
51
- return (prediction.recovery ? `${summary}\n${startupCheck("info", "Recovery", `${prediction.recovery.attempts}/3 attempts used; persistent route ${prediction.persistence || "unknown"}`)}` : summary) + details;
51
+ const pause = prediction.active === false ? `\n${startupCheck("info", "Prediction", "Adaptation paused; existing trust/route retained")}` : "";
52
+ return (prediction.recovery ? `${summary}\n${startupCheck("info", "Recovery", `${prediction.recovery.attempts}/3 attempts used; persistent route ${prediction.persistence || "unknown"}`)}` : summary) + pause + details;
52
53
  }
@@ -0,0 +1,87 @@
1
+ import { format, stripVTControlCharacters } from "node:util";
2
+ import { terminalCell } from "./terminal-text.mjs";
3
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
4
+ import { DEFAULT_TERMINAL_ANIMATION_THEME, TERMINAL_ANIMATION_THEMES, isTerminalAnimationTheme, renderTerminalAnimationFrame,
5
+ getTerminalAnimationCycleLength, getTerminalAnimationFrameDelay } from "./terminal-animation.mjs";
6
+ import { displayWidth } from "./cli-table.mjs";
7
+
8
+ const clear = "\r\x1b[2K";
9
+ const flagOff = value => /^(0|false|no|off)$/i.test(String(value || ""));
10
+
11
+ // A bounded status region, independent of file logging and inference delivery.
12
+ export function createTerminalConsole({ output = process.stdout, errorOutput = process.stderr, env = process.env,
13
+ snapshot = () => ({}), preferences = () => ({}), baseUrl = "", verbose = false,
14
+ timers = { setTimeout, clearTimeout }, now = Date.now } = {}) {
15
+ let running = false, timer = null, lines = 0, active = 0, frame = 0, lastRead = 0, data = {};
16
+ let notices = 0, lastNotice = "", lastPrintedNotice = "", lastRender = "";
17
+ let current = { theme: DEFAULT_TERMINAL_ANIMATION_THEME, terminal_animation_enabled: true };
18
+ let frameDelay = 1000;
19
+ const tty = output.isTTY === true && errorOutput.isTTY === true && (!env.CI || flagOff(env.CI)) && env.TERM !== "dumb";
20
+ const supported = () => tty && (Number(output.columns) || 80) >= 40;
21
+ const resized = () => { if (lines) output.write("\n");lines = 0;lastRender = "";frame = 0; };
22
+ output.on?.("resize", resized);
23
+ const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
24
+ const clip = (value, width) => {
25
+ let text = "";
26
+ for (const { segment } of segmenter.segment(terminalCell(value, { fallback: "" }))) {
27
+ if (displayWidth(text + segment) > width) break;text += segment;
28
+ }
29
+ return text;
30
+ };
31
+ const compact = value => new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(Number(value) || 0);
32
+ function render() {
33
+ if (!running || !supported() || verbose) { frameDelay = 1000;return; }
34
+ const width = Math.max(1, Math.min(160, Number(output.columns) || 80) - 1);
35
+ const usage = data.runtime_usage || {}, routes = data.requests?.by_route || {};
36
+ const outcomes = [data.stream_performance?.by_route?.responses, data.stream_performance?.by_route?.responses_compact, data.providers?.m365?.claude?.requests?.performance?.by_route?.messages]
37
+ .map(route => route?.terminal_outcomes?.totals || {});
38
+ const sum = key => outcomes.reduce((total, item) => total + (Number(item[key]) || 0), 0);
39
+ let motion = active ? "●" : "○";
40
+ frameDelay = 1000;
41
+ if (active && current.terminal_animation_enabled && !flagOff(env.CCDX_TERMINAL_ANIMATION) && width >= 24) {
42
+ frame %= getTerminalAnimationCycleLength(current.theme);
43
+ const metadata = TERMINAL_ANIMATION_THEMES.find(theme => theme.id === current.theme), index = metadata.startFrame + frame;
44
+ motion = renderTerminalAnimationFrame(current.theme, index);
45
+ if (Object.hasOwn(env, "NO_COLOR")) motion = stripVTControlCharacters(motion);
46
+ frame = (frame + 1) % getTerminalAnimationCycleLength(current.theme);
47
+ frameDelay = getTerminalAnimationFrameDelay(current.theme, index) + (frame === 0 ? metadata.loopPauseMs : 0);
48
+ }
49
+ const requests = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.total || 0), 0);
50
+ const body = [
51
+ `CCDX ${lastNotice ? "ATTENTION" : "READY"} / uptime ${Math.floor((data.uptime_ms || 0) / 60000)}m / ${baseUrl}`,
52
+ `This run · usage records ${usage.records || 0} · input ${compact(usage.input_tokens)} · cache read ${compact(usage.cached_input_tokens)} · output ${compact(usage.output_tokens)}${usage.partial_records ? " ~" : ""}`,
53
+ `Inference · ${requests} HTTP calls · active ${active} · done ${sum("completed")} · incomplete ${sum("incomplete")} · failed ${sum("failed")} · cancelled ${sum("cancelled")}`,
54
+ ].map(line => clip(line, width));
55
+ const notice = lastNotice ? `${notices} notices / ${lastNotice}` : active ? "Working" : "Idle / details in WebUI";
56
+ body.push(width >= 24 ? `${motion} ${clip(notice, Math.max(0, width - displayWidth(stripVTControlCharacters(motion)) - 1))}` : clip(`${motion} ${notice}`, width));
57
+ const rendered = body.join("\n");
58
+ if (rendered === lastRender) return;
59
+ lastRender = rendered;
60
+ output.write(`${lines ? `\x1b[${lines - 1}A` : ""}${body.map(line => clear + line).join("\n")}\r`);
61
+ lines = 4;
62
+ }
63
+ function tick() {
64
+ if (!running) return;
65
+ if (now() - lastRead >= 1000 || !lastRead) {
66
+ try { data = snapshot();current = { ...current, ...preferences() };if (!isTerminalAnimationTheme(current.theme)) current.theme = DEFAULT_TERMINAL_ANIMATION_THEME; } catch {}
67
+ lastRead = now();
68
+ }
69
+ render();
70
+ timer = timers.setTimeout(tick, frameDelay);timer?.unref?.();
71
+ }
72
+ return {
73
+ get enabled() { return supported() && !verbose; },
74
+ start() { if (running) return;running = true;tick(); },
75
+ beginRequest() { active++;let done = false;return () => { if (!done) { done = true;active = Math.max(0, active - 1); } }; },
76
+ log(method, args) {
77
+ const message = redactDiagnosticText(format(...args));
78
+ if (verbose) { (method === "error" || method === "warn" ? errorOutput : output).write(`${message}\n`);return; }
79
+ if (method !== "error" && method !== "warn" && !/^\[(WARN|ERR)\]/.test(message.trim())) return;
80
+ notices++;lastNotice = message.replace(/\s+/g, " ").slice(0, 240);
81
+ if (!supported() && lastNotice !== lastPrintedNotice) { errorOutput.write(`${lastNotice}\n`);lastPrintedNotice = lastNotice; }
82
+ },
83
+ snapshot() { return { notices, last_notice: lastNotice || null, mode: verbose ? "verbose" : supported() ? "status" : "plain" }; },
84
+ apply(value) { if (value.theme && value.theme !== current.theme) frame = 0;current = { ...current, ...value };lastRead = 0; },
85
+ cleanup() { running = false;if (timer) timers.clearTimeout(timer);timer = null;if (lines) output.write("\n");lines = 0;output.off?.("resize", resized); },
86
+ };
87
+ }
@@ -24,6 +24,9 @@ let pendingRecords = 0;
24
24
  let pendingBytes = 0;
25
25
  let droppedRecords = 0;
26
26
  let writeFailures = 0;
27
+ const runtimeUsage = { since: new Date().toISOString(), records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 };
28
+
29
+ export function runtimeUsageSnapshot() { return { ...runtimeUsage }; }
27
30
 
28
31
  export function usageLoggingStats() {
29
32
  return { pending_records: pendingRecords, pending_bytes: pendingBytes, dropped_records: droppedRecords,
@@ -180,7 +183,14 @@ function scheduleUsageWriteDrain() {
180
183
  }
181
184
 
182
185
  export function recordUsage(record) {
183
- if (!record || process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
186
+ if (!record) return Promise.resolve();
187
+ 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;
191
+ }
192
+ if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cacheReadTokens(usage) === undefined) runtimeUsage.partial_records++;
193
+ if (process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
184
194
  const filePath = usageLogPath();
185
195
  const line = `${JSON.stringify(record)}\n`;
186
196
  const bytes = Buffer.byteLength(line);
package/src/usage.mjs CHANGED
@@ -4,6 +4,7 @@ import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageLogPath, u
4
4
  export {
5
5
  usageSummaryVersion,
6
6
  usageLoggingStats,
7
+ runtimeUsageSnapshot,
7
8
  usageLogPath,
8
9
  usageLogMaxBytes,
9
10
  buildResponsesUsageRecord,
@@ -22,6 +22,7 @@ const AUTO_REVIEW_REASONING_KEY = "auto_review_reasoning";
22
22
  const TERMINAL_ANIMATION_KEY = "terminal_animation";
23
23
  const RESPONSE_HISTORY_MAX_MIB_KEY = "response_history_max_mib";
24
24
  const DECODED_BODY_LIMIT_MIB_KEY = "decoded_body_limit_mib";
25
+ const SERVICE_FLAGS = ["terminal_animation_enabled", "open_webui", "image_enabled", "prediction_enabled"];
25
26
  export const DECODED_BODY_LIMIT_MIN_MIB = RUNTIME_DEFAULTS.maxDecodedBodyBytes / MIB;
26
27
  export const DECODED_BODY_LIMIT_MAX_MIB = 512;
27
28
  export { RESPONSE_HISTORY_MAX_MIB, RESPONSE_HISTORY_MIN_MIB };
@@ -43,6 +44,12 @@ export function readUserSettings({ env = process.env, home = os.homedir(), stric
43
44
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
44
45
  throw invalidSettings(filePath, "expected a JSON object");
45
46
  }
47
+ for (const key of SERVICE_FLAGS) {
48
+ if (Object.hasOwn(parsed, key) && typeof parsed[key] !== "boolean") {
49
+ if (strict) throw invalidSettings(filePath, `${key} must be a boolean`);
50
+ delete parsed[key];
51
+ }
52
+ }
46
53
  if (Object.hasOwn(parsed, AUTO_REVIEW_MODEL_KEY)) {
47
54
  const value = parsed[AUTO_REVIEW_MODEL_KEY];
48
55
  if (typeof value !== "string" || !value.trim()) {
@@ -107,6 +114,20 @@ export function savedAutoReviewModel(options = {}) {
107
114
  return String(settings[AUTO_REVIEW_MODEL_KEY] || "").trim();
108
115
  }
109
116
 
117
+ export function servicePreferences(options = {}) {
118
+ const settings = readUserSettings({ ...options, strict: true });
119
+ return Object.fromEntries(SERVICE_FLAGS.map(key => [key, settings[key] !== false]));
120
+ }
121
+
122
+ export function writeServicePreference(key, value, options = {}) {
123
+ if (!SERVICE_FLAGS.includes(key) || typeof value !== "boolean") throw new Error("Unknown service setting or invalid boolean");
124
+ return withFileLockSync(`${userSettingsPath(options)}.lock`, () => {
125
+ const settings = readUserSettings({ ...options, strict: true });
126
+ const changed = atomicWriteFileIfChangedSync(userSettingsPath(options), `${JSON.stringify({ ...settings, [key]: value }, null, 2)}\n`, { mode: 0o600 });
127
+ return { changed, ...servicePreferences(options) };
128
+ });
129
+ }
130
+
110
131
  export function autoReviewModelPreference({ env = process.env, home = os.homedir() } = {}) {
111
132
  const { model, source } = autoReviewPreference({ env, home });
112
133
  return { model, source };