codex-copilot-dx 1.0.0 → 1.1.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.
@@ -82,14 +82,14 @@ function stopAnimationPreview() {
82
82
 
83
83
  function tickAnimationPreview() {
84
84
  previewTimer = null;
85
- if (!animationTimelines.length || !element("animation-settings").open || !previewVisible || document.visibilityState !== "visible" || reducedMotion.matches || previewDisabledByEnvironment) return;
85
+ if (!animationTimelines.length || !element("animation-settings").open || element("animation-settings").closest("[hidden]") || !previewVisible || document.visibilityState !== "visible" || reducedMotion.matches || previewDisabledByEnvironment) return;
86
86
  renderAnimationFrames(performance.now() - previewStarted);
87
87
  previewTimer = setTimeout(tickAnimationPreview, 32);
88
88
  }
89
89
 
90
90
  function syncAnimationPreview() {
91
91
  stopAnimationPreview();
92
- if (!animationTimelines.length || !element("animation-settings").open || !previewVisible || document.visibilityState !== "visible" || reducedMotion.matches || previewDisabledByEnvironment) {
92
+ if (!animationTimelines.length || !element("animation-settings").open || element("animation-settings").closest("[hidden]") || !previewVisible || document.visibilityState !== "visible" || reducedMotion.matches || previewDisabledByEnvironment) {
93
93
  for (const timeline of animationTimelines) timeline.lastFrame = -2;
94
94
  renderAnimationFrames(0);
95
95
  return;
@@ -155,7 +155,7 @@ function buildAnimationOptions(data) {
155
155
  function animationNote(data) {
156
156
  return data.disabled_by_environment
157
157
  ? "Disabled by CCDX_TERMINAL_ANIMATION; saved choice applies after override removal and next start."
158
- : "Saved choice applies on next ccdx start.";
158
+ : "Saved choice applies to the running terminal.";
159
159
  }
160
160
 
161
161
  function loadAnimation(options) {
@@ -375,7 +375,7 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
375
375
  },
376
376
  apply: render,
377
377
  state: state => {
378
- text("connection", state.pending || (!state.value && !state.error) ? "READING" : state.error ? "UNAVAILABLE" : "LOCAL OK");
378
+ text("connection", state.pending && !state.value ? "READING" : state.error ? "UNAVAILABLE" : "SERVICE REACHABLE");
379
379
  element("connection").className = `badge ${state.pending ? "neutral" : state.error ? "bad" : "good"}`;
380
380
  if (state.error) refreshTime(element("updated"), state);
381
381
  for (const node of timestamps.get("status")) refreshTime(node, state);
@@ -394,7 +394,7 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
394
394
  },
395
395
  },
396
396
  models: {
397
- visible: () => providerEntries.length > 0 && element("upstream-models").open,
397
+ visible: () => providerEntries.length > 0 && element("upstream-models").open && !element("upstream-models").closest("[hidden]"),
398
398
  variant: () => selectedProvider,
399
399
  load: async ({ signal, variant }) => {
400
400
  if (!variant) throw new Error("Reading provider catalog…");
@@ -418,7 +418,7 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
418
418
  },
419
419
  },
420
420
  usage: {
421
- visible: () => element("model-usage").open,
421
+ visible: () => element("model-usage").open && !element("model-usage").closest("[hidden]"),
422
422
  variant: () => {
423
423
  const mode = ((element("model-usage").open && element("usage-analytics").open) || Boolean(usageView.selectedDate)) ? "analytics" : "summary";
424
424
  const provider = element("usage-provider")?.value || "";
@@ -516,7 +516,6 @@ element("usage-provider")?.addEventListener("change", () => { dashboardRefresh.i
516
516
  element("refresh-models").addEventListener("click", loadModels);
517
517
  element("refresh-usage").addEventListener("click", loadUsage);
518
518
  loadAnimation();
519
- loadUsage();
520
519
  refresh();
521
- loadAuth().then(() => loadModels());
520
+ loadAuth();
522
521
  animateRefresh();
@@ -128,6 +128,7 @@ function dashboardProviders(providerStateFn, authStatusFn) {
128
128
  clients: (entry.clients || []).slice(0, 8).map(client => ({ id: code(client.id), name: label(client.name),
129
129
  selected: client.selected === true, state: code(client.state) || "unknown", gateway: code(client.gateway),
130
130
  reason: code(client.reason), last_request_at: label(client.last_request_at) || null })),
131
+ request_scope: label(entry.request_scope) || null,
131
132
  requests: entry.requests ? Object.fromEntries(["total", "active", "completed", "incomplete", "failed", "cancelled"].map(key => [key, finite(entry.requests[key])])) : null };
132
133
  });
133
134
  }
@@ -140,6 +141,8 @@ export async function handleDashboardApi(req, res, pathname, {
140
141
  authStatusFn = () => authStatus({ home }),
141
142
  providerCatalogFn,
142
143
  providerStateFn,
144
+ serviceControl,
145
+ applyAnimation,
143
146
  } = {}) {
144
147
  if (!isLoopbackAddress(req.socket?.remoteAddress)
145
148
  || req.headers?.host === undefined
@@ -158,6 +161,26 @@ export async function handleDashboardApi(req, res, pathname, {
158
161
  return;
159
162
  }
160
163
 
164
+ if (pathname === "/_ccdx/ui/settings") {
165
+ if (!serviceControl) { sendJson(res, 503, { error: "Settings require the running service; restart the updated CCDX" });return; }
166
+ if (req.method === "GET") {
167
+ try { sendJson(res, 200, serviceControl.snapshot()); } catch { sendJson(res, 409, { error: "Service settings are unreadable; existing settings were preserved" }); }
168
+ return;
169
+ }
170
+ if (req.method !== "POST") { sendJson(res, 405, { error: "Use GET or POST" });return; }
171
+ if (!sameOrigin(req)) { sendJson(res, 403, { error: "Settings require the same-origin dashboard" });return; }
172
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { sendJson(res, 415, { error: "Expected application/json" });return; }
173
+ const abort = createRequestAbort(req, res);abort.setTimeout(5000, "request_body_timeout");
174
+ try {
175
+ const input = await readJsonBody(req, { maxBodyBytes: 4096, maxDecodedBodyBytes: 4096, signal: abort.signal });
176
+ abort.clearTimeout();const data = await serviceControl.action(input);
177
+ if (!res.destroyed && !res.writableEnded) sendJson(res, 200, data);
178
+ } catch (error) {
179
+ sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300) });
180
+ } finally { abort.cleanup(); }
181
+ return;
182
+ }
183
+
161
184
  if (pathname === AUTH_PATH && req.method === "GET") {
162
185
  try {
163
186
  const profile = authStatusFn()?.profiles?.codex;
@@ -215,6 +238,7 @@ export async function handleDashboardApi(req, res, pathname, {
215
238
  }
216
239
  try {
217
240
  const result = writeTerminalAnimationTheme(body.theme, { env, home });
241
+ applyAnimation?.(body.theme);
218
242
  sendJson(res, 200, { changed: result.changed, ...animationState(env, home) });
219
243
  } catch {
220
244
  sendJson(res, 409, { error: "Animation setting was not saved; check ccdx animation" });
package/src/dashboard.mjs CHANGED
@@ -7,6 +7,7 @@ const ASSETS = new Map([
7
7
  ["/theme.js", ["./dashboard/theme.js", "text/javascript; charset=utf-8"]],
8
8
  ["/language.js", ["./dashboard/language.js", "text/javascript; charset=utf-8"]],
9
9
  ["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
10
+ ["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
10
11
  ["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
11
12
  ["/usage.js", ["./dashboard/usage.js", "text/javascript; charset=utf-8"]],
12
13
  ["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
@@ -373,5 +373,6 @@ export function logRequestFailure(label, err, abort) {
373
373
 
374
374
  const reason = abort?.reason || "aborted";
375
375
  err.statusCode ||= abortErrorStatusCode(reason);
376
- console.warn(status("warn", `${label} request aborted: ${reason}`));
376
+ const cancelled = reason === "client_aborted" || reason === "client_closed";
377
+ console[cancelled ? "log" : "warn"](status(cancelled ? "info" : "warn", `${label} request aborted: ${reason}`));
377
378
  }
package/src/image-mcp.mjs CHANGED
@@ -6,6 +6,7 @@ import { isIP } from "node:net";
6
6
  import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
7
7
  import { generateImage, supportsImageEditing, IMAGE_MAX_BYTES } from "./image-provider.mjs";
8
8
  import { readImageProviderConfig } from "./image-provider-config.mjs";
9
+ import { servicePreferences } from "./user-settings.mjs";
9
10
  import { createImageReferenceStore } from "./image-references.mjs";
10
11
 
11
12
  const MCP_PROTOCOL_VERSION = "2025-06-18";
@@ -155,6 +156,7 @@ function safeToolError(error, apiKey) {
155
156
 
156
157
  export function createImageMcpHandler({
157
158
  configLoader = () => readImageProviderConfig(),
159
+ isEnabled = () => servicePreferences().image_enabled,
158
160
  generateImageFn = generateImage,
159
161
  maxConcurrent = 2,
160
162
  localHostname = "",
@@ -216,9 +218,10 @@ export function createImageMcpHandler({
216
218
  protocolVersion: MCP_PROTOCOL_VERSIONS.has(requestedVersion) ? requestedVersion : MCP_PROTOCOL_VERSION,
217
219
  capabilities: { tools: { listChanged: false } },
218
220
  serverInfo: { name: "ccdx-image", version: "1" },
219
- instructions: config
221
+ instructions: config && isEnabled()
220
222
  ? `CCDX handles the configured image API and credentials; no Python or SDK setup. Embed returned image Markdown in the final reply. Redisplay reuses it without tool calls. Keep each image_id with its own image. Do not automatically retry failed/timed-out requests or switch providers.${supportsImageEditing(config) ? " Use generate_image for new images; edit_image requires the exact retained source ID." : " Use generate_image for new images. Editing is unsupported; do not substitute generation."}`
221
- : "Image generation is disabled. Enable it with ccdx enable-image before requesting images.",
223
+ : config ? "Image calls are paused. Resume them in the CCDX WebUI; the provider and retained edit handles are preserved."
224
+ : "Image generation is disabled. Enable it with ccdx enable-image before requesting images.",
222
225
  });
223
226
  return;
224
227
  }
@@ -229,7 +232,7 @@ export function createImageMcpHandler({
229
232
  if (request.method === "tools/list") {
230
233
  const config = configLoader();
231
234
  if (!config) imageReferences.clear();
232
- reply({ tools: config ? [imageTool(), ...(supportsImageEditing(config) ? [editTool()] : [])] : [] });
235
+ reply({ tools: config && isEnabled() ? [imageTool(), ...(supportsImageEditing(config) ? [editTool()] : [])] : [] });
233
236
  return;
234
237
  }
235
238
  if (request.method !== "tools/call") {
@@ -242,10 +245,10 @@ export function createImageMcpHandler({
242
245
  }
243
246
  metrics.total += 1;
244
247
  const config = configLoader();
245
- if (!config) {
248
+ if (!config || !isEnabled()) {
246
249
  metrics.failed += 1;
247
- imageReferences.clear();
248
- reply({ content: [{ type: "text", text: "Image generation is disabled. Run ccdx enable-image first." }], isError: true });
250
+ if (!config) imageReferences.clear();
251
+ reply({ content: [{ type: "text", text: config ? "Image calls are paused. Resume them in the CCDX WebUI." : "Image generation is disabled. Run ccdx enable-image first." }], isError: true });
249
252
  return;
250
253
  }
251
254
  const editing = request.params.name === EDIT_TOOL_NAME;
package/src/launcher.mjs CHANGED
@@ -83,10 +83,10 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
83
83
  const running = windowsAppProcesses(current.app, { env });
84
84
  if (running.length) {
85
85
  if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
86
- onPredictionRoute("verified");log(status("ok", "Running Codex App uses the current prediction route"));return true;
86
+ onPredictionRoute("verified");log(status("ok", "Codex already running"));return true;
87
87
  }
88
88
  if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
89
- onPredictionRoute("persisted");log(status("info", "App route preference is saved; waiting for configuration traffic to confirm it"));return true;
89
+ onPredictionRoute("persisted");log(status("info", "Codex already running"));return true;
90
90
  }
91
91
  throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then run ccdx again; no process was stopped");
92
92
  }
@@ -105,7 +105,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
105
105
  const routeRetained = actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl;
106
106
  onPredictionRoute(routeRetained ? "verified" : "unverified");
107
107
  log(status(routeRetained ? "info" : "warn", routeRetained
108
- ? "Codex launch route verified; prediction status will show when configuration traffic is observed"
108
+ ? "Codex opened"
109
109
  : "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
110
110
  return routeRetained;
111
111
  } catch (error) {
@@ -132,10 +132,10 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
132
132
  const running = macAppProcesses(predictionApp);
133
133
  if (running.length) {
134
134
  if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
135
- onPredictionRoute("verified");log(status("ok", "Running Codex App uses the current prediction route"));return true;
135
+ onPredictionRoute("verified");log(status("ok", "Codex already running"));return true;
136
136
  }
137
137
  if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
138
- onPredictionRoute("persisted");log(status("info", "App route preference is saved; waiting for configuration traffic to confirm it"));return true;
138
+ onPredictionRoute("persisted");log(status("info", "Codex already running"));return true;
139
139
  }
140
140
  throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then run ccdx again; no process was stopped");
141
141
  }
@@ -146,7 +146,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
146
146
  for (let attempt = 0; attempt < 10; attempt++) {
147
147
  const actual = macAppProcesses(predictionApp);
148
148
  if (actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl) {
149
- onPredictionRoute("verified");log(status("info", "Codex launch route verified; prediction status will show when configuration traffic is observed"));return true;
149
+ onPredictionRoute("verified");log(status("info", "Codex opened"));return true;
150
150
  }
151
151
  if (actual.length) break;
152
152
  if (attempt < 9) await new Promise(resolve => setTimeout(resolve, 100));
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
+ }