codex-copilot-dx 1.2.32 → 1.2.33

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.
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import { randomBytes, createHash } from "node:crypto";
3
3
  import { accessSettingsPath, readAccessSettings, updateAccessSettings, checkedApi, checkedAccessSettings, accessError, CLIENT_IDS, CLIENT_NAMES } from "./access-settings.mjs";
4
4
  import { createApiSecretStore, checkedApiKey } from "./api-secrets.mjs";
5
+ import { publicModelCatalog } from "./provider-metadata.mjs";
5
6
  import { createApiCatalogRefresh } from "./api-catalog-refresh.mjs";
6
7
  import { createApiProvider } from "./providers/api.mjs";
7
8
  import { createApiModelDisplayStore } from "./api-model-display.mjs";
@@ -39,7 +40,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
39
40
  commit: (...args) => enqueue(() => applyCatalog(...args)),
40
41
  onState: (id, state) => state ? discoveries.set(id, state) : discoveries.delete(id) });
41
42
  const capabilitySupport = inspectClaudeCapabilitySupport(options);
42
- let sharedSync = null, syncFlight = null, syncAgain = false, operations = 0;const syncTargets = new Set();
43
+ let sharedSync = null, syncFlight = null, syncAgain = false, operations = 0;const syncTargets = new Set(), manualTargets = new Set();
43
44
  function cleanSecrets(id) {
44
45
  const refs = retiredSecrets.get(id);if (!refs) return;
45
46
  for (const ref of refs) {
@@ -144,14 +145,15 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
144
145
  model_display: Object.fromEntries(api.models.map(model => [model.id, modelDisplay.get(api.id, revision, model.id)])) }), discovery: discoveries.get(api.id) || null, builtin: false, key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref) }; }),
145
146
  ], clients: CLIENT_IDS.map(id => ({ id, name: CLIENT_NAMES[id], ...config.clients[id], setup: setup[id] || null,
146
147
  ...(id === "codex" ? { memory_model: memoryModel.snapshot() } : {}),
147
- observed_at: lastClients[id] || null, ...(compact ? {} : { model_plan: { default_model: plan(id).defaultModel, default_unavailable: plan(id).defaultUnavailable,
148
+ observed_at: lastClients[id] || null, ...(compact ? {} : { revision: clientRevision(id), model_plan: { default_model: plan(id).defaultModel, default_unavailable: plan(id).defaultUnavailable,
148
149
  models: plan(id).models.map(model => ({ source: model.source_id, id: model.id, display_name: model.display_name, public_id: model.public_id, route_id: model.route_id, capability: model.capability })),
149
150
  unavailable: (config.clients[id].deployments || []).filter(item => !plan(id).models.some(model => model.source_id === item.source && model.id === item.model))
150
151
  .map(item => ({ source: item.source, id: item.model, route_id: deploymentModelId(item.source, item.model) })),
151
152
  available: config.clients[id].allowed.filter(enabled).flatMap(source => sourceModels(getSource(source), id).map(model => ({ source, id: model.id,
152
153
  display_name: model.display_name || model.name || model.id, route_id: deploymentModelId(source, model.id), capability: model.capability || resolveModelCapabilities(model, { builtin: true }) }))), sync: sharedSync, support: capabilitySupport } }) })),
153
- ...(!compact ? { source_impacts: Object.fromEntries(["github", "m365", ...config.apis.map(api => api.id)].map(id => [id, sourceImpact(id)])) } : {}), managed, m365_state: state.m365.state });
154
+ ...(!compact ? { source_impacts: Object.fromEntries(["github", "m365", ...config.apis.map(api => api.id)].map(id => [id, sourceImpact(id)])) } : {}), managed, ...(!compact ? { management_version: 1 } : {}), m365_state: state.m365.state });
154
155
  }
156
+ const clientRevision = id => createHash("sha256").update(JSON.stringify(binding(id))).digest("hex");
155
157
  function sourceImpact(source) {
156
158
  const clients = CLIENT_IDS.flatMap(id => {
157
159
  const c = binding(id);if (!c.enabled) return [];
@@ -165,23 +167,23 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
165
167
  const api = settings.apis.find(item => item.id === source), profile = api ? deploymentRevision(api, env) : getSource(source)?.profileId();
166
168
  return { clients, revision: createHash("sha256").update(JSON.stringify([source, enabled(source), profile, CLIENT_IDS.map(id => binding(id))])).digest("hex") };
167
169
  }
168
- async function syncClients(ids = CLIENT_IDS) {
170
+ async function syncClients(ids = CLIENT_IDS, { manual = false } = {}) {
169
171
  if (!ids.length) return;
170
- for (const id of ids) syncTargets.add(id);
172
+ for (const id of ids) { syncTargets.add(id);if (manual) manualTargets.add(id); }
171
173
  syncAgain = true;if (syncFlight) return syncFlight;
172
- syncFlight = (async () => { do { syncAgain = false;const targets = new Set(syncTargets);syncTargets.clear();await performClientSync(targets); } while (syncAgain && !closed); })();
174
+ syncFlight = (async () => { do { syncAgain = false;const targets = new Set(syncTargets);syncTargets.clear();const requested = new Set(manualTargets);manualTargets.clear();await performClientSync(targets, requested); } while (syncAgain && !closed); })();
173
175
  try { return await syncFlight; } finally { syncFlight = null; }
174
176
  }
175
- async function performClientSync(targets) {
177
+ async function performClientSync(targets, requested = new Set()) {
176
178
  if (!managed || closed) return;
177
179
  if (options.preserveClientConfiguration?.()) { for (const id of targets) setup[id] = "preserved";return; }
178
180
  const codex = binding("codex"), compiledCodex = plan("codex");
179
181
  const explicit = Array.isArray(codex.deployments), mode = codexAccessMode(), native = mode === "native";
180
182
  if (targets.has("codex")) try {
181
183
  if (mode === "paused" || mode === "disabled") {
182
- if (mode === "disabled" || codex.auto_sync !== false) configureCodex({ ...options, restore: true });
184
+ if (mode === "disabled" || (codex.auto_sync !== false || requested.has("codex"))) configureCodex({ ...options, restore: true });
183
185
  setup.codex = mode;
184
- } else if (codex.auto_sync === false) setup.codex = "manual_sync";
186
+ } else if (codex.auto_sync === false && !requested.has("codex")) setup.codex = "manual_sync";
185
187
  else if (codex.enabled && compiledCodex.defaultUnavailable && !native) setup.codex = "default_unavailable";
186
188
  else {
187
189
  setup.codex = configureCodex({ ...options, ...(codex.enabled && (native || explicit && codex.deployments.length || codex.source?.startsWith("api_"))
@@ -198,7 +200,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
198
200
  try {
199
201
  if (selected.enabled && compiled.defaultUnavailable) { setup[id] = "default_unavailable";continue; }
200
202
  if (!selected.enabled || !compiled.models.length) { const result = restoreClaude({ ...options, client: id });setup[id] = result.preserved ? "preserved" : "not_configured";continue; }
201
- if (selected.auto_sync === false) { setup[id] = "manual_sync";continue; }
203
+ if (selected.auto_sync === false && !requested.has(id)) { setup[id] = "manual_sync";continue; }
202
204
  if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
203
205
  const m365Only = compiled.models.every(model => model.source_id === "m365");
204
206
  if (id === "claude_code" && !m365Only) restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
@@ -256,13 +258,31 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
256
258
  const refreshApis = () => !closed && managed && !preserveClientConfiguration?.() ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id)) : Promise.resolve();
257
259
  async function change(input) {
258
260
  if (closed) throw accessError("ccdx_connections_closed", 503);
259
- if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "impact_revision", "model", "auto_review_model", "auto_review_effort", "deployments", "default_model", "auto_sync"])) throw accessError("ccdx_connections_action_invalid");
261
+ if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "impact_revision", "model", "auto_review_model", "auto_review_effort", "deployments", "default_model", "auto_sync", "client_revision"])) throw accessError("ccdx_connections_action_invalid");
262
+ if (["client", "preview_client", "sync_client", "client_state"].includes(input.operation) && input.client_revision !== undefined
263
+ && (!CLIENT_IDS.includes(input.id) || input.client_revision !== clientRevision(input.id))) throw accessError("ccdx_connections_conflict", 409);
264
+ if (!["client", "preview_client", "sync_client", "client_state"].includes(input.operation) && input.impact_revision !== undefined
265
+ && input.impact_revision !== sourceImpact(input.id).revision) throw accessError("ccdx_connections_conflict", 409);
266
+ if (input.operation === "sync_client") {
267
+ if (!validObject(input, ["operation", "id", "client_revision"]) || !CLIENT_IDS.includes(input.id) || typeof input.client_revision !== "string") throw accessError("ccdx_connections_action_invalid");
268
+ await syncClients([input.id], { manual: true });return snapshot();
269
+ }
270
+ if (input.operation === "client_state") {
271
+ if (!validObject(input, ["operation", "id", "enabled", "client_revision"]) || !CLIENT_IDS.includes(input.id)
272
+ || typeof input.enabled !== "boolean" || typeof input.client_revision !== "string") throw accessError("ccdx_connections_action_invalid");
273
+ const next = editable();next.clients[input.id].enabled = input.enabled;save(next);
274
+ await syncClients([input.id]);
275
+ if (input.id === "codex") await clientAccessChanged?.(input.enabled);
276
+ return snapshot();
277
+ }
260
278
  const next = editable();let freshRef, previousRef;
261
279
  if (input.operation === "source_access") {
262
- if (input.id !== "m365" || !Array.isArray(input.allowed) || new Set(input.allowed).size !== input.allowed.length || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
280
+ if (!["github", "m365", ...next.apis.map(api => api.id)].includes(input.id) || !Array.isArray(input.allowed) || new Set(input.allowed).size !== input.allowed.length || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
281
+ const api = next.apis.find(api => api.id === input.id);
282
+ if (input.allowed.some(id => input.id === "github" && id !== "codex" || api && !api.endpoints[id === "codex" ? "responses" : "messages"])) throw accessError("ccdx_api_protocol_required");
263
283
  const affected = CLIENT_IDS.filter(id => next.clients[id].allowed.includes(input.id) !== input.allowed.includes(id));
264
284
  const sharedClaude = ["claude_app", "claude_code"].filter(id => next.clients[id].enabled && next.clients[id].source === "m365");
265
- const migrateClaude = !next.claude_private_keys && sharedClaude.length > 0 && affected.some(id => id !== "codex");
285
+ const migrateClaude = input.id === "m365" && !next.claude_private_keys && sharedClaude.length > 0 && affected.some(id => id !== "codex");
266
286
  const targets = new Set();
267
287
  for (const id of affected) {
268
288
  const c = next.clients[id];
@@ -280,6 +300,13 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
280
300
  const retained = migrateClaude ? [...targets].filter(id => id !== "codex" && next.clients[id].enabled && next.clients[id].source === "m365") : [];
281
301
  return { ...snapshot(), client_refresh: retained.filter(id => setup[id] === "configured"),
282
302
  client_review: retained.filter(id => ["preserved", "partially_preserved", "manual_sync", "configuration_unavailable"].includes(setup[id])) };
303
+ } else if (input.operation === "remove_api") {
304
+ const existing = next.apis.find(api => api.id === input.id);
305
+ if (!validObject(input, ["operation", "id", "impact_revision"]) || !existing || existing.enabled || CLIENT_IDS.some(id => binding(id).source === input.id || binding(id).deployments?.some(item => item.source === input.id))) throw accessError("ccdx_source_in_use", 409);
306
+ previousRef = existing.secret_ref;catalogRefresh.cancel(input.id);
307
+ next.apis = next.apis.filter(api => api.id !== input.id);
308
+ for (const id of CLIENT_IDS) next.clients[id].allowed = next.clients[id].allowed.filter(source => source !== input.id);
309
+ save(next);discoveries.delete(input.id);
283
310
  } else if (input.operation === "save_api") {
284
311
  const existing = next.apis.find(api => api.id === input.id);
285
312
  if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
@@ -400,7 +427,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
400
427
  } else throw accessError("ccdx_connections_action_invalid");
401
428
  await syncClients();
402
429
  if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
403
- if (previousRef && (freshRef || input.config?.key_env)) { if (!retiredSecrets.has(input.id)) retiredSecrets.set(input.id, new Set());retiredSecrets.get(input.id).add(previousRef);cleanSecrets(input.id); }
430
+ if (previousRef && (freshRef || input.config?.key_env || input.operation === "remove_api")) { if (!retiredSecrets.has(input.id)) retiredSecrets.set(input.id, new Set());retiredSecrets.get(input.id).add(previousRef);cleanSecrets(input.id); }
404
431
  return snapshot();
405
432
  }
406
433
  return {
@@ -423,6 +450,12 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
423
450
  syncClients,
424
451
  async manageConnections(input) {
425
452
  if (!input) { if (binding("codex").enabled) void memoryModel.refresh();return snapshot(); }
453
+ if (validObject(input, ["operation", "id"]) && input.operation === "source_catalog") {
454
+ if (!["github", "m365", ...settings.apis.map(api => api.id)].includes(input.id)) throw accessError("ccdx_connections_action_invalid");
455
+ const source = getSource(input.id), raw = source?.catalog?.() || source?.registry?.models?.data;
456
+ return { source: input.id, loaded: Array.isArray(raw), evidence: input.id.startsWith("api_") ? "configured" : "cached", access_checked: false,
457
+ models: publicModelCatalog(raw || []).map(({ selectable, clients, ...model }) => model) };
458
+ }
426
459
  if (validObject(input, ["operation", "id"]) && input.operation === "discover") {
427
460
  const models = await catalogRefresh.refresh(input.id, true);return { ...snapshot(), discovered: models };
428
461
  }
@@ -34,7 +34,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
34
34
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
35
35
  const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
36
36
  history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
37
- preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id"], restore_preferences: ["action", "revision", "backup_id"],
37
+ preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
38
38
  provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
39
39
  if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
40
40
  if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
@@ -16,9 +16,9 @@ const idValid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{
16
16
  const valuesFor = settings => Object.fromEntries(keys.map(key => [key, key === "terminal_animation" && !isTerminalAnimationTheme(settings[key])
17
17
  ? SETTINGS_DEFAULTS[key] : settings[key] ?? SETTINGS_DEFAULTS[key]]));
18
18
  const revisionFor = values => createHash("sha256").update(JSON.stringify(keys.map(key => values[key]))).digest("hex");
19
- export const settingsBackupPath = options => path.join(path.dirname(userSettingsPath(options)), "settings-preferences-backup.json");
19
+ export const settingsBackupPath = options => path.join(path.dirname(userSettingsPath(options)), options?.backupScope === "service" ? "service-settings-preferences-backup.json" : "settings-preferences-backup.json");
20
20
 
21
- function checkedValues(values) {
21
+ export function checkedPreferenceValues(values) {
22
22
  if (!values || typeof values !== "object" || Array.isArray(values) || Object.keys(values).some(key => !keys.includes(key)
23
23
  || (key === "terminal_color_theme" ? !isColorTheme(values[key]) : key === "terminal_animation" ? !isTerminalAnimationTheme(values[key]) : typeof values[key] !== "boolean"))) {
24
24
  throw fail("ccdx_settings_values_invalid", "Choose valid settings on this page", 400);
@@ -31,7 +31,7 @@ function readBackup(options) {
31
31
  if (value?.version !== 1 || !idValid(value.id) || typeof value.created_at !== "string" || !Number.isFinite(Date.parse(value.created_at))
32
32
  || Object.keys(value).some(key => !["version", "id", "created_at", "values"].includes(key))
33
33
  || keys.some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
34
- checkedValues(value.values);return value;
34
+ checkedPreferenceValues(value.values);return value;
35
35
  } catch (error) {
36
36
  if (error.code === "ENOENT") return null;
37
37
  throw fail("ccdx_settings_backup_invalid", "The settings backup could not be read; existing files were preserved");
@@ -48,6 +48,8 @@ export function settingsPreferencesSnapshot(options = {}) {
48
48
  // Only this page's preferences enter its backup. Routing, auth, business flags
49
49
  // and unknown settings are retained in the current file, never copied here.
50
50
  export function writeSettingsPreferences(input, options = {}) {
51
+ if (input.scope !== undefined && (!["reset_preferences", "restore_preferences"].includes(input.action) || input.scope !== "service")) throw fail("ccdx_settings_action_invalid", "Unknown backup scope", 400);
52
+ if (input.scope === "service") options = { ...options, backupScope: "service" };
51
53
  const file = userSettingsPath(options);
52
54
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
53
55
  return withFileLockSync(`${file}.lock`, () => {
@@ -58,7 +60,7 @@ export function writeSettingsPreferences(input, options = {}) {
58
60
  throw fail("ccdx_settings_changed", "Settings changed elsewhere. Review the current settings before saving again");
59
61
  }
60
62
  let values;
61
- if (input.action === "preferences") values = checkedValues(input.values);
63
+ if (input.action === "preferences") values = checkedPreferenceValues(input.values);
62
64
  else {
63
65
  if (!idValid(input.backup_id)) throw fail("ccdx_settings_backup_invalid", "Choose the current settings backup", 400);
64
66
  if (input.action === "restore_preferences") {
@@ -2,6 +2,9 @@ import { status } from "./status.mjs";
2
2
  import { terminalCell } from "./terminal-text.mjs";
3
3
  import { colorTerminalText } from "./terminal-colors.mjs";
4
4
  import { terminalColorPreference } from "./user-settings.mjs";
5
+ import { format } from "node:util";
6
+ import { displayWidth } from "./cli-table.mjs";
7
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
5
8
 
6
9
  // The favicon's three ellipses, rasterized as terminal half-blocks. No runtime
7
10
  // graphics library or terminal cursor control is needed.
@@ -18,7 +21,7 @@ export function startupBanner({ commandName = "ccdx", version, stream = process.
18
21
  const title = `${terminalCell(commandName)} v${terminalCell(version)} by Dale Xiao`;
19
22
  const color = stream.isTTY === true && !Object.hasOwn(env, "NO_COLOR") && env.TERM !== "dumb";
20
23
  if (!color || Number(stream.columns || 80) < 72) return `${title}\nLocal model services for Codex and Claude`;
21
- const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Codex + Claude / local services"]]);
24
+ const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Local model gateway"]]);
22
25
  const theme = colorTheme || terminalColorPreference({ env, home });
23
26
  return ATOM.map((line, i) => `${colorTerminalText(line, theme, { output: stream, env })}${labels.has(i) ? ` ${labels.get(i)}` : ""}`).join("\n");
24
27
  }
@@ -42,6 +45,31 @@ export function startupLogger(name, output = console.log) {
42
45
  };
43
46
  }
44
47
 
48
+ // One transient startup row. Authorization instructions and warnings remain
49
+ // visible; only ordinary structured checks are replaced by the live region.
50
+ export function createStartupPresentation({ output = process.stdout, errorOutput = process.stderr, env = process.env, verbose = false } = {}) {
51
+ const enabled = !verbose && output.isTTY === true && errorOutput.isTTY === true && env.TERM !== "dumb"
52
+ && (!env.CI || /^(0|false|no|off)$/i.test(env.CI)) && (output.columns || 80) >= 40 && (output.rows || 24) >= 16;
53
+ let visible = false;const warnings = [];
54
+ function clear() { if (visible) output.write("\r\x1b[2K");visible = false; }
55
+ return { enabled, warnings, finish: clear,
56
+ log(method, args) {
57
+ const message = redactDiagnosticText(format(...args));
58
+ const warning = method === "error" || method === "warn" || /^\s*\[(?:WARN|ERR)\]/.test(message);
59
+ const check = /^\[(?:OK|INFO|WAIT)\]\s+([A-Za-z-]+)\s+(.*)$/.exec(message);
60
+ if (!enabled || warning || !check || ["Sign-in", "GitHub"].includes(check[1]) && !/GitHub token found|saved sign-in/i.test(check[2])) {
61
+ clear();(warning ? errorOutput : output).write(message + "\n");
62
+ if (warning && warnings.length < 100) warnings.push([method, args]);return;
63
+ }
64
+ const scope = ["App", "Config", "Suggestions", "Images"].includes(check[1]) ? "Codex" : check[1] === "Claude" ? "Apps" : check[1];
65
+ let text = `Starting · ${scope}`;
66
+ if (["Service", "Models", "Sources", "M365"].includes(scope)) text += ` · ${check[2]}`;
67
+ while (displayWidth(text) >= (output.columns || 80)) text = [...text].slice(0, -1).join("");
68
+ clear();output.write(`\r\x1b[2K${text}`);visible = true;
69
+ },
70
+ };
71
+ }
72
+
45
73
  export function predictionStartupCheck(prediction) {
46
74
  if (!prediction?.configured) return startupCheck("info", "Suggestions", "Off");
47
75
  const environment = prediction.environment?.status;
@@ -4,7 +4,7 @@ import { redactDiagnosticText } from "./diagnostic-text.mjs";
4
4
  import { DEFAULT_TERMINAL_ANIMATION_THEME, TERMINAL_ANIMATION_THEMES, isTerminalAnimationTheme, renderTerminalAnimationFrame,
5
5
  getTerminalAnimationCycleLength, getTerminalAnimationFrameDelay } from "./terminal-animation.mjs";
6
6
  import { displayWidth } from "./cli-table.mjs";
7
- import { providerStartupSummary } from "./startup-ui.mjs";
7
+ import { projectTerminalState, terminalUptime } from "./terminal-state.mjs";
8
8
  import { colorTerminalText, colorTerminalMotion } from "./terminal-colors.mjs";
9
9
 
10
10
  const clear = "\r\x1b[2K";
@@ -14,7 +14,7 @@ const flagOff = value => /^(0|false|no|off)$/i.test(String(value || ""));
14
14
  export function createTerminalConsole({ output = process.stdout, errorOutput = process.stderr, env = process.env,
15
15
  snapshot = () => ({}), preferences = () => ({}), baseUrl = "", verbose = false,
16
16
  timers = { setTimeout, clearTimeout }, now = Date.now } = {}) {
17
- let running = false, timer = null, lines = 0, active = 0, frame = 0, lastRead = 0, data = {};
17
+ let running = false, timer = null, lines = 0, frame = 0, lastRead = 0, data = {}, projection = projectTerminalState();
18
18
  let notices = 0, lastNotice = "", lastPrintedNotice = "", previous = [];
19
19
  let content = [], dirty = true, readFailed = false, updatedAt = null, fits = true;
20
20
  let current = { theme: DEFAULT_TERMINAL_ANIMATION_THEME, color_theme: "green", terminal_animation_enabled: true };
@@ -44,7 +44,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
44
44
  function table(width, usage, requests, inferenceActive, sum, compactTitle = false) {
45
45
  const left = Math.floor((width - 3) / 2), right = width - 3 - left;
46
46
  const cell = (label, value, size) => {
47
- const number = value === undefined ? "" : updatedAt === null && readFailed ? "—" : typeof value === "string" ? value : compact(value), inner = size - 2;
47
+ const number = value === undefined ? "" : updatedAt === null && readFailed ? "—" : value === null ? "—" : typeof value === "string" ? value : compact(value), inner = size - 2;
48
48
  const text = clip(label, Math.max(0, inner - displayWidth(number) - (number ? 1 : 0)));
49
49
  return ` ${text}${" ".repeat(Math.max(0, inner - displayWidth(text) - displayWidth(number)))}${number} `;
50
50
  };
@@ -52,18 +52,20 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
52
52
  const rule = (a, b, c) => `${a}${"─".repeat(left)}${b}${"─".repeat(right)}${c}`;
53
53
  const rate = usage.cache_hit_rate;
54
54
  const cacheHit = Number.isFinite(rate) && rate >= 0 && rate <= 1 ? `${usage.cache_hit_rate_partial ? "~" : ""}${(rate * 100).toFixed(1)}%` : "—";
55
- const usageRows = [[left < 23 ? "Records" : "Usage records", usage.records || 0], ["Input", usage.input_tokens], [left < 23 ? "Reused" : "Reused input", usage.cached_input_tokens],
56
- ["Output", usage.output_tokens], ["Partial usage", usage.partial_records || 0], ["Cache hit", cacheHit]];
57
- const requestRows = [["Requests", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
58
- const title = compactTitle ? [`┌─ Usage ${"─".repeat(left - 8)}┬─ Inference ${"─".repeat(right - 12)}┐`]
59
- : [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell("Inference", undefined, right)), rule("├", "┼", "┤")];
55
+ const usageRows = [[left < 23 ? "Records" : "Usage records", usage.records ?? null], ["Input", usage.input_tokens ?? null], [left < 23 ? "Reused" : "Reused input", usage.cached_input_tokens ?? null],
56
+ ["Output", usage.output_tokens ?? null], [left < 23 ? "Partial" : "Partial records", usage.partial_records ?? null], ["Cache hit", cacheHit]];
57
+ const requestRows = [["Total", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
58
+ if (sum("unknown")) { usageRows.push(["", ""]);requestRows.push(["Unknown", sum("unknown")]); }
59
+ const title = compactTitle ? [`┌─ Usage ${"─".repeat(left - 8)}┬─ Requests ${"─".repeat(right - 11)}┐`]
60
+ : [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell(right < 23 ? "Requests" : "Model requests", undefined, right)), rule("├", "┼", "┤")];
60
61
  return [...title,
61
- ...usageRows.map(([label, value], index) => row(cell(label, value ?? (label ? 0 : undefined), left), cell(...requestRows[index], right))), rule("└", "┴", "┘")];
62
+ ...usageRows.map(([label, value], index) => row(cell(label, value === undefined ? (label ? null : undefined) : value, left), cell(...requestRows[index], right))), rule("└", "┴", "┘")];
62
63
  }
63
64
  function render() {
64
65
  if (!running || !supported() || verbose) { frameDelay = 1000;return; }
65
66
  const width = Math.max(1, Math.min(160, Number(output.columns) || 80) - 1);
66
- let motion = active ? "●" : "○";
67
+ const active = readFailed ? null : projection.activity;
68
+ let motion = active === null ? "?" : active ? "●" : "○";
67
69
  frameDelay = 1000;
68
70
  if (active && current.terminal_animation_enabled && !flagOff(env.CCDX_TERMINAL_ANIMATION) && width >= 24) {
69
71
  frame %= getTerminalAnimationCycleLength(current.theme);
@@ -75,30 +77,29 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
75
77
  frameDelay = getTerminalAnimationFrameDelay(current.theme, index) + (frame === 0 ? metadata.loopPauseMs : 0);
76
78
  }
77
79
  if (dirty) {
78
- const usage = data.runtime_usage || {}, routes = data.requests?.by_route || {};
79
- const outcomes = [data.stream_performance?.by_route?.responses, data.stream_performance?.by_route?.responses_compact, (data.providers?.claude || data.providers?.m365?.claude)?.requests?.performance?.by_route?.messages]
80
- .map(route => route?.terminal_outcomes?.totals || {});
81
- const sum = key => outcomes.reduce((total, item) => total + (Number(item[key]) || 0), 0);
82
- const requests = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.total || 0), 0);
83
- const inferenceActive = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.active || 0), 0);
84
- const providers = providerStartupSummary(data);
85
- const heading = readFailed ? updatedAt === null ? "CCDX / No data received" : `CCDX / ${width < 80 ? "Previous data" : "Showing previous data / updated"} / ${new Date(updatedAt).toLocaleTimeString("en-GB")}`
86
- : `CCDX RUNNING / uptime ${Math.floor((data.uptime_ms || 0) / 60000)}m / ${baseUrl}`;
87
- content = [clip(heading, width)];
88
- for (const group of [[`Sources / ${providers.catalogs}`, providers.sourceLines], [`Claude / ${providers.claude}`, providers.claudeLines]]) {
89
- content.push(...(displayWidth(group[0]) <= width ? [group[0]] : (group[1] || [group[0]]).flatMap(line => wrap(line, width))));
90
- }
91
- content.push(...table(width, usage, requests, inferenceActive, sum));
92
- content.push(clip(`${notices} notices${lastNotice ? ` · latest: ${lastNotice}` : " / details in WebUI"}`, width));
80
+ const usage = data.runtime_usage || {}, view = projection;
81
+ const heading = readFailed ? updatedAt === null ? "Status unavailable" : `Previous data / ${new Date(updatedAt).toLocaleTimeString("en-GB")}`
82
+ : `${baseUrl ? `Listening · ${baseUrl}` : "Listening"} · up ${terminalUptime(data.uptime_ms)}`;
83
+ const sourceHeader = view.sources ? `Enabled sources: ${view.sources.length}` : "Enabled sources: unknown";
84
+ const appSize = width < 64 ? 13 : 15, setupSize = Math.max(10, Math.min(20, width - appSize - 7));
85
+ const appRows = view.clients.map(client => `${clip(client.name, appSize - 1).padEnd(appSize)}${clip(client.setup, setupSize - 1).padEnd(setupSize)}${String(readFailed || client.active === null ? "—" : client.active).padStart(6)}`);
86
+ const issue = view.issue?.label;
87
+ const notice = notices ? `${notices} ${notices === 1 ? "notice" : "notices"}${issue ? ` · last model issue: ${issue}` : " · ccdx status --details"}` : issue ? `Last model issue: ${issue}` : "No notices";
88
+ content = [clip(heading, width), sourceHeader,
89
+ ...(view.sources ? wrap(view.sources.map(source => source.name).join(" · "), width) : []),
90
+ `${"App".padEnd(appSize)}${"Setup".padEnd(setupSize)}${"Active".padStart(6)}`, ...appRows,
91
+ ...table(width, usage, view.requests, readFailed ? null : view.active, key => view.outcomes[key]),
92
+ clip("Web: ccdx web · Help: ccdx help · Ctrl+C: stop", width), clip(notice, width)];
93
93
  if (content.length + 1 >= (Number(output.rows) || 24)) {
94
- const summaries = [...(providers.compactSources || ["Sources: not checked"]), ...(providers.compactClaude || ["Claude: not checked"])];
95
- content = [clip(heading, width), ...summaries.flatMap(line => wrap(line, width)), ...table(width, usage, requests, inferenceActive, sum, true), content.at(-1)];
94
+ const grouped = Object.entries(view.clients.reduce((counts, client) => ({ ...counts, [client.setup]: (counts[client.setup] || 0) + 1 }), {})).map(([state, count]) => `${count} ${state.toLowerCase()}`).join(" · ");
95
+ content = [clip(heading, width), sourceHeader, clip(`Apps: ${grouped}`, width),
96
+ ...table(width, usage, view.requests, readFailed ? null : view.active, key => view.outcomes[key], true), clip(notice, width)];
96
97
  }
97
98
  dirty = false;
98
99
  }
99
100
  // Apply color after clipping/layout so escape sequences never consume columns.
100
101
  const body = [...content.map(line => ["klein", "pink"].includes(current.color_theme) && /^[┌│├└]/.test(line)
101
- ? colorTerminalText(line, current.color_theme, { output, env }) : line), `${motion} ${active ? "Working" : "Idle"}`];
102
+ ? colorTerminalText(line, current.color_theme, { output, env }) : line), `${motion} ${active === null ? "Status unknown" : active ? "Active" : "Idle"}`];
102
103
  fits = body.length < (Number(output.rows) || 24);
103
104
  if (!fits) { frameDelay = 1000;return; }
104
105
  // Animation ticks update only the final line; data stays on its 1s cadence.
@@ -120,7 +121,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
120
121
  if (now() - lastRead >= 1000 || !lastRead) {
121
122
  try {
122
123
  const next = snapshot(), nextPreferences = preferences();
123
- data = next;current = { ...current, ...nextPreferences };readFailed = false;updatedAt = now();
124
+ data = next;projection = projectTerminalState(data);current = { ...current, ...nextPreferences };readFailed = false;updatedAt = now();
124
125
  if (!isTerminalAnimationTheme(current.theme)) current.theme = DEFAULT_TERMINAL_ANIMATION_THEME;
125
126
  } catch { readFailed = true; }
126
127
  lastRead = now();
@@ -133,7 +134,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
133
134
  get enabled() { return supported() && fits && !verbose; },
134
135
  start() { if (running) return;running = true;tick(); },
135
136
  pause() { running = false;if (timer) timers.clearTimeout(timer);timer = null;if (lines) output.write("\n");lines = 0;previous = [];dirty = true; },
136
- beginRequest() { active++;dirty = true;let done = false;return () => { if (!done) { done = true;active = Math.max(0, active - 1);dirty = true; } }; },
137
+ beginRequest() { dirty = true;return () => { dirty = true; }; },
137
138
  log(method, args) {
138
139
  const message = redactDiagnosticText(format(...args));
139
140
  if (verbose) { (method === "error" || method === "warn" ? errorOutput : output).write(`${message}\n`);return; }
@@ -0,0 +1,69 @@
1
+ import { terminalCell } from "./terminal-text.mjs";
2
+
3
+ const integer = value => Number.isSafeInteger(value) && value >= 0;
4
+ const appIds = { codex_app: "codex", codex_cli: "codex", codex: "codex", claude_app: "claude_app", claude_code: "claude_code" };
5
+ export const TERMINAL_CLIENT_NAMES = Object.freeze({ codex: "Codex", claude_app: "Claude App", claude_code: "Claude Code" });
6
+ const labels = { configured: "Configured", paused: "Paused", disabled: "Disabled", not_configured: "Not configured", not_installed: "Not installed",
7
+ preserved: "Preserved", partially_preserved: "Partly preserved", manual_sync: "Manual sync", default_unavailable: "Default unavailable", configuration_unavailable: "Unreadable", unavailable: "Unavailable" };
8
+ export function terminalUptime(milliseconds) {
9
+ if (!Number.isFinite(milliseconds) || milliseconds < 0) return "unknown";
10
+ const minutes = Math.floor(milliseconds / 60000), hours = Math.floor(minutes / 60), days = Math.floor(hours / 24);
11
+ return days ? `${days}d ${hours % 24}h` : hours ? `${hours}h ${minutes % 60}m` : `${minutes}m`;
12
+ }
13
+ export function clientSetup(client = {}) {
14
+ if (client.enabled === false) return "Disabled";
15
+ if (client.enabled && (Array.isArray(client.deployments) ? !client.deployments.length : client.source === null)) return "Paused";
16
+ return labels[client.setup] || "Not checked";
17
+ }
18
+ export function projectTerminalState(data = {}) {
19
+ const routes = data.requests?.by_route, names = ["responses", "responses_compact", "messages"];
20
+ const partialRoutes = routes && names.some(name => routes[name]);
21
+ const active = partialRoutes ? names.reduce((sum, name) => sum + (routes[name]?.active || 0), 0) : null;
22
+ const requests = partialRoutes ? names.reduce((sum, name) => sum + (routes[name]?.total || 0), 0) : null;
23
+ const claude = (data.providers?.claude || data.providers?.m365?.claude)?.requests?.performance;
24
+ const performance = [data.stream_performance, claude].filter(Boolean);
25
+ const outcomes = Object.fromEntries(["completed", "incomplete", "failed", "cancelled", "unknown"].map(key => [key,
26
+ performance.flatMap(part => Object.entries(part.by_route || {}).filter(([route]) => part === claude ? route === "messages" : ["responses", "responses_compact"].includes(route)).map(([, row]) => row.terminal_outcomes?.totals || {}))
27
+ .reduce((sum, row) => sum + (integer(row[key]) ? row[key] : 0), 0)]));
28
+ const activity = Object.hasOwn(data.model_activity || {}, "active") ? integer(data.model_activity.active) ? data.model_activity.active : null : active;
29
+ const running = [...new Map(performance.flatMap(part => (part.active_requests || []).filter(row => part === claude ? !row.route || row.route === "messages" : !row.route || ["responses", "responses_compact"].includes(row.route))).map((row, i) => [row.request_id || `unknown-${i}`, row])).values()];
30
+ const byApp = new Map();let unidentified = 0;
31
+ for (const row of running) {
32
+ const app = appIds[row.application];if (app) byApp.set(app, (byApp.get(app) || 0) + 1);else unidentified++;
33
+ }
34
+ const connection = data.providers?.connections, clientRows = connection?.clients;
35
+ const clients = (clientRows || [
36
+ { id: "codex", setup: null },
37
+ ...[["app", "claude_app"], ["code", "claude_code"]].map(([key, id]) => ({ id, setup: data.providers?.m365?.claude?.clients?.[key] })),
38
+ ]).map(client => ({ id: client.id, name: TERMINAL_CLIENT_NAMES[client.id] || terminalCell(client.name || client.id),
39
+ setup: clientSetup(client.id === "codex" && !connection?.managed && !client.setup && data.client_integrations?.codex?.setup ? { ...client, setup: data.client_integrations.codex.setup } : client), active: running.length || active === 0 ? byApp.get(client.id) || 0 : null, observed_at: client.observed_at || null }));
40
+ if (integer(active) && active > running.length) unidentified += active - running.length;
41
+ if (unidentified) clients.push({ id: "other", name: "Other clients", setup: "Not identified", active: unidentified });
42
+ const sources = connection?.providers?.filter(item => item.enabled && !(item.id === "m365" && data.providers?.m365?.enabled === false)).map(item => ({ id: item.id, name: terminalCell(item.name || item.id) }))
43
+ || (data.providers ? [{ id: "github", name: "GitHub Copilot" }, ...(data.providers.m365?.enabled ? [{ id: "m365", name: "Microsoft 365" }] : [])] : null);
44
+ const lastFailure = data.http_errors?.actionable_recent?.at(-1);
45
+ let issue = null;
46
+ if (lastFailure) {
47
+ const app = TERMINAL_CLIENT_NAMES[appIds[lastFailure.application]] || "Unidentified client";
48
+ const source = connection?.providers?.find(item => item.id === lastFailure.provider)?.name || ({ github: "GitHub Copilot", m365: "Microsoft 365" }[lastFailure.provider]) || lastFailure.provider || "Unknown source";
49
+ const causes = { m365_network_error: "Network request failed", m365_catalog_http_403: "Model catalog access denied", ccdx_api_model_unavailable: "Selected model is unavailable", ccdx_client_source_disabled: "Model access is paused" };
50
+ const message = causes[lastFailure.code] || (lastFailure.route === "messages_count_tokens" ? "Token-count check failed" : lastFailure.http_status === 401 ? "Sign-in was rejected" : lastFailure.http_status === 403 ? "Access was denied" : lastFailure.http_status === 429 ? "Request limit reached" : "Request failed");
51
+ issue = { label: `${terminalCell(app)} / ${terminalCell(source)}: ${message}`, request_id: lastFailure.request_id, application: lastFailure.application };
52
+ }
53
+ return { sources, clients, requests, active, activity, outcomes, issue };
54
+ }
55
+
56
+ export function retainedRequests(data = {}) {
57
+ const claude = (data.providers?.claude || data.providers?.m365?.claude)?.requests?.performance;
58
+ const parts = [data.stream_performance, claude].filter(Boolean), rows = new Map();
59
+ for (const part of parts) {
60
+ for (const record of part.recent_requests || []) if (record.request_id) rows.set(record.request_id, { ...record, state: record.outcome || record.terminal_outcome || "unknown", active: false });
61
+ for (const record of part.active_requests || []) if (record.request_id) rows.set(record.request_id, { ...record, state: record.phase || "active", active: true });
62
+ }
63
+ for (const record of data.http_errors?.recent || data.http_errors?.actionable_recent || []) if (record.request_id) {
64
+ const existing = rows.get(record.request_id);
65
+ rows.set(record.request_id, { ...existing, ...record, error: true, active: existing?.active === true, state: ["cancelled", "incomplete"].includes(existing?.state) ? existing.state : "failed" });
66
+ }
67
+ const time = row => { const value = Date.parse(row.at || row.time || "");return Number.isFinite(value) ? value : 0; };
68
+ return [...rows.values()].sort((a, b) => Number(a.active) - Number(b.active) || time(a) - time(b));
69
+ }