codex-copilot-dx 1.2.1 → 1.2.3

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.
@@ -6,6 +6,7 @@ import { promisify } from "node:util";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import path from "node:path";
9
+ import { normalizeBrokerAccounts, chooseM365Account, windowsAccountHint } from "./m365-accounts.mjs";
9
10
 
10
11
  export const M365_CLIENT_ID = "aebc6443-996d-45c2-90f0-388ff96faa56";
11
12
  export const M365_RESOURCE = "42c8f7bd-c7a8-4ba9-bc1c-91edfb716247";
@@ -19,9 +20,9 @@ export function brokerFailure(error) {
19
20
  return { code, aadsts: [...new Set(String(error?.errorContext || "").match(/AADSTS\d+/g) || [])].slice(0, 3) };
20
21
  }
21
22
 
22
- export async function acquireSilentM365Token({ account = null } = {}, {
23
+ export async function acquireSilentM365Token({ account = null, action = "token" } = {}, {
23
24
  platform = process.platform, loadBroker = () => createRequire(import.meta.url)("@azure/msal-node-runtime").msalNodeRuntime,
24
- execFileImpl = promisify(execFile),
25
+ execFileImpl = promisify(execFile), env = process.env,
25
26
  } = {}) {
26
27
  if (!["darwin", "win32"].includes(platform)) throw fail("m365_platform_unsupported");
27
28
  if (platform === "darwin") {
@@ -39,18 +40,19 @@ export async function acquireSilentM365Token({ account = null } = {}, {
39
40
  catch (error) { reject(error); }
40
41
  });
41
42
  const discovered = await invoke("DiscoverAccountsAsync", M365_CLIENT_ID, randomUUID());
42
- const accounts = (discovered.accounts || []).filter(value => value.accountId && value.username && value.realm);
43
- const matching = account ? accounts.filter(value => value.homeAccountId === account.id && value.realm === account.tenant) : accounts;
44
- if (!matching.length) throw fail("m365_account_unavailable");
45
- if (matching.length !== 1) throw fail("m365_account_ambiguous");
46
- const selected = matching[0], parameters = new broker.AuthParameters();
43
+ const accounts = normalizeBrokerAccounts(discovered.accounts || []);
44
+ const windowsLogin = (!account || action === "accounts") && accounts.length > 1
45
+ ? await windowsAccountHint({ platform, env, execFileImpl }) : null;
46
+ if (action === "accounts") return { accounts: accounts.map(({ native, ...value }) => value), windowsLogin };
47
+ const selected = chooseM365Account(accounts, { binding: account, windowsLogin }), parameters = new broker.AuthParameters();
47
48
  parameters.CreateAuthParameters(M365_CLIENT_ID, AUTHORITY);
48
49
  parameters.SetRedirectUri(platform === "darwin" ? "msauth.com.msauth.unsignedapp://auth" : `ms-appx-web://Microsoft.AAD.BrokerPlugin/${M365_CLIENT_ID}`);
49
50
  parameters.SetRequestedScopes(`${M365_RESOURCE}/.default`);
50
- const result = await invoke("AcquireTokenSilentlyAsync", parameters, randomUUID(), selected);
51
+ const result = await invoke("AcquireTokenSilentlyAsync", parameters, randomUUID(), selected.native);
51
52
  if (!result.accessToken || !String(result.grantedScopes || "").split(" ").includes(`${M365_RESOURCE}/LLM.Read`)) throw fail("m365_llm_permission_unavailable");
53
+ if (result.account && (result.account.homeAccountId !== selected.id || result.account.realm !== selected.tenant)) throw fail("m365_account_changed");
52
54
  return { token: result.accessToken, expiresAt: Number(result.expiresOn) * 1000,
53
- account: { id: selected.homeAccountId, tenant: selected.realm, login: selected.username } };
55
+ account: { id: selected.id, tenant: selected.tenant, login: selected.login, selection_source: selected.selection_source } };
54
56
  }
55
57
 
56
58
  async function main() {
@@ -63,7 +65,7 @@ async function main() {
63
65
  if (Buffer.byteLength(input) > 4096) throw fail("m365_auth_request_invalid");
64
66
  }
65
67
  const request = JSON.parse(input);
66
- if (request.action !== "token") throw fail("m365_auth_request_invalid");
68
+ if (!["token", "accounts"].includes(request.action)) throw fail("m365_auth_request_invalid");
67
69
  const result = await acquireSilentM365Token(request);
68
70
  process.stdout.write(JSON.stringify(result), () => process.exit(0));
69
71
  } catch (error) { process.stdout.write(JSON.stringify({ error: brokerFailure(error) }), () => process.exit(1)); }
@@ -12,7 +12,7 @@ export function m365HelperEnvironment(env = process.env) {
12
12
  return Object.fromEntries(Object.entries(env).filter(([key]) => keys.has(key.toUpperCase())));
13
13
  }
14
14
 
15
- export function requestM365Token({ account, signal, env = process.env, spawnImpl = spawn, timeoutMs = 28000 } = {}) {
15
+ function requestM365Helper({ action = "token", account, signal, env = process.env, spawnImpl = spawn, timeoutMs = 28000 } = {}) {
16
16
  if (signal?.aborted) return Promise.reject(abortError(signal));
17
17
  return new Promise((resolve, reject) => {
18
18
  let child, timer, finished = false, bytes = 0;
@@ -46,6 +46,12 @@ export function requestM365Token({ account, signal, env = process.env, spawnImpl
46
46
  finish(m365Error(/^m365_[a-z_]+$/.test(result.error?.code || "") ? result.error.code : "m365_auth_failed"));return;
47
47
  }
48
48
  try {
49
+ if (action === "accounts") {
50
+ if (!Array.isArray(result.accounts) || result.accounts.length > 128) throw Error();
51
+ for (const value of result.accounts) m365AccountKey(value);
52
+ if (result.windowsLogin !== null && (typeof result.windowsLogin !== "string" || result.windowsLogin.length > 320 || /[\r\n\0]/.test(result.windowsLogin))) throw Error();
53
+ finish(null, result);return;
54
+ }
49
55
  m365AccountKey(result.account);
50
56
  if (typeof result.token !== "string" || !result.token || /\s/.test(result.token)
51
57
  || !Number.isFinite(result.expiresAt) || result.expiresAt <= Date.now()) throw Error();
@@ -53,11 +59,14 @@ export function requestM365Token({ account, signal, env = process.env, spawnImpl
53
59
  } catch { finish(m365Error("m365_auth_response_invalid"));return; }
54
60
  finish(null, result);
55
61
  });
56
- child.stdin.end(JSON.stringify({ action: "token", account: account || null }));
62
+ child.stdin.end(JSON.stringify({ action, account: account || null }));
57
63
  });
58
64
  }
59
65
 
60
- export function createM365Auth({ home, env = process.env, acquire = requestM365Token, now = Date.now } = {}) {
66
+ export const requestM365Token = options => requestM365Helper({ ...options, action: "token" });
67
+ export const requestM365Accounts = options => requestM365Helper({ ...options, action: "accounts" });
68
+
69
+ export function createM365Auth({ home, env = process.env, account, acquire = requestM365Token, now = Date.now } = {}) {
61
70
  let cached = null, flight = null, generation = 0, lastError = null, retryAt = 0, checkedAt = null;
62
71
  const snapshot = () => ({ token_cached: Boolean(cached && cached.expiresAt > now()),
63
72
  token_expires_in_ms: cached ? Math.max(0, cached.expiresAt - now()) : null,
@@ -71,7 +80,7 @@ export function createM365Auth({ home, env = process.env, acquire = requestM365T
71
80
  if (!flight) {
72
81
  const controller = new AbortController(), current = generation;
73
82
  const entry = { controller, waiters: 0, settled: false, promise: null };
74
- entry.promise = Promise.resolve().then(() => acquire({ account: cached?.account || readM365Account({ home }), env, signal: controller.signal }))
83
+ entry.promise = Promise.resolve().then(() => acquire({ account: cached?.account || account || readM365Account({ home }), env, signal: controller.signal }))
75
84
  .then(result => {
76
85
  if (current !== generation || controller.signal.aborted) throw abortError(controller.signal);
77
86
  m365AccountKey(result.account);
@@ -0,0 +1,42 @@
1
+ import { createHash } from "node:crypto";
2
+ import { m365Paths, readM365Json, writeM365Json, m365AccountKey } from "../m365-settings.mjs";
3
+ import { withFileLockSync } from "../lock.mjs";
4
+ import fs from "node:fs";
5
+
6
+ const changed = () => Object.assign(new Error("This conversation belongs to another company account. Start a new conversation."),
7
+ { code: "m365_account_changed", statusCode: 409 });
8
+ const hash = value => createHash("sha256").update(value).digest("hex");
9
+
10
+ export function createM365ConversationGuard({ home } = {}) {
11
+ const { directory, conversations: file } = m365Paths({ home });
12
+ let cached;
13
+ return (account, body, headers = {}) => {
14
+ const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
15
+ let session = headers["session_id"] || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
16
+ if (!session && typeof body.metadata?.user_id === "string") {
17
+ try { session = JSON.parse(body.metadata.user_id)?.session_id; } catch { session = /(?:^|_)session_([\w-]{8,128})$/.exec(body.metadata.user_id)?.[1]; }
18
+ }
19
+ const first = items.find(item => item?.role === "user");
20
+ const key = typeof session === "string" && session.length > 0 && session.length <= 512 && !/[\u0000-\u001f\u007f]/.test(session)
21
+ ? hash(`session\0${session}`) : first ? hash(`first\0${JSON.stringify(first)}`) : typeof body.input === "string" ? hash(`first\0${body.input}`) : null;
22
+ const hasHistory = Boolean(body.previous_response_id) || items.filter(item => item?.role === "user").length > 1
23
+ || items.some(item => item?.role === "assistant" || item?.role === "tool" || /(?:call|output|reasoning|compaction)/.test(item?.type || "")
24
+ || Array.isArray(item?.content) && item.content.some(part => part?.type === "tool_result"));
25
+ if (!key) { if (account.history_isolation && hasHistory) throw changed();return; }
26
+ const owner = m365AccountKey(account);
27
+ if (cached?.[key] === owner) return;
28
+ if (cached?.[key] && cached[key] !== owner) throw changed();
29
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
30
+ withFileLockSync(`${file}.lock`, () => {
31
+ const saved = readM365Json(file, { owners: {} });
32
+ if (!saved.owners || typeof saved.owners !== "object" || Array.isArray(saved.owners)
33
+ || Object.keys(saved.owners).length > 1024 || Object.entries(saved.owners).some(([id, value]) => !/^[a-f0-9]{64}$/.test(id) || !/^[a-f0-9]{64}$/.test(value))) throw changed();
34
+ const owners = saved.owners;
35
+ if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory) throw changed();
36
+ if (owners[key]) { cached = owners;return; }
37
+ owners[key] = owner;
38
+ while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
39
+ writeM365Json(file, { owners });cached = owners;
40
+ });
41
+ };
42
+ }
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { createM365Auth, m365Error } from "./m365-auth.mjs";
3
- import { m365Paths, m365AccountKey, readM365Account, readM365Json, writeM365Json } from "../m365-settings.mjs";
3
+ import { m365Paths, m365AccountKey, readM365Account, readM365Json, writeM365Binding } from "../m365-settings.mjs";
4
4
  import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
5
5
  import { prepareResponsesPayload, summarizeReqBody } from "../image-optimization.mjs";
6
6
  import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
@@ -15,6 +15,7 @@ import { removeNativeImageTools } from "../responses-image-tools.mjs";
15
15
  import { resolveClaudeModel } from "../claude-models.mjs";
16
16
  import { modelReasoningEfforts } from "../provider-metadata.mjs";
17
17
  import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
18
+ import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
18
19
 
19
20
  export const M365_API_BASE = "https://df.loki.delve.office.com/api/v1/llmapi";
20
21
  const SOFT_TTL_MS = 2 * 60 * 60 * 1000;
@@ -66,9 +67,11 @@ export function m365Models(catalog, family) {
66
67
  && model.supported_endpoints.some(endpoint => endpoint === "/responses" || endpoint === "/v1/responses"));
67
68
  }
68
69
 
69
- export function createM365Provider({ home, env = process.env, auth = createM365Auth({ home, env }), fetchImpl,
70
+ export function createM365Provider({ home, env = process.env, account: accountOverride, persist = true,
71
+ auth = createM365Auth({ home, env, account: accountOverride }), fetchImpl,
70
72
  createNetwork, now = Date.now, log = (kind, message) => console.log(status(kind, message)), onCatalog = () => {} } = {}) {
71
73
  const paths = m365Paths({ home });
74
+ const guardConversation = createM365ConversationGuard({ home });
72
75
  let catalog = null, account = null, catalogAt = 0, state = "idle", reason = null, flight = null, controller = null, generation = 0;
73
76
  let network = null, networkFlight = null, cacheTtlAdjustments = 0;
74
77
  const registry = { models: null, source: "unavailable", cacheState: "none", cacheSavedAtMs: null,
@@ -95,7 +98,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
95
98
  registry.source = source;registry.cacheSavedAtMs = savedAt;registry.cacheState = now() - savedAt < SOFT_TTL_MS ? "fresh" : "stale";
96
99
  }
97
100
  try {
98
- account = readM365Account({ home });
101
+ account = accountOverride || readM365Account({ home });
99
102
  const saved = readM365Json(paths.catalog);
100
103
  if (account && saved?.account_key === m365AccountKey(account) && Number.isFinite(saved.saved_at)
101
104
  && now() - saved.saved_at < HARD_TTL_MS) applyCatalog(saved.models, "cache", saved.saved_at);
@@ -143,10 +146,11 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
143
146
  if (!response.ok) throw m365Error(`m365_catalog_http_${response.status}`);
144
147
  let value;try { value = m365Catalog(JSON.parse(raw)); } catch { throw m365Error("m365_catalog_invalid"); }
145
148
  if (current !== generation || signal.aborted) throw m365Error("m365_refresh_cancelled");
146
- account = credential.account;
147
- writeM365Json(paths.account, account);
148
- writeM365Json(paths.catalog, { account_key: m365AccountKey(account), saved_at: now(), models: value });
149
- applyCatalog(value, "live", now());state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
149
+ const savedAt = now();
150
+ const nextAccount = { ...credential.account, ...(account?.history_isolation ? { history_isolation: true } : {}) };
151
+ if (persist) writeM365Binding(nextAccount, { account_key: m365AccountKey(nextAccount), saved_at: savedAt, models: value }, { home, expectedAccount: account });
152
+ account = nextAccount;
153
+ applyCatalog(value, "live", savedAt);state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
150
154
  try { await onCatalog(value); } catch { log("warn", "M365 models are ready; optional client configuration could not be updated"); }
151
155
  return value;
152
156
  })().catch(error => {
@@ -180,6 +184,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
180
184
  cacheModelEndpoints() {},
181
185
  async responses(body, options = {}) {
182
186
  const model = selectedModel(body.model, "gpt");
187
+ if (account) guardConversation(account, body, currentRequestContext()?.clientHeaders || options.headers);
183
188
  const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
184
189
  currentInputStart: options.currentInputStart || 0, signal: options.signal,
185
190
  profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
@@ -197,6 +202,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
197
202
  async messages(body, options = {}) {
198
203
  if (catalog && now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
199
204
  const model = selectedModel(body.model, "claude");
205
+ if (account) guardConversation(account, body, options.headers);
200
206
  const efforts = modelReasoningEfforts(model);
201
207
  if (body.output_config?.effort !== undefined && efforts && !efforts.includes(body.output_config.effort)) {
202
208
  throw protocolError("m365_effort_unavailable", "The selected effort is not advertised by this model. Refresh its model list and select an available effort.");
@@ -236,7 +242,12 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
236
242
  return { resp, reqContext: context, errorText, usedRetryPolicies: new Set() };
237
243
  },
238
244
  },
239
- snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login } : null,
245
+ commitSelection(expectedAccount) {
246
+ if (!catalog || state !== "ready" || !account) throw m365Error("m365_not_ready");
247
+ writeM365Binding(account, { account_key: m365AccountKey(account), saved_at: catalogAt, models: catalog }, { home, expectedAccount });
248
+ persist = true;
249
+ },
250
+ snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login, tenant: account.tenant, selection_source: account.selection_source || "legacy" } : null,
240
251
  network: network?.snapshot() || null,
241
252
  cache_ttl_adjustments: cacheTtlAdjustments,
242
253
  models: { total: catalog?.data.length || 0, claude: m365Models(catalog, "claude").length, gpt: m365Models(catalog, "gpt").length,
@@ -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", "auto_review_effort"] }[input.action];
32
+ provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[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,11 @@ 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", "auto-review"].includes(input.operation)) throw new Error("Invalid provider operation");
54
+ if (!providerRuntime || !["on", "off", "switch", "auto-review", "account"].includes(input.operation)) throw new Error("Invalid provider operation");
55
+ if (input.operation === "account" && (typeof input.account_id !== "string" || !/^[a-f0-9]{64}$/.test(input.account_id))) throw new Error("Select an available company account");
53
56
  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, auto_review_effort: input.auto_review_effort, effort: input.auto_review_effort });
57
+ 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,
58
+ ...(input.operation === "account" ? { account_id: input.account_id } : {}) });
55
59
  }
56
60
  return snapshot();
57
61
  }
@@ -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`, () => {