codex-copilot-dx 1.2.0 → 1.2.2

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.
@@ -0,0 +1,192 @@
1
+ // Also shipped as the standalone bootstrap helper. Keep imports built-in only.
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { createRequire } from "node:module";
6
+ import { Readable } from "node:stream";
7
+ import { createHash } from "node:crypto";
8
+ import { gunzipSync } from "node:zlib";
9
+ import { execFileSync } from "node:child_process";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
+
12
+ export const RELEASE_BASE = "https://github.com/DaleXiao/codex-copilot-dx/releases/download";
13
+ export function stableVersion(tag) {
14
+ const match = typeof tag === "string" && tag.length <= 64 && /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(tag);
15
+ return match && match.slice(1).every(part => Number.isSafeInteger(Number(part))) ? match.slice(1).join(".") : null;
16
+ }
17
+ // Use the downloader already shipped with the selected npm, rather than adding
18
+ // a second runtime dependency or bypassing its proxy/CA/offline settings.
19
+ export function createNpmReleaseFetch(npmCli, { env = process.env, exec = execFileSync } = {}) {
20
+ try {
21
+ const npmFetch = createRequire(npmCli)("make-fetch-happen");
22
+ const keys = ["https-proxy", "proxy", "noproxy", "cafile", "strict-ssl", "offline"];
23
+ const output = exec(process.execPath, [npmCli, "config", "get", "--global", ...keys], {
24
+ env, encoding: "utf8", timeout: 5000, maxBuffer: 128 * 1024, stdio: ["ignore", "pipe", "pipe"] });
25
+ const values = Object.fromEntries(output.trim().split(/\r?\n/).map(line => /^(https-proxy|proxy|noproxy|cafile|strict-ssl|offline)=(.*)$/.exec(line)).filter(Boolean).map(match => [match[1], match[2]]));
26
+ if (values.offline === "true") throw new Error("offline");
27
+ const present = value => value && !["null", "undefined"].includes(value) ? value : undefined;
28
+ const caFile = present(values.cafile);let ca;
29
+ if (caFile) {
30
+ if (!fs.statSync(caFile).isFile() || fs.statSync(caFile).size > 1024 * 1024) throw new Error("CA file");
31
+ ca = fs.readFileSync(caFile, "utf8");
32
+ }
33
+ return async (url, options = {}) => {
34
+ try {
35
+ const response = await npmFetch(url, { ...options, retry: 0, cache: "no-store", ca,
36
+ proxy: present(values["https-proxy"]) || present(values.proxy) || env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY,
37
+ noProxy: present(values.noproxy) || env.no_proxy || env.NO_PROXY,
38
+ strictSSL: values["strict-ssl"] !== "false" });
39
+ const body = [204, 205, 304].includes(response.status) ? null : Readable.toWeb(Readable.from(response.body));
40
+ const result = new Response(body, { status: response.status, headers: Object.fromEntries(response.headers) });
41
+ Object.defineProperty(result, "url", { value: response.url });return result;
42
+ } catch { throw new Error("Release download failed. Check the configured npm proxy, CA file and approved GitHub access; no fallback was attempted."); }
43
+ };
44
+ } catch (error) {
45
+ if (error.message === "offline") throw new Error("npm offline mode is enabled. Use an approved local Release package/cache; no download was started.");
46
+ throw new Error("Could not use this npm's download component or network settings. Keep its proxy/CA policy; use an approved local Release package or a complete supported npm distribution.");
47
+ }
48
+ }
49
+
50
+ export async function releaseBytes(url, { fetchImpl = fetch, maxBytes, timeoutMs = 60000 } = {}) {
51
+ const response = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.timeout(timeoutMs), headers: { "User-Agent": "codex-copilot-dx", Accept: "application/octet-stream" } });
52
+ const final = response.url && new URL(response.url);
53
+ if (!response.ok || final && (final.protocol !== "https:" || !["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"].includes(final.hostname))) {
54
+ await response.body?.cancel();throw new Error(`Release download refused (HTTP ${response.status}). Check company proxy, certificates and approved download access. No fallback was attempted.`);
55
+ }
56
+ const chunks = [];let size = 0;
57
+ try {
58
+ for await (const chunk of response.body || []) {
59
+ size += chunk.length;if (size > maxBytes) throw new Error("Release download exceeds its size limit");chunks.push(chunk);
60
+ }
61
+ return Buffer.concat(chunks, size);
62
+ } catch (error) { throw new Error("Release download did not finish; the existing installation was preserved", { cause: error }); }
63
+ }
64
+ export function releaseChecksum(manifest, name) {
65
+ const lines = manifest.toString("utf8").split(/\r?\n/).filter(line => line.endsWith(` ${name}`));
66
+ if (lines.length !== 1 || !/^[a-f0-9]{64} [\w.-]+$/.test(lines[0])) throw new Error("Release checksum is missing or invalid");
67
+ return lines[0].slice(0, 64);
68
+ }
69
+ export function packageMetadata(bytes) {
70
+ const tar = gunzipSync(bytes, { maxOutputLength: 64 * 1024 * 1024 });
71
+ let metadata;
72
+ for (let offset = 0; offset + 512 <= tar.length;) {
73
+ const header = tar.subarray(offset, offset + 512), name = header.subarray(0, 100).toString().replace(/\0.*$/s, "");
74
+ if (!name) break;
75
+ const sizeText = header.subarray(124, 136).toString().replace(/\0.*$/s, "").trim();
76
+ if (!/^[0-7]+$/.test(sizeText)) throw new Error("Invalid release package header");
77
+ const size = Number.parseInt(sizeText, 8);
78
+ if (!Number.isSafeInteger(size) || offset + 512 + size > tar.length) throw new Error("Invalid release package size");
79
+ if (name === "package/package.json") {
80
+ if (metadata || size > 65536 || ![0, 48].includes(header[156])) throw new Error("Invalid release package metadata");
81
+ metadata = JSON.parse(tar.subarray(offset + 512, offset + 512 + size));
82
+ }
83
+ offset += 512 + Math.ceil(size / 512) * 512;
84
+ }
85
+ if (metadata?.name !== "codex-copilot-dx" || !stableVersion(metadata.version)) throw new Error("Release package identity is invalid");
86
+ return metadata;
87
+ }
88
+ export async function downloadRelease(tag, { fetchImpl = fetch, directory } = {}) {
89
+ const version = stableVersion(tag);if (!version) throw new Error("A valid stable GitHub release tag is required");
90
+ const name = `codex-copilot-dx-${version}.tgz`, base = `${RELEASE_BASE}/v${version}`;
91
+ const manifest = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536 });
92
+ const expected = releaseChecksum(manifest, name);
93
+ const bytes = await releaseBytes(`${base}/${name}`, { fetchImpl, maxBytes: 16 * 1024 * 1024 });
94
+ if (createHash("sha256").update(bytes).digest("hex") !== expected) throw new Error("Release checksum mismatch; no installation was started");
95
+ if (packageMetadata(bytes).version !== version) throw new Error("Release package version does not match its tag");
96
+ const file = path.join(directory, name);fs.writeFileSync(file, bytes, { flag: "wx", mode: 0o600 });return { file, name, version };
97
+ }
98
+
99
+ // Preserve only this package and its command entries. Never snapshot credentials
100
+ // or change npm settings. A busy/readonly Windows installation fails in place.
101
+ export function protectInstallation({ target, prefix, platform = process.platform } = {}) {
102
+ if (!target || !prefix) return { commit() {}, rollback() {} };
103
+ const parent = path.dirname(target);fs.mkdirSync(parent, { recursive: true });
104
+ const lock = path.join(parent, ".ccdx-install.lock");let fd;
105
+ try { fd = fs.openSync(lock, "wx", 0o600); } catch { throw new Error("Another install may be running. Check the CCDX install lock before retrying."); }
106
+ let backup;
107
+ try { backup = fs.mkdtempSync(path.join(parent, ".ccdx-backup-")); }
108
+ catch (error) { fs.closeSync(fd);fs.unlinkSync(lock);throw error; }
109
+ const entries = [target, ...["ccdx", "codex-copilot-dx"].flatMap(name => platform === "win32"
110
+ ? [name, `${name}.cmd`, `${name}.ps1`].map(file => path.join(prefix, file)) : [path.join(prefix, "bin", name)])];
111
+ const saved = [];
112
+ const clean = () => { fs.rmSync(backup, { recursive: true, force: true });fs.closeSync(fd);fs.unlinkSync(lock); };
113
+ try {
114
+ entries.forEach((file, index) => {
115
+ let stat;try { stat = fs.lstatSync(file); } catch (error) { if (error.code !== "ENOENT") throw error; }
116
+ if (file === target && stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error("The npm target is linked or not a regular installation; use its owning installer");
117
+ const copy = path.join(backup, String(index));
118
+ if (stat) fs.cpSync(file, copy, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true });
119
+ saved.push({ file, copy, existed: Boolean(stat) });
120
+ });
121
+ } catch (error) { clean();throw error; }
122
+ let finalized = false;
123
+ return {
124
+ commit() {
125
+ finalized = true;
126
+ try { clean(); }
127
+ catch { console.error(`CCDX was installed, but backup cleanup needs attention: ${backup}; check ${lock} before retrying.`); }
128
+ },
129
+ rollback() {
130
+ if (finalized) return;
131
+ try {
132
+ for (const { file, copy, existed } of saved) {
133
+ fs.rmSync(file, { recursive: true, force: true });
134
+ if (existed) fs.cpSync(copy, file, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true });
135
+ }
136
+ clean();
137
+ } catch (error) {
138
+ fs.closeSync(fd);
139
+ throw new Error(`Restore could not finish. Previous package and commands remain at ${backup}; do not delete the install lock until restored.`, { cause: error });
140
+ }
141
+ },
142
+ };
143
+ }
144
+
145
+ export function verifyPackageRuntime(target, version, { brokerRequired = false } = {}) {
146
+ const code = `const {createRequire}=require('node:module');const r=createRequire(${JSON.stringify(path.join(target, "package.json"))});const pkg=r('./package.json');if(pkg.name!=='codex-copilot-dx'||pkg.version!==${JSON.stringify(version)})throw Error('Version mismatch');r('sharp')({create:{width:1,height:1,channels:3,background:'white'}}).png().toBuffer().then(()=>{${brokerRequired ? "if(!r('@azure/msal-node-runtime').msalNodeRuntime)throw Error('Native broker unavailable');" : ""}}).catch(e=>{console.error(e.message);process.exitCode=1});`;
147
+ execFileSync(process.execPath, ["-e", code], { timeout: 30000, stdio: ["ignore", "pipe", "pipe"] });
148
+ const output = execFileSync(process.execPath, [path.join(target, "bin", "cli.mjs"), "version"], { encoding: "utf8", timeout: 15000, stdio: ["ignore", "pipe", "pipe"] });
149
+ if (!output.includes(`ccdx v${version} `)) throw new Error("Installed command version could not be verified");
150
+ }
151
+
152
+ export async function writePrivateLaunchers({ prefix, target }) {
153
+ const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
154
+ const windows = process.platform === "win32"
155
+ ? await import(pathToFileURL(path.join(target, "src", "windows-command.mjs")).href) : null;
156
+ for (const name of ["ccdx", "codex-copilot-dx"]) {
157
+ const cli = path.join(target, "bin", name === "ccdx" ? "cli.mjs" : "codex-copilot-dx.mjs");
158
+ if (windows) {
159
+ fs.writeFileSync(path.join(prefix, `${name}.cmd`), windows.privateWindowsCommand({ node: process.execPath, cli, prefix }));
160
+ } else {
161
+ const file = path.join(prefix, "bin", name);fs.rmSync(file, { force: true });
162
+ fs.writeFileSync(file, `#!/bin/sh\nPATH=${quote(path.dirname(process.execPath))}:"$PATH"\nexport PATH\nCCDX_PRIVATE_INSTALL_PREFIX=${quote(prefix)}\nexport CCDX_PRIVATE_INSTALL_PREFIX\nif [ -z "\${npm_config_prefix:-}\${NPM_CONFIG_PREFIX:-}" ]; then npm_config_prefix=${quote(prefix)}; export npm_config_prefix; fi\nexec ${quote(process.execPath)} ${quote(cli)} "$@"\n`, { mode: 0o755 });
163
+ }
164
+ }
165
+ if (windows && windows.inspectWindowsCommand({ packageRoot: target, repair: true }).status !== "ready") throw new Error("Private Windows commands could not be verified");
166
+ }
167
+
168
+ async function bootstrap() {
169
+ const [tag, prefix, npmCli, ...flags] = process.argv.slice(2);
170
+ const permission = flags.includes("--allow-remote"), privateRuntime = flags.includes("--private-runtime");
171
+ if (!stableVersion(tag) || !prefix || !path.isAbsolute(prefix) || !npmCli || !path.isAbsolute(npmCli) || flags.some(flag => !["--allow-remote", "--private-runtime"].includes(flag))) throw new Error("Use: node ccdx-install.mjs vVERSION /absolute/prefix /absolute/npm-cli.js [--allow-remote]");
172
+ const target = path.join(prefix, ...(process.platform === "win32" ? [] : ["lib"]), "node_modules", "codex-copilot-dx");
173
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "ccdx-install-"));let transaction;
174
+ try {
175
+ const release = await downloadRelease(tag, { directory, fetchImpl: createNpmReleaseFetch(npmCli) });
176
+ transaction = protectInstallation({ target, prefix });
177
+ const npmVersion = execFileSync(process.execPath, [npmCli, "--version"], { encoding: "utf8", timeout: 10000 }).trim();
178
+ const args = [npmCli, "install", "--global", "--prefix", prefix, "--ignore-scripts", "--no-audit", "--no-fund"];
179
+ if (permission && Number(npmVersion.split(".")[0]) >= 12) args.push("--allow-remote=all");
180
+ args.push(release.file);
181
+ execFileSync(process.execPath, args, { stdio: "inherit", timeout: 300000 });
182
+ verifyPackageRuntime(target, release.version, { brokerRequired: ["darwin", "win32"].includes(process.platform) });
183
+ if (privateRuntime || process.platform === "win32") await writePrivateLaunchers({ prefix, target });
184
+ transaction.commit();transaction = null;
185
+ console.log(`Installed CCDX ${release.version}. Existing services keep running until restarted.`);
186
+ } catch (error) {
187
+ transaction?.rollback();throw new Error("Installation failed. Previous CCDX package and commands were restored. Check approved registry, proxy, certificates and npm policy; dependencies still need registry access.", { cause: error });
188
+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }
189
+ }
190
+ if (process.argv[1] && path.basename(process.argv[1]) === "ccdx-install.mjs" && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
191
+ try { await bootstrap(); } catch (error) { console.error(error.message);if (error.cause) console.error(error.cause.message);process.exitCode = 1; }
192
+ }
@@ -1,5 +1,5 @@
1
1
  import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
2
- writeTerminalAnimationTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib } from "./user-settings.mjs";
2
+ writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib } from "./user-settings.mjs";
3
3
  import { readImageProviderConfig } from "./image-provider-config.mjs";
4
4
  import { readPredictionSettings } from "./native-prediction-profile.mjs";
5
5
  import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
@@ -10,11 +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
- const { saved, theme, historyLimit } = serviceSettingsSnapshot(options), prediction = clientIntegration?.snapshot().prediction;
13
+ const { saved, theme, color_theme, historyLimit } = serviceSettingsSnapshot(options), prediction = clientIntegration?.snapshot().prediction;
14
14
  let imageConfigured = false, predictionConfigured = false;
15
15
  try { imageConfigured = Boolean(readImages()); } catch {}
16
16
  try { predictionConfigured = readPrediction().enabled === true; } catch {}
17
- return { source: "service_settings", saved, theme,
17
+ return { source: "service_settings", saved, theme, color_theme,
18
18
  effective: {
19
19
  terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
20
20
  state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
@@ -27,14 +27,16 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
27
27
  }
28
28
  async function apply(input) {
29
29
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
30
- const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"],
30
+ const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"], color_theme: ["action", "theme"],
31
31
  history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
32
- provider: ["action", "operation", "provider", "model", "auto_review_model"] }[input.action];
32
+ provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort"] }[input.action];
33
33
  if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
34
34
  if (input.action === "preference") {
35
35
  writeServicePreference(input.key, input.value, options);
36
36
  if (input.key === "prediction_enabled") clientIntegration?.setPredictionActive(input.value);
37
37
  terminal?.apply?.({ ...servicePreferences(options) });
38
+ } else if (input.action === "color_theme") {
39
+ writeTerminalColorTheme(input.theme, options);terminal?.apply?.({ color_theme: input.theme });
38
40
  } else if (input.action === "animation") {
39
41
  if (!isTerminalAnimationTheme(input.theme)) throw new Error("Select a listed animation theme");
40
42
  writeTerminalAnimationTheme(input.theme, options);terminal?.apply?.({ theme: input.theme });
@@ -49,9 +51,9 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
49
51
  try { writeResponseHistoryLimitMib(input.mib, options); } catch (error) { setHistoryCacheLimit(before);throw error; }
50
52
  } else if (input.action === "history_clean") cleanRuntimeCaches({ history: true });
51
53
  else {
52
- if (!providerRuntime || !["on", "off", "switch"].includes(input.operation)) throw new Error("Invalid provider operation");
54
+ if (!providerRuntime || !["on", "off", "switch", "auto-review"].includes(input.operation)) throw new Error("Invalid provider operation");
53
55
  if (input.operation === "on" && env.CCDX_M365 === "0") throw new Error("Microsoft 365 is disabled by CCDX_M365=0");
54
- await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model });
56
+ await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort, effort: input.auto_review_effort });
55
57
  }
56
58
  return snapshot();
57
59
  }
@@ -1,5 +1,7 @@
1
1
  import { status } from "./status.mjs";
2
2
  import { terminalCell } from "./terminal-text.mjs";
3
+ import { colorTerminalText } from "./terminal-colors.mjs";
4
+ import { terminalColorPreference } from "./user-settings.mjs";
3
5
 
4
6
  // The favicon's three ellipses, rasterized as terminal half-blocks. No runtime
5
7
  // graphics library or terminal cursor control is needed.
@@ -12,12 +14,13 @@ const ATOM = [
12
14
  " ▀▄█▀ ▀█▄▀ ",
13
15
  ];
14
16
 
15
- export function startupBanner({ commandName = "ccdx", version, stream = process.stdout, env = process.env } = {}) {
17
+ export function startupBanner({ commandName = "ccdx", version, stream = process.stdout, env = process.env, home, colorTheme } = {}) {
16
18
  const title = `${terminalCell(commandName)} v${terminalCell(version)} by Dale Xiao`;
17
19
  const color = stream.isTTY === true && !Object.hasOwn(env, "NO_COLOR") && env.TERM !== "dumb";
18
20
  if (!color || Number(stream.columns || 80) < 72) return `${title}\nLocal model services for Codex and Claude`;
19
21
  const labels = new Map([[1, `${terminalCell(commandName).toUpperCase()} v${terminalCell(version)}`], [2, "by Dale Xiao"], [4, "Codex + Claude / local services"]]);
20
- return ATOM.map((line, i) => `\x1b[38;2;166;245;168m${line}\x1b[0m${labels.has(i) ? ` ${labels.get(i)}` : ""}`).join("\n");
22
+ const theme = colorTheme || terminalColorPreference({ env, home });
23
+ return ATOM.map((line, i) => `${colorTerminalText(line, theme, { output: stream, env })}${labels.has(i) ? ` ${labels.get(i)}` : ""}`).join("\n");
21
24
  }
22
25
 
23
26
  export function startupCheck(kind, name, detail) {
@@ -0,0 +1,20 @@
1
+ export const isColorTheme = value => value === "green" || value === "klein";
2
+
3
+ export function terminalColorCode(theme, { output = process.stdout, env = process.env } = {}) {
4
+ if (output.isTTY !== true || Object.hasOwn(env, "NO_COLOR") || env.TERM === "dumb") return "";
5
+ // Preserve the original green exactly. Blue also supports ordinary ANSI terminals.
6
+ if (theme !== "klein") return "\x1b[38;2;166;245;168m";
7
+ const depth = output.getColorDepth?.(env) || (/truecolor|24bit/i.test(env.COLORTERM || "") ? 24 : 4);
8
+ return depth >= 24 ? "\x1b[38;2;76;159;255m" : depth >= 8 ? "\x1b[38;5;75m" : "\x1b[94m";
9
+ }
10
+
11
+ export function colorTerminalText(text, theme, options) {
12
+ const code = terminalColorCode(theme, options);
13
+ return code ? `${code}${text}\x1b[0m` : text;
14
+ }
15
+
16
+ export function colorTerminalMotion(frame, theme, options) {
17
+ if (theme !== "klein") return frame;
18
+ const code = terminalColorCode(theme, options);
19
+ return frame.replace(/\x1b\[(?:38;5;\d+|97)m/g, code);
20
+ }
@@ -5,6 +5,7 @@ import { DEFAULT_TERMINAL_ANIMATION_THEME, TERMINAL_ANIMATION_THEMES, isTerminal
5
5
  getTerminalAnimationCycleLength, getTerminalAnimationFrameDelay } from "./terminal-animation.mjs";
6
6
  import { displayWidth } from "./cli-table.mjs";
7
7
  import { providerStartupSummary } from "./startup-ui.mjs";
8
+ import { colorTerminalText, colorTerminalMotion } from "./terminal-colors.mjs";
8
9
 
9
10
  const clear = "\r\x1b[2K";
10
11
  const flagOff = value => /^(0|false|no|off)$/i.test(String(value || ""));
@@ -16,7 +17,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
16
17
  let running = false, timer = null, lines = 0, active = 0, frame = 0, lastRead = 0, data = {};
17
18
  let notices = 0, lastNotice = "", lastPrintedNotice = "", previous = [];
18
19
  let content = [], dirty = true, readFailed = false, updatedAt = null, fits = true;
19
- let current = { theme: DEFAULT_TERMINAL_ANIMATION_THEME, terminal_animation_enabled: true };
20
+ let current = { theme: DEFAULT_TERMINAL_ANIMATION_THEME, color_theme: "green", terminal_animation_enabled: true };
20
21
  let frameDelay = 1000;
21
22
  const tty = output.isTTY === true && errorOutput.isTTY === true && (!env.CI || flagOff(env.CI)) && env.TERM !== "dumb";
22
23
  const supported = () => tty && (Number(output.columns) || 80) >= 40 && (Number(output.rows) || 24) >= 16;
@@ -66,6 +67,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
66
67
  frame %= getTerminalAnimationCycleLength(current.theme);
67
68
  const metadata = TERMINAL_ANIMATION_THEMES.find(theme => theme.id === current.theme), index = metadata.startFrame + frame;
68
69
  motion = renderTerminalAnimationFrame(current.theme, index);
70
+ motion = colorTerminalMotion(motion, current.color_theme, { output, env });
69
71
  if (Object.hasOwn(env, "NO_COLOR")) motion = stripVTControlCharacters(motion);
70
72
  frame = (frame + 1) % getTerminalAnimationCycleLength(current.theme);
71
73
  frameDelay = getTerminalAnimationFrameDelay(current.theme, index) + (frame === 0 ? metadata.loopPauseMs : 0);
@@ -92,7 +94,9 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
92
94
  }
93
95
  dirty = false;
94
96
  }
95
- const body = [...content, `${motion} ${active ? "Working" : "Idle"}`];
97
+ // Apply color after clipping/layout so escape sequences never consume columns.
98
+ const body = [...content.map(line => current.color_theme === "klein" && /^[┌│├└]/.test(line)
99
+ ? colorTerminalText(line, current.color_theme, { output, env }) : line), `${motion} ${active ? "Working" : "Idle"}`];
96
100
  fits = body.length < (Number(output.rows) || 24);
97
101
  if (!fits) { frameDelay = 1000;return; }
98
102
  // Animation ticks update only the final line; data stays on its 1s cadence.
@@ -3,6 +3,7 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
5
5
  import { withFileLockSync } from "./lock.mjs";
6
+ import { isColorTheme } from "./terminal-colors.mjs";
6
7
  import { AUTO_REVIEW_REASONING_EFFORTS, DEFAULT_CODEX_AUTO_REVIEW_MODEL } from "./models.mjs";
7
8
  import { loadRuntimeConfig, RUNTIME_DEFAULTS } from "./runtime-config.mjs";
8
9
  import {
@@ -50,6 +51,10 @@ export function readUserSettings({ env = process.env, home = os.homedir(), stric
50
51
  delete parsed[key];
51
52
  }
52
53
  }
54
+ if (Object.hasOwn(parsed, "terminal_color_theme") && !isColorTheme(parsed.terminal_color_theme)) {
55
+ if (strict) throw invalidSettings(filePath, "terminal_color_theme must be green or klein");
56
+ delete parsed.terminal_color_theme;
57
+ }
53
58
  if (Object.hasOwn(parsed, AUTO_REVIEW_MODEL_KEY)) {
54
59
  const value = parsed[AUTO_REVIEW_MODEL_KEY];
55
60
  if (typeof value !== "string" || !value.trim()) {
@@ -123,10 +128,26 @@ const serviceFlags = settings => Object.fromEntries(SERVICE_FLAGS.map(key => [ke
123
128
  // One strict read gives each status update a coherent view; no stale cache.
124
129
  export function serviceSettingsSnapshot(options = {}) {
125
130
  const settings = readUserSettings({ ...options, strict: true });
126
- return { saved: serviceFlags(settings), theme: animationPreference(settings).theme,
131
+ return { saved: serviceFlags(settings), theme: animationPreference(settings).theme, color_theme: settings.terminal_color_theme || "green",
127
132
  historyLimit: historyLimitPreference(settings, options.env || process.env) };
128
133
  }
129
134
 
135
+ export function terminalColorPreference(options = {}) {
136
+ return readUserSettings(options).terminal_color_theme || "green";
137
+ }
138
+
139
+ export function writeTerminalColorTheme(theme, options = {}) {
140
+ if (!isColorTheme(theme)) throw new Error("Choose green or klein for the terminal color theme");
141
+ return withFileLockSync(`${userSettingsPath(options)}.lock`, () => {
142
+ const settings = readUserSettings({ ...options, strict: true });
143
+ const next = { ...settings };
144
+ if (theme === "green") delete next.terminal_color_theme;
145
+ else next.terminal_color_theme = theme;
146
+ const changed = atomicWriteFileIfChangedSync(userSettingsPath(options), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
147
+ return { changed, color_theme: theme };
148
+ });
149
+ }
150
+
130
151
  export function writeServicePreference(key, value, options = {}) {
131
152
  if (!SERVICE_FLAGS.includes(key) || typeof value !== "boolean") throw new Error("Unknown service setting or invalid boolean");
132
153
  return withFileLockSync(`${userSettingsPath(options)}.lock`, () => {
package/src/version.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import { stableVersion as githubReleaseVersion } from "./release-install.mjs";
2
3
  import path from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
5
  import { operationError } from "./operation-error.mjs";
@@ -30,12 +31,7 @@ export function isVersionGreater(a, b) {
30
31
  return false;
31
32
  }
32
33
 
33
- export function githubReleaseVersion(tag) {
34
- if (typeof tag !== "string" || tag.length > 64) return null;
35
- const match = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(tag);
36
- if (!match || !match.slice(1).every((part) => Number.isSafeInteger(Number(part)))) return null;
37
- return match.slice(1).join(".");
38
- }
34
+ export { stableVersion as githubReleaseVersion } from "./release-install.mjs";
39
35
 
40
36
  export async function lookupLatestRelease({ fetchImpl = fetch, timeoutMs = 2000 } = {}) {
41
37
  const controller = new AbortController();
@@ -37,6 +37,16 @@ exit $ret
37
37
  `;
38
38
  }
39
39
 
40
+ export function privateWindowsCommand({ node, cli, prefix }) {
41
+ const relativeNode = path.relative(prefix, node), relativeCli = path.relative(prefix, cli);
42
+ const privateNode = !path.isAbsolute(relativeNode) && !relativeNode.startsWith(`..${path.sep}`);
43
+ // Expand the native batch directory at run time. Embedding a UTF-8 absolute
44
+ // path in a .cmd file breaks Unicode profiles under legacy console code pages.
45
+ const binary = privateNode ? `%~dp0${relativeNode}` : "node.exe";
46
+ const nodePath = privateNode ? `set "PATH=%~dp0${path.dirname(relativeNode)};%PATH%"\r\n` : "";
47
+ return `@echo off\r\nsetlocal DisableDelayedExpansion\r\nset "CCDX_PRIVATE_INSTALL_PREFIX=%~dp0"\r\n${nodePath}if not defined npm_config_prefix set "npm_config_prefix=%~dp0"\r\n"${binary}" "%~dp0${relativeCli}" %*\r\nexit /b %errorlevel%\r\n`;
48
+ }
49
+
40
50
  export function inspectWindowsCommand({ platform = process.platform,
41
51
  packageRoot = fileURLToPath(new URL("../", import.meta.url)), repair = false, locked = false } = {}) {
42
52
  if (platform !== "win32") return { status: "not_applicable", changed: false };
@@ -58,7 +68,9 @@ export function inspectWindowsCommand({ platform = process.platform,
58
68
  try {
59
69
  if (!fs.lstatSync(cmd).isFile() || fs.statSync(cmd).size > 8192) throw new Error();
60
70
  const batch = fs.readFileSync(cmd, "utf8");
61
- if (!batch.startsWith("@ECHO off") || !batch.includes(`"%dp0%\\${target.replaceAll("/", "\\")}" %*`)) throw new Error();
71
+ const ownedNpm = batch.startsWith("@ECHO off") && batch.includes(`"%dp0%\\${target.replaceAll("/", "\\")}" %*`);
72
+ const ownedPrivate = batch === privateWindowsCommand({ node: process.execPath, cli: path.join(root, "bin", script), prefix });
73
+ if (!ownedNpm && !ownedPrivate) throw new Error();
62
74
  let stat;
63
75
  try { stat = fs.lstatSync(ps1); } catch (error) { if (error.code !== "ENOENT") throw error; }
64
76
  if (!stat) { results.push({ name, status: "ready", changed: false });continue; }