codex-copilot-dx 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.
@@ -16,8 +15,8 @@ const ATOM = [
16
15
  export function startupBanner({ commandName = "ccdx", version, stream = process.stdout, env = process.env } = {}) {
17
16
  const title = `${terminalCell(commandName)} v${terminalCell(version)} by Dale Xiao`;
18
17
  const color = stream.isTTY === true && !Object.hasOwn(env, "NO_COLOR") && env.TERM !== "dumb";
19
- if (!color || Number(stream.columns || 80) < 72) return `${title}\nUse Codex App with GitHub Copilot`;
20
- const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Codex App + GitHub Copilot"]]);
18
+ if (!color || Number(stream.columns || 80) < 72) return `${title}\nLocal model services for Codex and Claude`;
19
+ const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Codex + Claude / local services"]]);
21
20
  return ATOM.map((line, i) => `\x1b[38;2;166;245;168m${line}\x1b[0m${labels.has(i) ? ` ${labels.get(i)}` : ""}`).join("\n");
22
21
  }
23
22
 
@@ -42,11 +41,39 @@ export function startupLogger(name, output = console.log) {
42
41
 
43
42
  export function predictionStartupCheck(prediction) {
44
43
  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
- return (prediction.recovery ? `${summary}\n${startupCheck("info", "Recovery", `${prediction.recovery.attempts}/3 attempts used; persistent route ${prediction.persistence || "unknown"}`)}` : summary) + details;
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; App route ${prediction.launch_route === "verified" ? "verified" : prediction.launch_route === "persisted" ? "saved, not verified" : "not verified"}; suggestion unchecked`;
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", "Prediction", 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 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" };
69
+ const client = id => states[ms?.claude?.clients?.[id]] || "not checked";
70
+ 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})`;
72
+ const claude = `Code: ${client("code")} / App: ${client("app")} / ${gateway}`;
73
+ return { catalogs, claude, warning: Object.values(ms?.claude?.clients || {}).includes("configuration_unavailable") };
74
+ }
75
+
76
+ export function providerStartupChecks(data) {
77
+ const summary = providerStartupSummary(data);
78
+ return `${startupCheck("info", "Providers", summary.catalogs)}\n${startupCheck(summary.warning ? "warn" : "info", "Claude", summary.claude)}`;
52
79
  }
@@ -0,0 +1,114 @@
1
+ import { format, stripVTControlCharacters } from "node:util";
2
+ import { terminalCell } from "./terminal-text.mjs";
3
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
4
+ import { DEFAULT_TERMINAL_ANIMATION_THEME, TERMINAL_ANIMATION_THEMES, isTerminalAnimationTheme, renderTerminalAnimationFrame,
5
+ getTerminalAnimationCycleLength, getTerminalAnimationFrameDelay } from "./terminal-animation.mjs";
6
+ import { displayWidth } from "./cli-table.mjs";
7
+ import { providerStartupSummary } from "./startup-ui.mjs";
8
+
9
+ const clear = "\r\x1b[2K";
10
+ const flagOff = value => /^(0|false|no|off)$/i.test(String(value || ""));
11
+
12
+ // A bounded status region, independent of file logging and inference delivery.
13
+ export function createTerminalConsole({ output = process.stdout, errorOutput = process.stderr, env = process.env,
14
+ snapshot = () => ({}), preferences = () => ({}), baseUrl = "", verbose = false,
15
+ timers = { setTimeout, clearTimeout }, now = Date.now } = {}) {
16
+ let running = false, timer = null, lines = 0, active = 0, frame = 0, lastRead = 0, data = {};
17
+ let notices = 0, lastNotice = "", lastPrintedNotice = "", previous = [];
18
+ let content = [], dirty = true;
19
+ let current = { theme: DEFAULT_TERMINAL_ANIMATION_THEME, terminal_animation_enabled: true };
20
+ let frameDelay = 1000;
21
+ const tty = output.isTTY === true && errorOutput.isTTY === true && (!env.CI || flagOff(env.CI)) && env.TERM !== "dumb";
22
+ const supported = () => tty && (Number(output.columns) || 80) >= 40 && (Number(output.rows) || 24) >= 16;
23
+ const resized = () => { if (lines) output.write("\n");lines = 0;previous = [];frame = 0;dirty = true; };
24
+ output.on?.("resize", resized);
25
+ const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
26
+ const clip = (value, width) => {
27
+ let text = "";
28
+ for (const { segment } of segmenter.segment(terminalCell(value, { fallback: "" }))) {
29
+ if (displayWidth(text + segment) > width) break;text += segment;
30
+ }
31
+ return text;
32
+ };
33
+ const numbers = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
34
+ const compact = value => numbers.format(Number(value) || 0);
35
+ function table(width, usage, requests, inferenceActive, sum) {
36
+ const left = Math.floor((width - 3) / 2), right = width - 3 - left;
37
+ const cell = (label, value, size) => {
38
+ const number = value === undefined ? "" : compact(value), inner = size - 2;
39
+ const text = clip(label, Math.max(0, inner - displayWidth(number) - (number ? 1 : 0)));
40
+ return ` ${text}${" ".repeat(Math.max(0, inner - displayWidth(text) - displayWidth(number)))}${number} `;
41
+ };
42
+ const row = (a, b) => `│${a}│${b}│`;
43
+ 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("├", "┼", "┤"),
48
+ ...usageRows.map(([label, value], index) => row(cell(label, value ?? (label ? 0 : undefined), left), cell(...requestRows[index], right))), rule("└", "┴", "┘")];
49
+ }
50
+ function render() {
51
+ if (!running || !supported() || verbose) { frameDelay = 1000;return; }
52
+ const width = Math.max(1, Math.min(160, Number(output.columns) || 80) - 1);
53
+ let motion = active ? "●" : "○";
54
+ frameDelay = 1000;
55
+ if (active && current.terminal_animation_enabled && !flagOff(env.CCDX_TERMINAL_ANIMATION) && width >= 24) {
56
+ frame %= getTerminalAnimationCycleLength(current.theme);
57
+ const metadata = TERMINAL_ANIMATION_THEMES.find(theme => theme.id === current.theme), index = metadata.startFrame + frame;
58
+ motion = renderTerminalAnimationFrame(current.theme, index);
59
+ if (Object.hasOwn(env, "NO_COLOR")) motion = stripVTControlCharacters(motion);
60
+ frame = (frame + 1) % getTerminalAnimationCycleLength(current.theme);
61
+ frameDelay = getTerminalAnimationFrameDelay(current.theme, index) + (frame === 0 ? metadata.loopPauseMs : 0);
62
+ }
63
+ if (dirty) {
64
+ const usage = data.runtime_usage || {}, routes = data.requests?.by_route || {};
65
+ const outcomes = [data.stream_performance?.by_route?.responses, data.stream_performance?.by_route?.responses_compact, data.providers?.m365?.claude?.requests?.performance?.by_route?.messages]
66
+ .map(route => route?.terminal_outcomes?.totals || {});
67
+ const sum = key => outcomes.reduce((total, item) => total + (Number(item[key]) || 0), 0);
68
+ const requests = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.total || 0), 0);
69
+ const inferenceActive = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.active || 0), 0);
70
+ 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));
73
+ content.push(...table(width, usage, requests, inferenceActive, sum));
74
+ content.push(clip(`${notices} notices${lastNotice ? ` / latest: ${lastNotice}` : " / details in WebUI"}`, width));
75
+ dirty = false;
76
+ }
77
+ const body = [...content, `${motion} ${active ? "Working" : "Idle"}`];
78
+ // Animation ticks update only the final line; data stays on its 1s cadence.
79
+ let update = "";
80
+ if (!lines) update = `${body.map(line => clear + line).join("\n")}\r`;
81
+ else for (let index = 0; index < body.length; index++) {
82
+ if (body[index] === previous[index]) continue;
83
+ const offset = body.length - 1 - index;
84
+ update += `${offset ? `\x1b[${offset}A` : ""}${clear}${body[index]}\r${offset ? `\x1b[${offset}B` : ""}`;
85
+ }
86
+ if (update) output.write(update);
87
+ previous = body;lines = body.length;
88
+ }
89
+ function tick() {
90
+ if (!running) return;
91
+ if (now() - lastRead >= 1000 || !lastRead) {
92
+ try { data = snapshot();current = { ...current, ...preferences() };if (!isTerminalAnimationTheme(current.theme)) current.theme = DEFAULT_TERMINAL_ANIMATION_THEME; } catch {}
93
+ lastRead = now();
94
+ dirty = true;
95
+ }
96
+ render();
97
+ timer = timers.setTimeout(tick, frameDelay);timer?.unref?.();
98
+ }
99
+ return {
100
+ get enabled() { return supported() && !verbose; },
101
+ start() { if (running) return;running = true;tick(); },
102
+ beginRequest() { active++;dirty = true;let done = false;return () => { if (!done) { done = true;active = Math.max(0, active - 1);dirty = true; } }; },
103
+ log(method, args) {
104
+ const message = redactDiagnosticText(format(...args));
105
+ if (verbose) { (method === "error" || method === "warn" ? errorOutput : output).write(`${message}\n`);return; }
106
+ if (method !== "error" && method !== "warn" && !/^\[(WARN|ERR)\]/.test(message.trim())) return;
107
+ notices++;lastNotice = message.replace(/\s+/g, " ").slice(0, 240);dirty = true;
108
+ if (!supported() && lastNotice !== lastPrintedNotice) { errorOutput.write(`${lastNotice}\n`);lastPrintedNotice = lastNotice; }
109
+ },
110
+ snapshot() { return { notices, last_notice: lastNotice || null, mode: verbose ? "verbose" : supported() ? "status" : "plain" }; },
111
+ apply(value) { if (value.theme && value.theme !== current.theme) frame = 0;current = { ...current, ...value };lastRead = 0; },
112
+ cleanup() { running = false;if (timer) timers.clearTimeout(timer);timer = null;if (lines) output.write("\n");lines = 0;output.off?.("resize", resized); },
113
+ };
114
+ }
@@ -24,6 +24,9 @@ let pendingRecords = 0;
24
24
  let pendingBytes = 0;
25
25
  let droppedRecords = 0;
26
26
  let writeFailures = 0;
27
+ const runtimeUsage = { since: new Date().toISOString(), records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 };
28
+
29
+ export function runtimeUsageSnapshot() { return { ...runtimeUsage }; }
27
30
 
28
31
  export function usageLoggingStats() {
29
32
  return { pending_records: pendingRecords, pending_bytes: pendingBytes, dropped_records: droppedRecords,
@@ -180,7 +183,14 @@ function scheduleUsageWriteDrain() {
180
183
  }
181
184
 
182
185
  export function recordUsage(record) {
183
- if (!record || process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
186
+ if (!record) return Promise.resolve();
187
+ const usage = record.usage || {};
188
+ runtimeUsage.records++;
189
+ for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cacheReadTokens(usage)], ["output_tokens", usage.output_tokens]]) {
190
+ if (Number.isFinite(value) && value >= 0) runtimeUsage[target] += value;
191
+ }
192
+ if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cacheReadTokens(usage) === undefined) runtimeUsage.partial_records++;
193
+ if (process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
184
194
  const filePath = usageLogPath();
185
195
  const line = `${JSON.stringify(record)}\n`;
186
196
  const bytes = Buffer.byteLength(line);
package/src/usage.mjs CHANGED
@@ -4,6 +4,7 @@ import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageLogPath, u
4
4
  export {
5
5
  usageSummaryVersion,
6
6
  usageLoggingStats,
7
+ runtimeUsageSnapshot,
7
8
  usageLogPath,
8
9
  usageLogMaxBytes,
9
10
  buildResponsesUsageRecord,
@@ -22,6 +22,7 @@ const AUTO_REVIEW_REASONING_KEY = "auto_review_reasoning";
22
22
  const TERMINAL_ANIMATION_KEY = "terminal_animation";
23
23
  const RESPONSE_HISTORY_MAX_MIB_KEY = "response_history_max_mib";
24
24
  const DECODED_BODY_LIMIT_MIB_KEY = "decoded_body_limit_mib";
25
+ const SERVICE_FLAGS = ["terminal_animation_enabled", "open_webui", "image_enabled", "prediction_enabled"];
25
26
  export const DECODED_BODY_LIMIT_MIN_MIB = RUNTIME_DEFAULTS.maxDecodedBodyBytes / MIB;
26
27
  export const DECODED_BODY_LIMIT_MAX_MIB = 512;
27
28
  export { RESPONSE_HISTORY_MAX_MIB, RESPONSE_HISTORY_MIN_MIB };
@@ -43,6 +44,12 @@ export function readUserSettings({ env = process.env, home = os.homedir(), stric
43
44
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
44
45
  throw invalidSettings(filePath, "expected a JSON object");
45
46
  }
47
+ for (const key of SERVICE_FLAGS) {
48
+ if (Object.hasOwn(parsed, key) && typeof parsed[key] !== "boolean") {
49
+ if (strict) throw invalidSettings(filePath, `${key} must be a boolean`);
50
+ delete parsed[key];
51
+ }
52
+ }
46
53
  if (Object.hasOwn(parsed, AUTO_REVIEW_MODEL_KEY)) {
47
54
  const value = parsed[AUTO_REVIEW_MODEL_KEY];
48
55
  if (typeof value !== "string" || !value.trim()) {
@@ -107,6 +114,20 @@ export function savedAutoReviewModel(options = {}) {
107
114
  return String(settings[AUTO_REVIEW_MODEL_KEY] || "").trim();
108
115
  }
109
116
 
117
+ export function servicePreferences(options = {}) {
118
+ const settings = readUserSettings({ ...options, strict: true });
119
+ return Object.fromEntries(SERVICE_FLAGS.map(key => [key, settings[key] !== false]));
120
+ }
121
+
122
+ export function writeServicePreference(key, value, options = {}) {
123
+ if (!SERVICE_FLAGS.includes(key) || typeof value !== "boolean") throw new Error("Unknown service setting or invalid boolean");
124
+ return withFileLockSync(`${userSettingsPath(options)}.lock`, () => {
125
+ const settings = readUserSettings({ ...options, strict: true });
126
+ const changed = atomicWriteFileIfChangedSync(userSettingsPath(options), `${JSON.stringify({ ...settings, [key]: value }, null, 2)}\n`, { mode: 0o600 });
127
+ return { changed, ...servicePreferences(options) };
128
+ });
129
+ }
130
+
110
131
  export function autoReviewModelPreference({ env = process.env, home = os.homedir() } = {}) {
111
132
  const { model, source } = autoReviewPreference({ env, home });
112
133
  return { model, source };