codex-copilot-dx 0.10.1 → 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.
Files changed (47) hide show
  1. package/README.md +18 -17
  2. package/bin/cli.mjs +24 -3
  3. package/docs/ARCHITECTURE.md +60 -14
  4. package/docs/README.md +3 -0
  5. package/docs/REFERENCE.md +186 -45
  6. package/package.json +2 -2
  7. package/src/adapter.mjs +19 -4
  8. package/src/browser-launch.mjs +22 -0
  9. package/src/claude-client-config.mjs +22 -5
  10. package/src/claude-gateway.mjs +30 -8
  11. package/src/claude-models.mjs +26 -0
  12. package/src/cli-animation.mjs +1 -1
  13. package/src/cli-image.mjs +3 -0
  14. package/src/cli-m365.mjs +1 -1
  15. package/src/cli-options.mjs +11 -6
  16. package/src/cli-table.mjs +1 -1
  17. package/src/client-integration.mjs +5 -1
  18. package/src/dashboard/console.js +141 -0
  19. package/src/dashboard/index.html +105 -52
  20. package/src/dashboard/language.js +103 -0
  21. package/src/dashboard/refresh.js +2 -1
  22. package/src/dashboard/status.js +60 -29
  23. package/src/dashboard/ui.css +49 -0
  24. package/src/dashboard/ui.js +113 -26
  25. package/src/dashboard-api.mjs +72 -7
  26. package/src/dashboard.mjs +1 -0
  27. package/src/image-mcp.mjs +9 -6
  28. package/src/live-models.mjs +11 -3
  29. package/src/log.mjs +13 -11
  30. package/src/m365-settings.mjs +0 -2
  31. package/src/native-prediction-recovery.mjs +1 -0
  32. package/src/native-prediction.mjs +6 -2
  33. package/src/observability.mjs +8 -1
  34. package/src/optional-routes.mjs +2 -2
  35. package/src/provider-metadata.mjs +21 -0
  36. package/src/provider-runtime.mjs +80 -26
  37. package/src/providers/m365-auth.mjs +4 -4
  38. package/src/providers/m365.mjs +10 -2
  39. package/src/response-failures.mjs +1 -1
  40. package/src/service-control.mjs +60 -0
  41. package/src/startup-ui.mjs +4 -3
  42. package/src/terminal-console.mjs +87 -0
  43. package/src/usage-analysis.mjs +1 -1
  44. package/src/usage-analytics.mjs +3 -3
  45. package/src/usage-store.mjs +40 -17
  46. package/src/usage.mjs +14 -7
  47. package/src/user-settings.mjs +21 -0
@@ -1,4 +1,5 @@
1
1
  import os from "node:os";
2
+ import { isProviderId } from "./provider-metadata.mjs";
2
3
  import { fetchLiveCopilotModels } from "./live-models.mjs";
3
4
  import { authStatus } from "./auth-status.mjs";
4
5
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
@@ -11,7 +12,7 @@ import {
11
12
  renderTerminalAnimationFrame,
12
13
  TERMINAL_ANIMATION_THEMES,
13
14
  } from "./terminal-animation.mjs";
14
- import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate } from "./usage-store.mjs";
15
+ import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroups } from "./usage-store.mjs";
15
16
  import { createUsageAnalytics } from "./usage-analytics.mjs";
16
17
  import { analyzeUsageLogs } from "./usage-analysis.mjs";
17
18
  import { readUserSettings, terminalAnimationPreference, writeTerminalAnimationTheme } from "./user-settings.mjs";
@@ -19,6 +20,7 @@ import { readUserSettings, terminalAnimationPreference, writeTerminalAnimationTh
19
20
  const ANIMATION_PATH = "/_ccdx/ui/animation";
20
21
  const MODELS_PATH = "/_ccdx/ui/models/live";
21
22
  const USAGE_PATH = "/_ccdx/ui/usage";
23
+ const PROVIDERS_PATH = "/_ccdx/ui/providers";
22
24
  const AUTH_PATH = "/_ccdx/ui/auth";
23
25
  const DISABLED_ANIMATION = /^(0|false|no|off)$/i;
24
26
 
@@ -98,7 +100,7 @@ function usageRow(model, values) {
98
100
  }
99
101
 
100
102
  function usageTable(summary) {
101
- const models = Object.entries(summary.byModel || {})
103
+ const models = Object.entries(usageModelGroups(summary))
102
104
  .sort(([leftName, left], [rightName, right]) => (right.total_tokens || 0) - (left.total_tokens || 0)
103
105
  || leftName.localeCompare(rightName, "en"));
104
106
  return {
@@ -108,6 +110,29 @@ function usageTable(summary) {
108
110
  };
109
111
  }
110
112
 
113
+ function dashboardProviders(providerStateFn, authStatusFn) {
114
+ const local = authStatusFn()?.profiles?.codex || {};
115
+ const entries = providerStateFn?.() || [{ id: "github", name: "GitHub Copilot", enabled: true, state: "unknown",
116
+ clients: [{ id: "codex", name: "Codex App", selected: true, state: "configured" }] }];
117
+ return entries.slice(0, 16).filter(entry => isProviderId(entry.id)).map(entry => {
118
+ const auth = entry.id === "github" ? { ...entry.auth,
119
+ state: local.valid ? "saved" : local.configured ? "unavailable" : "unconfigured",
120
+ account: local.valid ? local.login || "" : "" } : entry.auth || {};
121
+ const label = value => safeText(redactDiagnosticText(value || ""), 160);
122
+ const code = value => typeof value === "string" && /^[a-z0-9_:-]{1,80}$/.test(value) ? value : null;
123
+ return { id: entry.id, name: label(entry.name) || entry.id, enabled: entry.enabled === true,
124
+ state: code(entry.state) || "unknown", reason: code(entry.reason), generation: finite(entry.generation),
125
+ auth: { state: code(auth.state) || "unknown", account: label(auth.account), token_cached: auth.token_cached === true,
126
+ expires_in_ms: finite(auth.expires_in_ms), checked_at: label(auth.checked_at) || null },
127
+ models: { count: finite(entry.models?.count), source: code(entry.models?.source) || "unknown", checked_at: label(entry.models?.checked_at) || null },
128
+ clients: (entry.clients || []).slice(0, 8).map(client => ({ id: code(client.id), name: label(client.name),
129
+ selected: client.selected === true, state: code(client.state) || "unknown", gateway: code(client.gateway),
130
+ reason: code(client.reason), last_request_at: label(client.last_request_at) || null })),
131
+ request_scope: label(entry.request_scope) || null,
132
+ requests: entry.requests ? Object.fromEntries(["total", "active", "completed", "incomplete", "failed", "cancelled"].map(key => [key, finite(entry.requests[key])])) : null };
133
+ });
134
+ }
135
+
111
136
  export async function handleDashboardApi(req, res, pathname, {
112
137
  env = process.env,
113
138
  home = os.homedir(),
@@ -115,6 +140,9 @@ export async function handleDashboardApi(req, res, pathname, {
115
140
  usageSummaryFn,
116
141
  authStatusFn = () => authStatus({ home }),
117
142
  providerCatalogFn,
143
+ providerStateFn,
144
+ serviceControl,
145
+ applyAnimation,
118
146
  } = {}) {
119
147
  if (!isLoopbackAddress(req.socket?.remoteAddress)
120
148
  || req.headers?.host === undefined
@@ -127,6 +155,32 @@ export async function handleDashboardApi(req, res, pathname, {
127
155
  return;
128
156
  }
129
157
 
158
+ if (pathname === PROVIDERS_PATH && req.method === "GET") {
159
+ try { sendJson(res, 200, { source: "provider_status", providers: dashboardProviders(providerStateFn, authStatusFn) }); }
160
+ catch { sendJson(res, 500, { error: "Could not read provider status" }); }
161
+ return;
162
+ }
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
+
130
184
  if (pathname === AUTH_PATH && req.method === "GET") {
131
185
  try {
132
186
  const profile = authStatusFn()?.profiles?.codex;
@@ -184,6 +238,7 @@ export async function handleDashboardApi(req, res, pathname, {
184
238
  }
185
239
  try {
186
240
  const result = writeTerminalAnimationTheme(body.theme, { env, home });
241
+ applyAnimation?.(body.theme);
187
242
  sendJson(res, 200, { changed: result.changed, ...animationState(env, home) });
188
243
  } catch {
189
244
  sendJson(res, 409, { error: "Animation setting was not saved; check ccdx animation" });
@@ -194,7 +249,12 @@ export async function handleDashboardApi(req, res, pathname, {
194
249
  if (pathname === MODELS_PATH && req.method === "GET") {
195
250
  const abort = createRequestAbort(req, res);
196
251
  try {
197
- const catalog = providerCatalogFn?.() || await liveModelsFn({ signal: abort.signal });
252
+ const provider = new URL(req.url, "http://localhost").searchParams.get("provider") || "";
253
+ if (provider && (!isProviderId(provider) || !dashboardProviders(providerStateFn, authStatusFn).some(entry => entry.id === provider))) {
254
+ sendJson(res, 400, { error: "Select a registered provider" });return;
255
+ }
256
+ const catalog = await providerCatalogFn?.({ ...(provider ? { provider } : {}), signal: abort.signal })
257
+ || await liveModelsFn({ signal: abort.signal, includeAll: true });
198
258
  if (!Array.isArray(catalog?.models) || !Number.isFinite(catalog?.advertised)) {
199
259
  throw new Error("Invalid live model catalog");
200
260
  }
@@ -204,16 +264,21 @@ export async function handleDashboardApi(req, res, pathname, {
204
264
  checked_at: catalog.source === "catalog" ? catalog.checkedAt : new Date().toISOString(),
205
265
  upstream_host: safeText(catalog?.upstreamHost || "GitHub Copilot", 120),
206
266
  advertised: finite(catalog?.advertised),
207
- selectable: models.length,
267
+ selectable: models.filter(model => model.selectable !== false).length,
208
268
  models: models.slice(0, 500).map((model) => ({
209
269
  id: safeText(model.id, 100),
210
270
  vendor: safeText(model.vendor, 80),
211
271
  endpoints: Array.isArray(model.endpoints) ? model.endpoints.filter((value) => ["responses", "chat", "messages"].includes(value)) : [],
212
272
  preview: model.preview === true,
273
+ selectable: model.selectable !== false,
274
+ clients: Array.isArray(model.clients) ? model.clients.filter(value => typeof value === "string").slice(0, 8).map(value => safeText(value, 40)) : [],
275
+ reasoning_efforts: Array.isArray(model.reasoning_efforts) ? model.reasoning_efforts.slice(0, 16).map(value => safeText(value, 16)) : null,
276
+ state: ["listed", "restricted", "hidden"].includes(model.state) ? model.state : "listed",
277
+ context_window: finite(model.context_window),
213
278
  })),
214
279
  });
215
280
  } catch (error) {
216
- if (!res.destroyed && !res.writableEnded) sendJson(res, 502, { error: liveModelError(error) });
281
+ if (!res.destroyed && !res.writableEnded) sendJson(res, error.statusCode || 502, { error: /^m365_[a-z0-9_]+$/.test(error.code || "") ? `Model catalog unavailable / ${error.code}` : liveModelError(error) });
217
282
  } finally { abort.cleanup(); }
218
283
  return;
219
284
  }
@@ -221,13 +286,13 @@ export async function handleDashboardApi(req, res, pathname, {
221
286
  if (pathname === USAGE_PATH && req.method === "GET") {
222
287
  const query = new URL(req.url, "http://localhost").searchParams;
223
288
  const provider = query.get("provider") || "";
224
- if (provider && !["github", "m365"].includes(provider)) { sendJson(res, 400, { error: "Select GitHub or Microsoft 365" });return; }
289
+ if (provider && !isProviderId(provider)) { sendJson(res, 400, { error: "Select a valid provider" });return; }
225
290
  let analytics = null;
226
291
  if (query.get("analytics") === "1") {
227
292
  try {
228
293
  const timeZone = query.get("time_zone") || "UTC";
229
294
  if (timeZone.length > 100) throw new Error("Invalid time zone");
230
- analytics = createUsageAnalytics({ timeZone });
295
+ analytics = createUsageAnalytics({ timeZone, qualifyProviders: !provider });
231
296
  } catch {
232
297
  sendJson(res, 400, { error: "Select a valid usage time zone" });
233
298
  return;
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"]],
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;
@@ -1,4 +1,5 @@
1
1
  import os from "node:os";
2
+ import { publicModelCatalog } from "./provider-metadata.mjs";
2
3
  import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
3
4
  import { githubTokenFingerprint } from "./github-identity.mjs";
4
5
  import { validateGithubToken } from "./auth.mjs";
@@ -82,16 +83,17 @@ export async function fetchLiveCopilotModels({
82
83
  timeoutMs = DEFAULT_MODELS_TIMEOUT_MS,
83
84
  vscodeVersion = FALLBACK_VSCODE_VERSION,
84
85
  signal,
86
+ includeAll = false,
85
87
  } = {}) {
86
88
  const credentials = readModelCredentials(home);
87
89
  let flights = modelFlights.get(fetchImpl);
88
90
  if (!flights) { flights = createAbortAwareSingleflight();modelFlights.set(fetchImpl, flights); }
89
- const key = `${home}\0${githubTokenFingerprint(credentials.token)}\0${vscodeVersion}\0${timeoutMs}`;
90
- const result = await flights.run(key, sharedSignal => lookupLiveModels(credentials, { fetchImpl, timeoutMs, vscodeVersion, signal: sharedSignal }), { signal });
91
+ const key = `${home}\0${githubTokenFingerprint(credentials.token)}\0${vscodeVersion}\0${timeoutMs}\0${includeAll}`;
92
+ const result = await flights.run(key, sharedSignal => lookupLiveModels(credentials, { fetchImpl, timeoutMs, vscodeVersion, includeAll, signal: sharedSignal }), { signal });
91
93
  return structuredClone(result); // Independent callers retain independent catalog values.
92
94
  }
93
95
 
94
- async function lookupLiveModels(credentials, { fetchImpl, timeoutMs, vscodeVersion, signal }) {
96
+ async function lookupLiveModels(credentials, { fetchImpl, timeoutMs, vscodeVersion, includeAll, signal }) {
95
97
  const controller = new AbortController();
96
98
  const cancel = () => controller.abort(signal.reason);
97
99
  signal.addEventListener("abort", cancel, { once: true });
@@ -135,6 +137,12 @@ async function lookupLiveModels(credentials, { fetchImpl, timeoutMs, vscodeVersi
135
137
  throw new Error("Copilot models endpoint returned invalid JSON");
136
138
  }
137
139
  const catalog = selectableCopilotModels(payload);
140
+ if (includeAll) {
141
+ const selected = new Set(catalog.models.map(model => model.id));
142
+ catalog.models = publicModelCatalog(Array.isArray(payload) ? payload : payload.data, {
143
+ selectable: model => selected.has(model.id), clients: model => selected.has(model.id) ? ["codex"] : [],
144
+ });
145
+ }
138
146
  let upstreamHost = "GitHub Copilot";
139
147
  try { upstreamHost = new URL(apiBase).hostname; } catch {}
140
148
  return { ...catalog, profile: AUTH_PROFILE_CODEX, upstreamHost: safeText(upstreamHost, "GitHub Copilot") };
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"]);
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"
@@ -0,0 +1,21 @@
1
+ // Public metadata only. Credentials and provider transport never enter this layer.
2
+ export const isProviderId = value => typeof value === "string" && /^[a-z][a-z0-9_-]{0,63}$/.test(value)
3
+ && !["constructor", "prototype"].includes(value);
4
+
5
+ export function modelReasoningEfforts(model) {
6
+ const values = model?.capabilities?.supports?.reasoning_effort;
7
+ return Array.isArray(values) ? [...new Set(values.filter(value => typeof value === "string" && /^[a-z][a-z0-9_-]{0,15}$/.test(value)))].slice(0, 16) : null;
8
+ }
9
+
10
+ export function publicModelCatalog(models, { clients = () => [], selectable = () => false } = {}) {
11
+ return models.slice(0, 1000).filter(model => typeof model?.id === "string").map(model => ({
12
+ id: model.id, vendor: model.publisher || model.vendor || model.owned_by || "Unknown",
13
+ endpoints: [["responses", ["/responses", "/v1/responses"]], ["chat", ["/chat/completions", "/v1/chat/completions"]],
14
+ ["messages", ["/v1/messages"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
15
+ preview: model.preview === true, selectable: selectable(model), clients: clients(model),
16
+ reasoning_efforts: modelReasoningEfforts(model),
17
+ context_window: Number.isSafeInteger(model.capabilities?.limits?.max_context_window_tokens)
18
+ && model.capabilities.limits.max_context_window_tokens > 0 ? model.capabilities.limits.max_context_window_tokens : null,
19
+ state: model.policy?.state && model.policy.state !== "enabled" ? "restricted" : model.model_picker_enabled === false ? "hidden" : "listed",
20
+ }));
21
+ }