codex-copilot-dx 1.1.0 → 1.2.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 (42) hide show
  1. package/README.md +4 -4
  2. package/bin/cli.mjs +27 -24
  3. package/docs/ARCHITECTURE.md +22 -3
  4. package/docs/README.md +1 -0
  5. package/docs/REFERENCE.md +35 -10
  6. package/package.json +1 -1
  7. package/src/auth-device-flow.mjs +1 -1
  8. package/src/auth-status.mjs +1 -1
  9. package/src/auto-review-model.mjs +2 -2
  10. package/src/claude-client-lifecycle.mjs +33 -0
  11. package/src/claude-gateway.mjs +15 -6
  12. package/src/cli-auth.mjs +6 -6
  13. package/src/cli-cache.mjs +5 -5
  14. package/src/cli-image.mjs +1 -1
  15. package/src/cli-m365.mjs +5 -5
  16. package/src/cli-models.mjs +2 -2
  17. package/src/cli-options.mjs +26 -26
  18. package/src/cli-status.mjs +6 -1
  19. package/src/dashboard/console.js +58 -26
  20. package/src/dashboard/index.html +95 -87
  21. package/src/dashboard/language.js +779 -362
  22. package/src/dashboard/status.js +53 -41
  23. package/src/dashboard/ui.css +4 -4
  24. package/src/dashboard/ui.js +31 -28
  25. package/src/dashboard/usage.js +16 -16
  26. package/src/dashboard-api.mjs +1 -0
  27. package/src/doctor.mjs +4 -4
  28. package/src/http-transport.mjs +4 -2
  29. package/src/launcher.mjs +14 -14
  30. package/src/native-prediction.mjs +3 -3
  31. package/src/operation-error.mjs +12 -7
  32. package/src/package-update.mjs +3 -3
  33. package/src/provider-registry.mjs +19 -0
  34. package/src/provider-runtime.mjs +22 -27
  35. package/src/provider-settings.mjs +2 -1
  36. package/src/response-failures.mjs +2 -1
  37. package/src/service-control.mjs +4 -5
  38. package/src/startup-ui.mjs +45 -11
  39. package/src/stream-performance.mjs +29 -1
  40. package/src/terminal-console.mjs +82 -27
  41. package/src/usage-store.mjs +10 -5
  42. package/src/user-settings.mjs +16 -3
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
  }
@@ -99,13 +99,13 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
99
99
  child.once("error", () => resolve(false));
100
100
  child.once("spawn", () => { child.unref(); resolve(true); });
101
101
  });
102
- if (!launched) { onPredictionRoute("unverified");log(status("warn", "Could not launch the registered Windows Codex App"));return false; }
102
+ if (!launched) { onPredictionRoute("unverified");log(status("warn", "Could not open the registered Codex App"));return false; }
103
103
  await new Promise(resolve => setTimeout(resolve, 300));
104
104
  const actual = windowsAppProcesses(current.app, { env });
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) {
@@ -114,13 +114,13 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
114
114
  }
115
115
  }
116
116
  if (platform !== "darwin") {
117
- log(status("warn", "Automatic launch requires macOS or an enabled Windows prediction setup"));
118
- log(status("info", "Open Codex App manually; it will connect to the adapter."));
117
+ log(status("warn", "Auto-open needs macOS or Windows suggestion setup."));
118
+ log(status("info", "Open Codex App to use this service."));
119
119
  return false;
120
120
  }
121
121
 
122
122
  if (!autoLaunchEnabled(env)) {
123
- log(status("info", "Auto-launch disabled (CCDX_AUTO_LAUNCH=0); open Codex App manually."));
123
+ log(status("info", "Auto-open is off. Open Codex App manually.\nCCDX_AUTO_LAUNCH=0"));
124
124
  return false;
125
125
  }
126
126
 
@@ -132,21 +132,21 @@ 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
  }
142
142
  await preparePredictionRoute?.();
143
143
  if (!await tryOpen([predictionApp, ...extraArgs], { spawnImpl })) {
144
- onPredictionRoute("unverified");log(status("warn", "Could not launch the verified macOS Codex App"));return false;
144
+ onPredictionRoute("unverified");log(status("warn", "Could not open Codex App"));return false;
145
145
  }
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));
@@ -161,13 +161,13 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
161
161
  for (const attempt of attempts) {
162
162
  const args = [...attempt, ...extraArgs];
163
163
  if (await tryOpen(args, { spawnImpl })) {
164
- log(status("ok", "Codex app launched"));
164
+ log(status("ok", "Codex opened"));
165
165
  return true;
166
166
  }
167
167
  }
168
168
 
169
- log(status("warn", "Could not launch the Codex app (checked com.openai.codex, Codex.app, ChatGPT.app)"));
170
- log(status("info", "Open Codex App manually; it will connect to the adapter."));
169
+ log(status("warn", "Could not find or open Codex App.\nChecked com.openai.codex, Codex.app and ChatGPT.app."));
170
+ log(status("info", "Open Codex App to use this service."));
171
171
  log(status("info", "Download it from https://openai.com/codex"));
172
172
  return false;
173
173
  }
@@ -35,10 +35,10 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
35
35
  const settings = readPredictionSettings(opts);
36
36
  if (action === "fix") {
37
37
  if (!settings.enabled) {
38
- output("Native predictions are off; nothing was enabled or changed. Run ccdx prediction on to opt in.");
38
+ output("Input suggestions are off. Nothing changed.\nTo enable: ccdx prediction on");
39
39
  return { status: "disabled", exitCode: 0 };
40
40
  }
41
- if (!repairRuntime) throw new Error("Prediction repair needs a running CCDX adapter with prediction-fix support");
41
+ if (!repairRuntime) throw new Error("Start a CCDX version that supports suggestion repair.");
42
42
  const result = await repairRuntime();
43
43
  const prediction = result.prediction;
44
44
  output(`Prediction repair: ${result.status}; bridge: ${prediction.bridge}; candidate: ${prediction.candidate}`);
@@ -74,7 +74,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
74
74
  }
75
75
  return settings;
76
76
  }
77
- if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, status, or fix");
77
+ if (!["on", "off"].includes(action)) throw new Error("Choose prediction on, off, status or fix.");
78
78
  if (!["darwin", "win32"].includes(platform)) throw new Error("Native prediction setup supports macOS and Windows only; no configuration changed");
79
79
  let paths = predictionPaths({ ...opts, app: settings.app });
80
80
  if (action === "off") {
@@ -4,19 +4,24 @@ export function operationError(code, message, { status = null, retryAt = null }
4
4
  return Object.assign(new Error(message), { code, status, retryAt });
5
5
  }
6
6
 
7
- export function operationErrorDetails(error) {
8
- const code = String(error?.code || error?.cause?.code || "unknown");
7
+ export function operationErrorDetails(error, { reason } = {}) {
8
+ const code = String(reason || error?.code || error?.cause?.code || "unknown");
9
+ const status = Number.isInteger(error?.status) ? error.status : Number.isInteger(error?.statusCode) ? error.statusCode : null;
9
10
  let source = "unknown";
10
- if (/proxy/i.test(code)) source = "proxy";
11
+ if (["client_aborted", "client_closed", "cancelled"].includes(code)) source = "cancelled";
12
+ else if (/proxy/i.test(code)) source = "proxy";
11
13
  else if (/cert|tls|ssl/i.test(code)) source = "tls";
12
- else if (/timeout|abort/i.test(code) || error?.name === "AbortError" || error?.name === "TimeoutError") source = "timeout";
13
- else if (/limit|429/.test(code)) source = "rate_limit";
14
+ else if (/timeout|timed_out/i.test(code) || error?.name === "TimeoutError") source = "timeout";
15
+ else if (/abort/i.test(code) || error?.name === "AbortError") source = "aborted";
16
+ else if (status === 429 || /limit|429/.test(code)) source = "rate_limit";
17
+ else if (status === 401) source = "authentication";
18
+ else if (status === 403) source = "access_denied";
14
19
  else if (/config|format|route|redirect/.test(code)) source = "configuration";
15
- else if (/HTTP|http/.test(code)) source = "upstream";
16
20
  else if (/ENOTFOUND|ECONN|EAI_/.test(code)) source = "network";
21
+ else if (/HTTP|http/.test(code) || status >= 400) source = "upstream";
17
22
  return { code: /^[A-Za-z0-9_-]{1,80}$/.test(code) ? code : "unknown", source,
18
23
  message: redactDiagnosticText(String(error?.message || "Operation failed")).slice(0, 400),
19
- status: Number.isInteger(error?.status) ? error.status : null };
24
+ status };
20
25
  }
21
26
 
22
27
  // Error classifiers consume decoded string fields; responses retain their
@@ -78,7 +78,7 @@ export function inspectNpmDownloadPolicy({ env = process.env, platform = process
78
78
  export function globalUpdateCommand(source, { platform = process.platform, releaseTag, allowRemote = false } = {}) {
79
79
  if (typeof allowRemote !== "boolean") throw new Error("Remote download permission must be a boolean");
80
80
  const normalized = normalizeUpdateSource(source);
81
- if (!normalized) throw new Error(`Update source must be npm or github: ${source}`);
81
+ if (!normalized) throw new Error(`Choose npm or github. Received: ${source}`);
82
82
  const args = ["install", "--global"];
83
83
  if (allowRemote) args.push("--allow-remote=all");
84
84
  if (normalized === "github") {
@@ -140,7 +140,7 @@ export async function runPackageUpdateCommand({
140
140
  } = {}) {
141
141
  if (typeof allowRemote !== "boolean") throw new Error("Remote download permission must be a boolean");
142
142
  let selectedSource = normalizeUpdateSource(source);
143
- if (source && !selectedSource) throw new Error(`Update source must be npm or github: ${source}`);
143
+ if (source && !selectedSource) throw new Error(`Choose npm or github. Received: ${source}`);
144
144
 
145
145
  if (!selectedSource) {
146
146
  if (!prompt && (!input.isTTY || !output.isTTY)) {
@@ -158,7 +158,7 @@ export async function runPackageUpdateCommand({
158
158
  });
159
159
  try {
160
160
  while (!selectedSource) {
161
- const answer = String(await ask("Select update source [1], or q to cancel: ") || "").trim().toLowerCase();
161
+ const answer = String(await ask("Choose update source [1], or q to cancel: ") || "").trim().toLowerCase();
162
162
  if (answer === "q" || answer === "quit") {
163
163
  output.write("No changes made.\n");
164
164
  return { cancelled: true, source: "" };
@@ -0,0 +1,19 @@
1
+ import { isProviderId } from "./provider-metadata.mjs";
2
+
3
+ // Internal composition metadata, never a loader for third-party code.
4
+ export const PROVIDER_DEFINITIONS = Object.freeze([
5
+ Object.freeze({ id: "github", name: "GitHub Copilot", codex: true, modelSelection: false }),
6
+ Object.freeze({ id: "m365", name: "Microsoft 365", codex: true, modelSelection: true }),
7
+ ]);
8
+
9
+ export function createProviderRegistry(definitions = PROVIDER_DEFINITIONS) {
10
+ const entries = new Map();
11
+ if (!Array.isArray(definitions) || definitions.length > 16) throw new Error("Invalid source registry");
12
+ for (const definition of definitions) {
13
+ if (!isProviderId(definition?.id) || entries.has(definition.id) || typeof definition.name !== "string" || !definition.name.trim()) throw new Error("Invalid or duplicate source");
14
+ entries.set(definition.id, Object.freeze({ ...definition }));
15
+ }
16
+ return Object.freeze({ get: id => entries.get(id), list: () => [...entries.values()] });
17
+ }
18
+
19
+ export const providerRegistry = createProviderRegistry();
@@ -3,6 +3,8 @@ import { publicModelCatalog } from "./provider-metadata.mjs";
3
3
  import { createGithubProvider } from "./providers/github.mjs";
4
4
  import { readProviderSettings, writeProviderSettings } from "./provider-settings.mjs";
5
5
  import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey } from "./m365-settings.mjs";
6
+ import { providerRegistry } from "./provider-registry.mjs";
7
+ import { createClaudeClientLifecycle } from "./claude-client-lifecycle.mjs";
6
8
 
7
9
  const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
8
10
  { code: reason, statusCode: 503 });
@@ -15,7 +17,9 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
15
17
  profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
16
18
  return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
17
19
  let selection = readProviderSettings(options), m365 = null, gateway = null, pending = null, closed = false, serial = null;
18
- let reason = null, claudeReason = null, clients = { code: "not_configured", app: "not_configured" }, lastClients = {};
20
+ let reason = null, claudeReason = null, lastClients = {};
21
+ const clientLifecycle = createClaudeClientLifecycle({ options, configureClients, restoreClients });
22
+ const sources = new Map([[github.id, github]]);
19
23
  const dashboardProfiles = new Map();
20
24
  const dashboardGeneration = provider => {
21
25
  const profile = provider.profileId(), previous = dashboardProfiles.get(provider.id);
@@ -27,23 +31,12 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
27
31
  try { enabled = readM365Settings(options).enabled && env.CCDX_M365 !== "0"; }
28
32
  catch { enabled = false;reason = "m365_config_invalid"; }
29
33
 
30
- let clientSync = null;
31
34
  async function syncClaudeClients() {
32
- if (clientSync) return clientSync;
33
- clientSync = (async () => {
34
- const source = m365, profile = source?.profileId();
35
- if (!source || !gateway || closed || !enabled) return;
36
- try {
37
- const integration = configureClients ? null : await import("./claude-client-config.mjs");
38
- const configure = configureClients || integration.configureClaudeClients;
39
- const desktopManaged = integration ? await integration.inspectClaudeDesktopPolicy(options) : false;
40
- if (closed || !enabled || source !== m365 || source.profileId() !== profile || !gateway) return;
41
- claudeReason = source.models("claude").length ? null : "m365_no_claude_models";
42
- clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${corePort}/anthropic`,
43
- apiKey: ensureM365GatewayKey(options), models: source.models("claude") });
44
- } catch { clients = { code: "configuration_unavailable", app: "configuration_unavailable" };claudeReason = "m365_claude_config_unavailable"; }
45
- })().finally(() => { clientSync = null; });
46
- return clientSync;
35
+ const source = m365, profile = source?.profileId();
36
+ if (!source || !gateway || closed || !enabled) return;
37
+ await clientLifecycle.sync({ source, baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: () => ensureM365GatewayKey(options),
38
+ current: () => !closed && enabled && source === m365 && source.profileId() === profile && Boolean(gateway) });
39
+ claudeReason = clientLifecycle.snapshot().reason || (source.models("claude").length ? null : "m365_no_claude_models");
47
40
  }
48
41
 
49
42
  async function startM365(forceRefresh = false) {
@@ -58,6 +51,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
58
51
  // Reconcile after refresh, outside inference serialization and without a watcher.
59
52
  setImmediate(() => { if (!pending && gateway && !closed && enabled) void syncClaudeClients(); });
60
53
  } });
54
+ sources.set(m365.id, m365);
61
55
  }
62
56
  await m365.refresh();if (closed || !enabled) return null;
63
57
  const claudeModels = m365.models("claude");
@@ -93,20 +87,20 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
93
87
  preference: selection.m365 || null,
94
88
  active_requests: activeM365Requests,
95
89
  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 },
90
+ base_url: gateway ? `http://127.0.0.1:${corePort}/anthropic` : null, clients: clientLifecycle.snapshot().clients,
97
91
  observed_clients: { ...lastClients }, requests: gateway?.snapshot?.() || null } } });
98
92
 
99
93
  function current() {
100
- if (selection.codex === "github") return github;
101
- if (!m365 || !enabled || m365.snapshot().state === "disabled") throw unavailable(reason || "m365_not_ready");
102
- return m365;
94
+ const source = sources.get(selection.codex);
95
+ if (!source || selection.codex === "m365" && (!enabled || source.snapshot().state === "disabled")) throw unavailable(reason || "m365_not_ready");
96
+ return source;
103
97
  }
104
98
  const serialize = task => {
105
99
  const next = (serial || Promise.resolve()).then(task);
106
100
  serial = next.catch(() => {});return next;
107
101
  };
108
102
  async function switchSource(provider, preference) {
109
- if (!["github", "m365"].includes(provider)) throw new Error("Provider must be github or m365");
103
+ if (!providerRegistry.get(provider)?.codex) throw new Error("Choose a listed Codex source");
110
104
  if (provider === "m365") {
111
105
  if (!enabled) throw unavailable("m365_disabled");
112
106
  const ready = await startM365();if (!ready) throw unavailable(reason || "m365_not_ready");
@@ -131,9 +125,8 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
131
125
  await switchSource("github");
132
126
  updateM365Settings({ enabled: false }, options);enabled = false;
133
127
  await gateway?.close();gateway = null;m365?.close();
134
- await pending;m365 = null;
135
- const restore = restoreClients || (await import("./claude-client-config.mjs")).restoreClaudeClients;
136
- const result = restore(options);clients = { code: result.preserved ? "preserved" : "restored", app: result.preserved ? "preserved" : "restored" };
128
+ await pending;sources.delete("m365");m365 = null;
129
+ const result = await clientLifecycle.restore();
137
130
  if (remove) {
138
131
  if (result.remaining) throw Object.assign(new Error("User-modified Claude settings were preserved; M365 profile cleanup is incomplete"), { code: "m365_cleanup_preserved" });
139
132
  const paths = m365Paths(options);
@@ -156,7 +149,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
156
149
  selection: () => selection,
157
150
  dashboardProviders() {
158
151
  const state = snapshot(), service = githubClient.runtimeStatus?.() || {}, ms = state.m365;
159
- return [
152
+ const projections = [
160
153
  { id: "github", name: "GitHub Copilot", generation: dashboardGeneration(github), enabled: true, state: service.token_cached ? "ready" : "unknown",
161
154
  auth: { state: "unknown", token_cached: service.token_cached === true, expires_in_ms: service.token_expires_in_ms ?? null },
162
155
  models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
@@ -168,10 +161,12 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
168
161
  models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
169
162
  clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "m365", state: selection.codex === "m365" ? ms.state : "standby" },
170
163
  ...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
171
- selected: enabled, state: clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
164
+ selected: enabled, state: clientLifecycle.snapshot().clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
172
165
  last_request_at: lastClients[`claude_${id}`] || null }))],
173
166
  requests: ms.claude.requests, request_scope: "Claude Messages" },
174
167
  ];
168
+ return providerRegistry.list().map(definition => ({ ...projections.find(source => source.id === definition.id),
169
+ id: definition.id, name: definition.name, selection: { codex: definition.codex, models_required: definition.modelSelection } }));
175
170
  },
176
171
  async dashboardCatalog({ provider = selection.codex } = {}) {
177
172
  if (provider === "github") return null;
@@ -4,13 +4,14 @@ import { userSettingsPath } from "./user-settings.mjs";
4
4
  import { readBoundedFileSync } from "./bounded-file.mjs";
5
5
  import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
6
6
  import { withFileLockSync } from "./lock.mjs";
7
+ import { providerRegistry } from "./provider-registry.mjs";
7
8
 
8
9
  export function providerSettingsPath(options = {}) {
9
10
  return path.join(path.dirname(userSettingsPath(options)), "providers.json");
10
11
  }
11
12
  const invalid = () => Object.assign(new Error("Provider selection is invalid; review providers.json before starting ccdx. The existing file was preserved"), { code: "ccdx_provider_selection_invalid" });
12
13
  function checked(value) {
13
- if (!value || value.version !== 1 || !["github", "m365"].includes(value.codex)) throw invalid();
14
+ if (!value || value.version !== 1 || !providerRegistry.get(value.codex)?.codex) throw invalid();
14
15
  if (value.m365 !== undefined && (!value.m365 || typeof value.m365 !== "object"
15
16
  || ["model", "auto_review_model"].some(key => typeof value.m365[key] !== "string" || !/^gpt-[\w.-]{1,120}$/.test(value.m365[key])))) throw invalid();
16
17
  if (value.codex === "m365" && !value.m365) throw invalid();
@@ -1,6 +1,7 @@
1
1
  import { terminalCell } from "./terminal-text.mjs";
2
2
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
3
3
  import { currentRequestContext } from "./request-context.mjs";
4
+ import { isProviderId } from "./provider-metadata.mjs";
4
5
 
5
6
  const DEFAULT_RECENT_FAILURES = 10;
6
7
 
@@ -41,7 +42,7 @@ export function responseFailureDetails(event, eventType = event?.type, {
41
42
  return {
42
43
  at: new Date().toISOString(),
43
44
  request_id: currentRequestContext()?.requestId || null,
44
- ...(["github", "m365"].includes(provider) ? { provider } : {}),
45
+ ...(isProviderId(provider) ? { provider } : {}),
45
46
  event_type: safeIdentifier(eventType || "response.failed"),
46
47
  model: safeIdentifier(response?.model || model),
47
48
  code: safeIdentifier(error?.code || "unknown_error"),
@@ -1,4 +1,4 @@
1
- import { readUserSettings, servicePreferences, writeServicePreference, terminalAnimationPreference,
1
+ import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
2
2
  writeTerminalAnimationTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib } from "./user-settings.mjs";
3
3
  import { readImageProviderConfig } from "./image-provider-config.mjs";
4
4
  import { readPredictionSettings } from "./native-prediction-profile.mjs";
@@ -10,12 +10,11 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
10
10
  const options = { env, home };
11
11
  let serial = Promise.resolve();
12
12
  function snapshot() {
13
- readUserSettings({ ...options, strict: true });
14
- const saved = servicePreferences(options), prediction = clientIntegration?.snapshot().prediction;
13
+ const { saved, theme, historyLimit } = serviceSettingsSnapshot(options), prediction = clientIntegration?.snapshot().prediction;
15
14
  let imageConfigured = false, predictionConfigured = false;
16
15
  try { imageConfigured = Boolean(readImages()); } catch {}
17
16
  try { predictionConfigured = readPrediction().enabled === true; } catch {}
18
- return { source: "service_settings", saved, theme: terminalAnimationPreference(options).theme,
17
+ return { source: "service_settings", saved, theme,
19
18
  effective: {
20
19
  terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
21
20
  state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
@@ -23,7 +22,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
23
22
  image_enabled: { value: saved.image_enabled && imageConfigured, state: imageConfigured ? "next_call" : "needs_setup", configured: imageConfigured },
24
23
  prediction_enabled: { value: prediction?.active === true, state: !predictionConfigured ? "needs_setup"
25
24
  : prediction?.environment?.status === "needs_app_relaunch" ? "needs_app_relaunch" : prediction?.bridge !== "running" ? "needs_service_restart" : "next_config_request", configured: predictionConfigured },
26
- }, history: { ...responseHistoryLimitPreference(options), ...cacheRuntimeSnapshot().response_history },
25
+ }, history: { ...historyLimit, ...cacheRuntimeSnapshot().response_history },
27
26
  providers: providerRuntime?.snapshot() || null, terminal: terminal?.snapshot?.() || null };
28
27
  }
29
28
  async function apply(input) {
@@ -1,6 +1,5 @@
1
1
  import { status } from "./status.mjs";
2
2
  import { terminalCell } from "./terminal-text.mjs";
3
- import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
4
3
 
5
4
  // The favicon's three ellipses, rasterized as terminal half-blocks. No runtime
6
5
  // graphics library or terminal cursor control is needed.
@@ -27,7 +26,7 @@ export function startupCheck(kind, name, detail) {
27
26
  }
28
27
 
29
28
  export function startupReady({ baseUrl, commandName = "ccdx", reused = false } = {}) {
30
- return ["", startupCheck("ok", "Ready", reused ? "Using the existing CCDX adapter" : "Core service available"), "",
29
+ return ["", startupCheck("ok", "Ready", reused ? "Using the running service" : "Local service ready"), "",
31
30
  `Web UI ${baseUrl}`, `Help ${commandName} help`, ...(!reused ? ["Stop Ctrl+C"] : []), ""].join("\n");
32
31
  }
33
32
 
@@ -41,13 +40,48 @@ export function startupLogger(name, output = console.log) {
41
40
  }
42
41
 
43
42
  export function predictionStartupCheck(prediction) {
44
- if (!prediction?.configured) return startupCheck("info", "Prediction", "Off");
45
- const details = prediction.environment ? `\n${startupCheck("info", "Environment", formatPredictionEnvironment(prediction.environment))}` : "";
46
- if (prediction.bridge !== "running") return startupCheck("warn", "Prediction", prediction.reason || "Bridge unavailable; core service is available") + details;
47
- const route = prediction.launch_route;
48
- const summary = startupCheck(route === "unverified" ? "warn" : "info", "Prediction", route === "verified"
49
- ? "Bridge running; App route verified; suggestion not checked"
50
- : "Bridge running; App route not verified; suggestion not checked");
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;
43
+ if (!prediction?.configured) return startupCheck("info", "Suggestions", "Off");
44
+ const environment = prediction.environment?.status;
45
+ const problem = ["unavailable", "needs_service_restart", "needs_app_relaunch"].includes(environment);
46
+ let detail = prediction.bridge !== "running" ? prediction.bridge === "recovering" ? "Bridge recovering" : "Bridge unavailable"
47
+ : prediction.active === false ? "Paused; trust and route retained"
48
+ : "Running; suggestion display not verified";
49
+ if (problem) detail += environment === "needs_service_restart" ? "; restart CCDX" : environment === "needs_app_relaunch" ? "; relaunch Codex" : "; environment unavailable";
50
+ const warning = prediction.bridge !== "running" || problem || prediction.launch_route === "unverified";
51
+ const lines = [startupCheck(warning ? "warn" : "info", "Suggestions", detail)];
52
+ if (prediction.bridge !== "running" && prediction.reason) lines.push(startupCheck("warn", "Reason", prediction.reason));
53
+ if (warning) lines.push(startupCheck("info", "Details", "ccdx prediction status"));
54
+ return lines.join("\n");
55
+ }
56
+
57
+ // Catalog discovery, client configuration and inference access are distinct.
58
+ export function providerStartupSummary(data = {}) {
59
+ if (!data.providers) return { catalogs: "Status unavailable; see WebUI", claude: "Configuration not checked", warning: false };
60
+ const providers = data.providers, ms = providers?.m365;
61
+ const github = data.profiles?.codex?.models || (data.models?.provider !== "m365" ? data.models : null);
62
+ const found = catalog => ["cache", "live"].includes(catalog?.source) && Number.isSafeInteger(catalog?.models ?? catalog?.total) && (catalog.models ?? catalog.total) > 0;
63
+ const githubFound = found(github), m365Found = ms?.enabled !== false && found(ms?.models);
64
+ const catalog = (name, value) => `${name} ${value.models ?? value.total} (${value.source})`;
65
+ const m365State = { disabled: "off", unsupported: "unsupported", checking: "checking", idle: "not checked", unavailable: "unavailable", ready: "ready" }[ms?.state] || "unknown";
66
+ const count = Number(githubFound) + Number(m365Found);
67
+ const sourceLines = [`${count} source${count === 1 ? "" : "s"} with model lists`,
68
+ githubFound ? catalog("GitHub", github) : github ? "GitHub not discovered" : "GitHub not checked",
69
+ m365Found ? `${catalog("M365", ms.models)}${ms.state !== "ready" ? `, ${m365State}` : ""}` : `M365 ${m365State}`];
70
+ const catalogs = `${sourceLines[0]} / ${sourceLines.slice(1).join("; ")}`;
71
+ const states = { configured: "configured", restored: "settings restored", partially_preserved: "partly configured; custom settings kept", preserved: "custom/managed settings kept", not_installed: "not installed", configuration_unavailable: "config unreadable", not_configured: "not checked" };
72
+ const client = id => states[ms?.claude?.clients?.[id]] || "not checked";
73
+ const gatewayReason = ms?.claude?.reason === "m365_no_claude_models" ? "no Claude models" : m365State;
74
+ const gateway = ms?.claude?.gateway === "running" ? "local service running" : `local service off (${gatewayReason})`;
75
+ const claude = `Code: ${client("code")} / App: ${client("app")} / ${gateway}`;
76
+ const shortStates = { configured: "set", restored: "restored", partially_preserved: "partial", preserved: "custom kept", not_installed: "not installed", configuration_unavailable: "unreadable" };
77
+ return { catalogs, claude, sourceLines, claudeLines: [`Claude Code: ${client("code")}`, `Claude App: ${client("app")}`, gateway],
78
+ compactSources: [`Lists ${count} / ${githubFound ? catalog("GitHub", github) : "GitHub not checked"}`, m365Found ? catalog("M365", ms.models) : `M365 ${m365State}`],
79
+ compactClaude: [`Code: ${shortStates[ms?.claude?.clients?.code] || "unchecked"} / App: ${shortStates[ms?.claude?.clients?.app] || "unchecked"}`,
80
+ ms?.claude?.gateway === "running" ? "Claude service: running" : `Claude service: off (${gatewayReason})`],
81
+ warning: Object.values(ms?.claude?.clients || {}).includes("configuration_unavailable") };
82
+ }
83
+
84
+ export function providerStartupChecks(data) {
85
+ const summary = providerStartupSummary(data);
86
+ return `${startupCheck("info", "Sources", summary.catalogs)}\n${startupCheck(summary.warning ? "warn" : "info", "Claude", summary.claude)}`;
53
87
  }
@@ -1,5 +1,6 @@
1
1
  import { performance } from "node:perf_hooks";
2
2
  import { currentRequestContext } from "./request-context.mjs";
3
+ import { isProviderId } from "./provider-metadata.mjs";
3
4
 
4
5
  const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
5
6
  const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
@@ -11,6 +12,7 @@ const TERMINAL_ORIGINS = new Set([
11
12
  ]);
12
13
  const MAX_MODEL_OUTCOME_LABELS = 32;
13
14
  const MAX_RECENT_REQUESTS = 20;
15
+ const MAX_PROVIDER_LABELS = 16;
14
16
  const PREPARATION_EDGES_MS = Object.freeze([1, 2, 5, 10, 20, 50, 100, 250, 500, 1_000, 5_000, 30_000, 120_000]);
15
17
  const TTFT_EDGES_MS = Object.freeze([
16
18
  100, 200, 300, 500, 700, 1_000, 1_400, 2_000, 2_800, 4_000,
@@ -146,6 +148,7 @@ function createRoutePerformance() {
146
148
  incompleteReasons: Object.create(null),
147
149
  terminalByModel: new Map(),
148
150
  terminalByOrigin: Object.create(null),
151
+ providers: new Map(),
149
152
  };
150
153
  }
151
154
 
@@ -162,6 +165,12 @@ function routeSnapshot(route) {
162
165
  by_model: Object.fromEntries([...route.terminalByModel].map(([model, counts]) => [model, { ...counts }])),
163
166
  by_origin: Object.fromEntries(Object.entries(route.terminalByOrigin).map(([origin, counts]) => [origin, { ...counts }])),
164
167
  },
168
+ by_provider: Object.fromEntries([...route.providers].map(([id, source]) => [id, {
169
+ requests: source.requests, active: source.active, finished: source.finished,
170
+ terminal_outcomes: { totals: { ...source.totals }, by_model: Object.fromEntries([...source.models].map(([model, counts]) => [model, { ...counts }])) },
171
+ request_ttft_ms: histogramSnapshot(source.ttft, "ms"),
172
+ preparation_ms: Object.fromEntries(PREPARATION_STAGES.map(stage => [stage, histogramSnapshot(source.preparation[stage], "ms")])),
173
+ }])),
165
174
  ttft_ms: histogramSnapshot(route.ttft, "ms"),
166
175
  tpot_us: histogramSnapshot(route.tpot, "us"),
167
176
  output_tokens_per_second: {
@@ -197,6 +206,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
197
206
  let finished = false;
198
207
  let model = "other";
199
208
  let provider = null;
209
+ let sourceStats = null;
200
210
  let terminalOutcome = null;
201
211
  let terminalOrigin = null;
202
212
  let incompleteReason = null;
@@ -212,6 +222,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
212
222
  let terminalAt = null;
213
223
  const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null };
214
224
  const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
225
+ const assignProvider = value => {
226
+ if (finished || sourceStats || !isProviderId(value)) return;
227
+ provider = value;
228
+ const label = route.providers.has(value) || route.providers.size < MAX_PROVIDER_LABELS ? value : "other";
229
+ if (!route.providers.has(label)) route.providers.set(label, { requests: 0, active: 0, finished: 0, totals: emptyOutcomes(), models: new Map(),
230
+ ttft: createHistogram(TTFT_EDGES_MS), preparation: Object.fromEntries(PREPARATION_STAGES.map(stage => [stage, createHistogram(PREPARATION_EDGES_MS)])) });
231
+ sourceStats = route.providers.get(label);sourceStats.requests++;sourceStats.active++;
232
+ };
215
233
 
216
234
  return {
217
235
  beginStage(stage) {
@@ -261,13 +279,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
261
279
  }
262
280
  },
263
281
  setOutputTokens(value) {
282
+ if (value === null || value === undefined) return;
264
283
  const tokens = Number(value);
265
284
  if (Number.isFinite(tokens) && tokens >= 0) outputTokens = tokens;
266
285
  },
267
286
  setModel(value) {
268
287
  model = modelLabel(value);
269
288
  },
270
- setProvider(value) { if (["github", "m365"].includes(value)) provider = value; },
289
+ setProvider: assignProvider,
271
290
  attemptCount() { return attempts; },
272
291
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
273
292
  observeContext(values) {
@@ -294,6 +313,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
294
313
  },
295
314
  finish({ failed: finishFailed = false, aborted = false, statusCode = 0 } = {}) {
296
315
  if (finished) return;
316
+ if (!sourceStats) assignProvider("unknown");
297
317
  finished = true;
298
318
  failed ||= finishFailed;
299
319
  const outcome = terminalOutcome || (aborted ? "cancelled" : "unknown");
@@ -309,6 +329,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
309
329
  route.terminalByModel.get(label)[outcome] += 1;
310
330
  route.terminalByOrigin[origin] ||= emptyOutcomes();
311
331
  route.terminalByOrigin[origin][outcome] += 1;
332
+ if (sourceStats) {
333
+ sourceStats.active--;sourceStats.finished++;sourceStats.totals[outcome]++;
334
+ const sourceModel = sourceStats.models.has(model) || sourceStats.models.size < MAX_MODEL_OUTCOME_LABELS ? model : "other";
335
+ if (!sourceStats.models.has(sourceModel)) sourceStats.models.set(sourceModel, emptyOutcomes());
336
+ sourceStats.models.get(sourceModel)[outcome]++;
337
+ if (firstOutputAt !== null) observe(sourceStats.ttft, Math.max(0, firstOutputAt - requestStartedAt));
338
+ for (const stage of PREPARATION_STAGES) observe(sourceStats.preparation[stage], preparationMs[stage]);
339
+ }
312
340
  const finishedAt = now();
313
341
  // Only scalar, allowlisted metadata survives the request; never retain payloads.
314
342
  recentRequests.push({