codex-copilot-dx 1.1.1 → 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.
package/src/launcher.mjs CHANGED
@@ -99,7 +99,7 @@ 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;
@@ -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
 
@@ -141,7 +141,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
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);
@@ -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) {
@@ -26,7 +26,7 @@ export function startupCheck(kind, name, detail) {
26
26
  }
27
27
 
28
28
  export function startupReady({ baseUrl, commandName = "ccdx", reused = false } = {}) {
29
- return ["", startupCheck("ok", "Ready", reused ? "Using the existing CCDX adapter" : "Core service available"), "",
29
+ return ["", startupCheck("ok", "Ready", reused ? "Using the running service" : "Local service ready"), "",
30
30
  `Web UI ${baseUrl}`, `Help ${commandName} help`, ...(!reused ? ["Stop Ctrl+C"] : []), ""].join("\n");
31
31
  }
32
32
 
@@ -40,15 +40,15 @@ export function startupLogger(name, output = console.log) {
40
40
  }
41
41
 
42
42
  export function predictionStartupCheck(prediction) {
43
- if (!prediction?.configured) return startupCheck("info", "Prediction", "Off");
43
+ if (!prediction?.configured) return startupCheck("info", "Suggestions", "Off");
44
44
  const environment = prediction.environment?.status;
45
45
  const problem = ["unavailable", "needs_service_restart", "needs_app_relaunch"].includes(environment);
46
46
  let detail = prediction.bridge !== "running" ? prediction.bridge === "recovering" ? "Bridge recovering" : "Bridge unavailable"
47
47
  : prediction.active === false ? "Paused; trust and route retained"
48
- : `Running; App route ${prediction.launch_route === "verified" ? "verified" : prediction.launch_route === "persisted" ? "saved, not verified" : "not verified"}; suggestion unchecked`;
48
+ : "Running; suggestion display not verified";
49
49
  if (problem) detail += environment === "needs_service_restart" ? "; restart CCDX" : environment === "needs_app_relaunch" ? "; relaunch Codex" : "; environment unavailable";
50
50
  const warning = prediction.bridge !== "running" || problem || prediction.launch_route === "unverified";
51
- const lines = [startupCheck(warning ? "warn" : "info", "Prediction", detail)];
51
+ const lines = [startupCheck(warning ? "warn" : "info", "Suggestions", detail)];
52
52
  if (prediction.bridge !== "running" && prediction.reason) lines.push(startupCheck("warn", "Reason", prediction.reason));
53
53
  if (warning) lines.push(startupCheck("info", "Details", "ccdx prediction status"));
54
54
  return lines.join("\n");
@@ -64,16 +64,24 @@ export function providerStartupSummary(data = {}) {
64
64
  const catalog = (name, value) => `${name} ${value.models ?? value.total} (${value.source})`;
65
65
  const m365State = { disabled: "off", unsupported: "unsupported", checking: "checking", idle: "not checked", unavailable: "unavailable", ready: "ready" }[ms?.state] || "unknown";
66
66
  const count = Number(githubFound) + Number(m365Found);
67
- const catalogs = `${count} catalog${count === 1 ? "" : "s"} found / ${githubFound ? catalog("GitHub", github) : github ? "GitHub not discovered" : "GitHub not checked"}; ${m365Found ? `${catalog("M365", ms.models)}${ms.state !== "ready" ? `, ${m365State}` : ""}` : `M365 ${m365State}`}`;
68
- const states = { configured: "configured", partially_preserved: "partly configured; custom settings kept", preserved: "custom/managed settings kept", not_installed: "not installed", configuration_unavailable: "config unreadable", not_configured: "not checked" };
67
+ const sourceLines = [`${count} source${count === 1 ? "" : "s"} with model lists`,
68
+ githubFound ? catalog("GitHub", github) : github ? "GitHub not discovered" : "GitHub not checked",
69
+ m365Found ? `${catalog("M365", ms.models)}${ms.state !== "ready" ? `, ${m365State}` : ""}` : `M365 ${m365State}`];
70
+ const catalogs = `${sourceLines[0]} / ${sourceLines.slice(1).join("; ")}`;
71
+ const states = { configured: "configured", restored: "settings restored", partially_preserved: "partly configured; custom settings kept", preserved: "custom/managed settings kept", not_installed: "not installed", configuration_unavailable: "config unreadable", not_configured: "not checked" };
69
72
  const client = id => states[ms?.claude?.clients?.[id]] || "not checked";
70
73
  const gatewayReason = ms?.claude?.reason === "m365_no_claude_models" ? "no Claude models" : m365State;
71
- const gateway = ms?.claude?.gateway === "running" ? "gateway running" : `gateway off (${gatewayReason})`;
74
+ const gateway = ms?.claude?.gateway === "running" ? "local service running" : `local service off (${gatewayReason})`;
72
75
  const claude = `Code: ${client("code")} / App: ${client("app")} / ${gateway}`;
73
- return { catalogs, claude, warning: Object.values(ms?.claude?.clients || {}).includes("configuration_unavailable") };
76
+ const shortStates = { configured: "set", restored: "restored", partially_preserved: "partial", preserved: "custom kept", not_installed: "not installed", configuration_unavailable: "unreadable" };
77
+ return { catalogs, claude, sourceLines, claudeLines: [`Claude Code: ${client("code")}`, `Claude App: ${client("app")}`, gateway],
78
+ compactSources: [`Lists ${count} / ${githubFound ? catalog("GitHub", github) : "GitHub not checked"}`, m365Found ? catalog("M365", ms.models) : `M365 ${m365State}`],
79
+ compactClaude: [`Code: ${shortStates[ms?.claude?.clients?.code] || "unchecked"} / App: ${shortStates[ms?.claude?.clients?.app] || "unchecked"}`,
80
+ ms?.claude?.gateway === "running" ? "Claude service: running" : `Claude service: off (${gatewayReason})`],
81
+ warning: Object.values(ms?.claude?.clients || {}).includes("configuration_unavailable") };
74
82
  }
75
83
 
76
84
  export function providerStartupChecks(data) {
77
85
  const summary = providerStartupSummary(data);
78
- return `${startupCheck("info", "Providers", summary.catalogs)}\n${startupCheck(summary.warning ? "warn" : "info", "Claude", summary.claude)}`;
86
+ return `${startupCheck("info", "Sources", summary.catalogs)}\n${startupCheck(summary.warning ? "warn" : "info", "Claude", summary.claude)}`;
79
87
  }
@@ -1,5 +1,6 @@
1
1
  import { performance } from "node:perf_hooks";
2
2
  import { currentRequestContext } from "./request-context.mjs";
3
+ import { isProviderId } from "./provider-metadata.mjs";
3
4
 
4
5
  const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
5
6
  const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
@@ -11,6 +12,7 @@ const TERMINAL_ORIGINS = new Set([
11
12
  ]);
12
13
  const MAX_MODEL_OUTCOME_LABELS = 32;
13
14
  const MAX_RECENT_REQUESTS = 20;
15
+ const MAX_PROVIDER_LABELS = 16;
14
16
  const PREPARATION_EDGES_MS = Object.freeze([1, 2, 5, 10, 20, 50, 100, 250, 500, 1_000, 5_000, 30_000, 120_000]);
15
17
  const TTFT_EDGES_MS = Object.freeze([
16
18
  100, 200, 300, 500, 700, 1_000, 1_400, 2_000, 2_800, 4_000,
@@ -146,6 +148,7 @@ function createRoutePerformance() {
146
148
  incompleteReasons: Object.create(null),
147
149
  terminalByModel: new Map(),
148
150
  terminalByOrigin: Object.create(null),
151
+ providers: new Map(),
149
152
  };
150
153
  }
151
154
 
@@ -162,6 +165,12 @@ function routeSnapshot(route) {
162
165
  by_model: Object.fromEntries([...route.terminalByModel].map(([model, counts]) => [model, { ...counts }])),
163
166
  by_origin: Object.fromEntries(Object.entries(route.terminalByOrigin).map(([origin, counts]) => [origin, { ...counts }])),
164
167
  },
168
+ by_provider: Object.fromEntries([...route.providers].map(([id, source]) => [id, {
169
+ requests: source.requests, active: source.active, finished: source.finished,
170
+ terminal_outcomes: { totals: { ...source.totals }, by_model: Object.fromEntries([...source.models].map(([model, counts]) => [model, { ...counts }])) },
171
+ request_ttft_ms: histogramSnapshot(source.ttft, "ms"),
172
+ preparation_ms: Object.fromEntries(PREPARATION_STAGES.map(stage => [stage, histogramSnapshot(source.preparation[stage], "ms")])),
173
+ }])),
165
174
  ttft_ms: histogramSnapshot(route.ttft, "ms"),
166
175
  tpot_us: histogramSnapshot(route.tpot, "us"),
167
176
  output_tokens_per_second: {
@@ -197,6 +206,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
197
206
  let finished = false;
198
207
  let model = "other";
199
208
  let provider = null;
209
+ let sourceStats = null;
200
210
  let terminalOutcome = null;
201
211
  let terminalOrigin = null;
202
212
  let incompleteReason = null;
@@ -212,6 +222,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
212
222
  let terminalAt = null;
213
223
  const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null };
214
224
  const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
225
+ const assignProvider = value => {
226
+ if (finished || sourceStats || !isProviderId(value)) return;
227
+ provider = value;
228
+ const label = route.providers.has(value) || route.providers.size < MAX_PROVIDER_LABELS ? value : "other";
229
+ if (!route.providers.has(label)) route.providers.set(label, { requests: 0, active: 0, finished: 0, totals: emptyOutcomes(), models: new Map(),
230
+ ttft: createHistogram(TTFT_EDGES_MS), preparation: Object.fromEntries(PREPARATION_STAGES.map(stage => [stage, createHistogram(PREPARATION_EDGES_MS)])) });
231
+ sourceStats = route.providers.get(label);sourceStats.requests++;sourceStats.active++;
232
+ };
215
233
 
216
234
  return {
217
235
  beginStage(stage) {
@@ -261,13 +279,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
261
279
  }
262
280
  },
263
281
  setOutputTokens(value) {
282
+ if (value === null || value === undefined) return;
264
283
  const tokens = Number(value);
265
284
  if (Number.isFinite(tokens) && tokens >= 0) outputTokens = tokens;
266
285
  },
267
286
  setModel(value) {
268
287
  model = modelLabel(value);
269
288
  },
270
- setProvider(value) { if (["github", "m365"].includes(value)) provider = value; },
289
+ setProvider: assignProvider,
271
290
  attemptCount() { return attempts; },
272
291
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
273
292
  observeContext(values) {
@@ -294,6 +313,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
294
313
  },
295
314
  finish({ failed: finishFailed = false, aborted = false, statusCode = 0 } = {}) {
296
315
  if (finished) return;
316
+ if (!sourceStats) assignProvider("unknown");
297
317
  finished = true;
298
318
  failed ||= finishFailed;
299
319
  const outcome = terminalOutcome || (aborted ? "cancelled" : "unknown");
@@ -309,6 +329,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
309
329
  route.terminalByModel.get(label)[outcome] += 1;
310
330
  route.terminalByOrigin[origin] ||= emptyOutcomes();
311
331
  route.terminalByOrigin[origin][outcome] += 1;
332
+ if (sourceStats) {
333
+ sourceStats.active--;sourceStats.finished++;sourceStats.totals[outcome]++;
334
+ const sourceModel = sourceStats.models.has(model) || sourceStats.models.size < MAX_MODEL_OUTCOME_LABELS ? model : "other";
335
+ if (!sourceStats.models.has(sourceModel)) sourceStats.models.set(sourceModel, emptyOutcomes());
336
+ sourceStats.models.get(sourceModel)[outcome]++;
337
+ if (firstOutputAt !== null) observe(sourceStats.ttft, Math.max(0, firstOutputAt - requestStartedAt));
338
+ for (const stage of PREPARATION_STAGES) observe(sourceStats.preparation[stage], preparationMs[stage]);
339
+ }
312
340
  const finishedAt = now();
313
341
  // Only scalar, allowlisted metadata survives the request; never retain payloads.
314
342
  recentRequests.push({
@@ -15,7 +15,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
15
15
  timers = { setTimeout, clearTimeout }, now = Date.now } = {}) {
16
16
  let running = false, timer = null, lines = 0, active = 0, frame = 0, lastRead = 0, data = {};
17
17
  let notices = 0, lastNotice = "", lastPrintedNotice = "", previous = [];
18
- let content = [], dirty = true;
18
+ let content = [], dirty = true, readFailed = false, updatedAt = null, fits = true;
19
19
  let current = { theme: DEFAULT_TERMINAL_ANIMATION_THEME, terminal_animation_enabled: true };
20
20
  let frameDelay = 1000;
21
21
  const tty = output.isTTY === true && errorOutput.isTTY === true && (!env.CI || flagOff(env.CI)) && env.TERM !== "dumb";
@@ -32,19 +32,29 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
32
32
  };
33
33
  const numbers = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
34
34
  const compact = value => numbers.format(Number(value) || 0);
35
- function table(width, usage, requests, inferenceActive, sum) {
35
+ const wrap = (value, width) => {
36
+ const rows = [];let row = "";
37
+ for (const word of terminalCell(value, { fallback: "" }).split(/\s+/)) {
38
+ if (row && displayWidth(`${row} ${word}`) > width) { rows.push(row);row = ""; }
39
+ row += `${row ? " " : ""}${word}`;
40
+ }
41
+ if (row) rows.push(clip(row, width));return rows;
42
+ };
43
+ function table(width, usage, requests, inferenceActive, sum, compactTitle = false) {
36
44
  const left = Math.floor((width - 3) / 2), right = width - 3 - left;
37
45
  const cell = (label, value, size) => {
38
- const number = value === undefined ? "" : compact(value), inner = size - 2;
46
+ const number = value === undefined ? "" : updatedAt === null && readFailed ? "—" : compact(value), inner = size - 2;
39
47
  const text = clip(label, Math.max(0, inner - displayWidth(number) - (number ? 1 : 0)));
40
48
  return ` ${text}${" ".repeat(Math.max(0, inner - displayWidth(text) - displayWidth(number)))}${number} `;
41
49
  };
42
50
  const row = (a, b) => `│${a}│${b}│`;
43
51
  const rule = (a, b, c) => `${a}${"─".repeat(left)}${b}${"─".repeat(right)}${c}`;
44
- const usageRows = [["Records", usage.records || 0], ["Input total", usage.input_tokens], ["Cache read", usage.cached_input_tokens],
45
- ["Output", usage.output_tokens], ["Partial records", usage.partial_records || 0], ["", undefined]];
46
- const requestRows = [["HTTP calls", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
47
- return [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell("Inference", undefined, right)), rule("├", "┼", "┤"),
52
+ const usageRows = [[left < 23 ? "Records" : "Usage records", usage.records || 0], ["Input", usage.input_tokens], [left < 23 ? "Reused" : "Reused input", usage.cached_input_tokens],
53
+ ["Output", usage.output_tokens], ["Partial usage", usage.partial_records || 0], ["", undefined]];
54
+ const requestRows = [["Requests", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
55
+ const title = compactTitle ? [`┌─ Usage ${"─".repeat(left - 8)}┬─ Inference ${"─".repeat(right - 12)}┐`]
56
+ : [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell("Inference", undefined, right)), rule("├", "┼", "┤")];
57
+ return [...title,
48
58
  ...usageRows.map(([label, value], index) => row(cell(label, value ?? (label ? 0 : undefined), left), cell(...requestRows[index], right))), rule("└", "┴", "┘")];
49
59
  }
50
60
  function render() {
@@ -68,16 +78,29 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
68
78
  const requests = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.total || 0), 0);
69
79
  const inferenceActive = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.active || 0), 0);
70
80
  const providers = providerStartupSummary(data);
71
- content = [`CCDX RUNNING / uptime ${Math.floor((data.uptime_ms || 0) / 60000)}m / ${baseUrl}`,
72
- `Providers / ${providers.catalogs}`, `Claude / ${providers.claude}`].map(line => clip(line, width));
81
+ const heading = readFailed ? updatedAt === null ? "CCDX / No data received" : `CCDX / ${width < 80 ? "Previous data" : "Showing previous data / updated"} / ${new Date(updatedAt).toLocaleTimeString("en-GB")}`
82
+ : `CCDX RUNNING / uptime ${Math.floor((data.uptime_ms || 0) / 60000)}m / ${baseUrl}`;
83
+ content = [clip(heading, width)];
84
+ for (const group of [[`Sources / ${providers.catalogs}`, providers.sourceLines], [`Claude / ${providers.claude}`, providers.claudeLines]]) {
85
+ content.push(...(displayWidth(group[0]) <= width ? [group[0]] : (group[1] || [group[0]]).flatMap(line => wrap(line, width))));
86
+ }
73
87
  content.push(...table(width, usage, requests, inferenceActive, sum));
74
- content.push(clip(`${notices} notices${lastNotice ? ` / latest: ${lastNotice}` : " / details in WebUI"}`, width));
88
+ content.push(clip(`${notices} notices${lastNotice ? ` · latest: ${lastNotice}` : " / details in WebUI"}`, width));
89
+ if (content.length + 1 >= (Number(output.rows) || 24)) {
90
+ const summaries = [...(providers.compactSources || ["Sources: not checked"]), ...(providers.compactClaude || ["Claude: not checked"])];
91
+ content = [clip(heading, width), ...summaries.flatMap(line => wrap(line, width)), ...table(width, usage, requests, inferenceActive, sum, true), content.at(-1)];
92
+ }
75
93
  dirty = false;
76
94
  }
77
95
  const body = [...content, `${motion} ${active ? "Working" : "Idle"}`];
96
+ fits = body.length < (Number(output.rows) || 24);
97
+ if (!fits) { frameDelay = 1000;return; }
78
98
  // Animation ticks update only the final line; data stays on its 1s cadence.
79
99
  let update = "";
80
- if (!lines) update = `${body.map(line => clear + line).join("\n")}\r`;
100
+ if (lines && lines !== body.length) {
101
+ update = `${lines > 1 ? `\x1b[${lines - 1}A` : ""}\r\x1b[J`;lines = 0;previous = [];
102
+ }
103
+ if (!lines) update += `${body.map(line => clear + line).join("\n")}\r`;
81
104
  else for (let index = 0; index < body.length; index++) {
82
105
  if (body[index] === previous[index]) continue;
83
106
  const offset = body.length - 1 - index;
@@ -89,7 +112,11 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
89
112
  function tick() {
90
113
  if (!running) return;
91
114
  if (now() - lastRead >= 1000 || !lastRead) {
92
- try { data = snapshot();current = { ...current, ...preferences() };if (!isTerminalAnimationTheme(current.theme)) current.theme = DEFAULT_TERMINAL_ANIMATION_THEME; } catch {}
115
+ try {
116
+ const next = snapshot(), nextPreferences = preferences();
117
+ data = next;current = { ...current, ...nextPreferences };readFailed = false;updatedAt = now();
118
+ if (!isTerminalAnimationTheme(current.theme)) current.theme = DEFAULT_TERMINAL_ANIMATION_THEME;
119
+ } catch { readFailed = true; }
93
120
  lastRead = now();
94
121
  dirty = true;
95
122
  }
@@ -97,7 +124,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
97
124
  timer = timers.setTimeout(tick, frameDelay);timer?.unref?.();
98
125
  }
99
126
  return {
100
- get enabled() { return supported() && !verbose; },
127
+ get enabled() { return supported() && fits && !verbose; },
101
128
  start() { if (running) return;running = true;tick(); },
102
129
  beginRequest() { active++;dirty = true;let done = false;return () => { if (!done) { done = true;active = Math.max(0, active - 1);dirty = true; } }; },
103
130
  log(method, args) {
@@ -105,9 +132,10 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
105
132
  if (verbose) { (method === "error" || method === "warn" ? errorOutput : output).write(`${message}\n`);return; }
106
133
  if (method !== "error" && method !== "warn" && !/^\[(WARN|ERR)\]/.test(message.trim())) return;
107
134
  notices++;lastNotice = message.replace(/\s+/g, " ").slice(0, 240);dirty = true;
108
- if (!supported() && lastNotice !== lastPrintedNotice) { errorOutput.write(`${lastNotice}\n`);lastPrintedNotice = lastNotice; }
135
+ if ((!supported() || !fits) && lastNotice !== lastPrintedNotice) { errorOutput.write(`${lastNotice}\n`);lastPrintedNotice = lastNotice; }
109
136
  },
110
- snapshot() { return { notices, last_notice: lastNotice || null, mode: verbose ? "verbose" : supported() ? "status" : "plain" }; },
137
+ snapshot() { return { notices, last_notice: lastNotice || null, mode: verbose ? "verbose" : supported() && fits ? "status" : "plain",
138
+ data_state: readFailed ? updatedAt === null ? "unavailable" : "stale" : updatedAt === null ? "unknown" : "current", updated_at: updatedAt === null ? null : new Date(updatedAt).toISOString() }; },
111
139
  apply(value) { if (value.theme && value.theme !== current.theme) frame = 0;current = { ...current, ...value };lastRead = 0; },
112
140
  cleanup() { running = false;if (timer) timers.clearTimeout(timer);timer = null;if (lines) output.write("\n");lines = 0;output.off?.("resize", resized); },
113
141
  };