codex-copilot-dx 1.2.31 → 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.
- package/README.md +28 -30
- package/bin/cli.mjs +28 -6
- package/docs/ARCHITECTURE.md +40 -0
- package/docs/REFERENCE.md +151 -20
- package/package.json +1 -1
- package/src/cli-command-spec.mjs +123 -0
- package/src/cli-image.mjs +2 -2
- package/src/cli-management.mjs +340 -0
- package/src/cli-options.mjs +19 -52
- package/src/cli-status.mjs +7 -7
- package/src/cli-tools.mjs +3 -2
- package/src/client-integration.mjs +7 -3
- package/src/config.mjs +4 -3
- package/src/connection-runtime.mjs +47 -14
- package/src/dashboard/index.html +1 -1
- package/src/dashboard/language.js +1 -0
- package/src/dashboard/preferences.js +1 -1
- package/src/dashboard/theme.js +2 -2
- package/src/dashboard/ui.css +32 -2
- package/src/service-control.mjs +1 -1
- package/src/settings-preferences.mjs +6 -4
- package/src/startup-ui.mjs +29 -1
- package/src/terminal-console.mjs +31 -30
- package/src/terminal-state.mjs +69 -0
|
@@ -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 (
|
|
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
|
}
|
package/src/dashboard/index.html
CHANGED
|
@@ -351,7 +351,7 @@
|
|
|
351
351
|
<h2 id="web-appearance-title" data-i18n="appearance_web_appearance">网页外观</h2>
|
|
352
352
|
<div class="appearance-row">
|
|
353
353
|
<div class="appearance-label"><label for="web-color-theme" data-i18n="appearance_color_theme">颜色主题</label><p id="web-color-note" role="status" data-i18n="theme_saved_browser">This browser only. Applies now.</p></div>
|
|
354
|
-
<select id="web-color-theme" class="appearance-select"><option value="green" data-i18n="appearance_classic_green">经典绿(默认)</option><option value="klein" data-i18n="appearance_klein_blue">克莱因蓝</option><option value="pink" data-i18n="appearance_soft_pink">淡粉色</option></select>
|
|
354
|
+
<select id="web-color-theme" class="appearance-select"><option value="green" data-i18n="appearance_classic_green">经典绿(默认)</option><option value="klein" data-i18n="appearance_klein_blue">克莱因蓝</option><option value="pink" data-i18n="appearance_soft_pink">淡粉色</option><option value="mono" data-i18n="appearance_pure_white">纯白</option></select>
|
|
355
355
|
</div>
|
|
356
356
|
</section>
|
|
357
357
|
|
|
@@ -545,6 +545,7 @@
|
|
|
545
545
|
"appearance_classic_green": ["Classic green (default)", "经典绿(默认)"],
|
|
546
546
|
"appearance_klein_blue": ["Klein blue", "克莱因蓝"],
|
|
547
547
|
"appearance_soft_pink": ["Soft pink", "淡粉色"],
|
|
548
|
+
"appearance_pure_white": ["Pure white", "纯白"],
|
|
548
549
|
"model_activity_active": ["Processing {count} requests", "正在处理 {count} 个请求"],
|
|
549
550
|
"model_activity_idle": ["No model requests", "暂无模型请求"],
|
|
550
551
|
"model_activity_unknown": ["Activity unknown", "活动状态未知"],
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
const raw = localStorage.getItem(backupKey);if (raw === null) return { version: 1, entries: [] };
|
|
14
14
|
const value = JSON.parse(raw);
|
|
15
15
|
if (value?.version !== 1 || !Array.isArray(value.entries) || value.entries.length > 2 || value.entries.some(entry => typeof entry.id !== "string"
|
|
16
|
-
|| !["dark", "light"].includes(entry.values?.theme) || !["green", "klein", "pink"].includes(entry.values?.palette))) throw Error("preferences_browser_backup_invalid");
|
|
16
|
+
|| !["dark", "light"].includes(entry.values?.theme) || !["green", "klein", "pink", "mono"].includes(entry.values?.palette))) throw Error("preferences_browser_backup_invalid");
|
|
17
17
|
return value;
|
|
18
18
|
}
|
|
19
19
|
function render() {
|
package/src/dashboard/theme.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const key = "ccdx.dashboard.theme", paletteKey = "ccdx.dashboard.palette";
|
|
3
|
-
const valid = value => value === "green" || value === "klein" || value === "pink";
|
|
3
|
+
const valid = value => value === "green" || value === "klein" || value === "pink" || value === "mono";
|
|
4
4
|
let theme = "dark", palette = "green", saved = true;
|
|
5
5
|
try {
|
|
6
6
|
if (localStorage.getItem(key) === "light") theme = "light";
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
const applyTheme = () => {
|
|
19
19
|
document.documentElement.dataset.theme = theme;
|
|
20
20
|
document.documentElement.dataset.palette = palette;
|
|
21
|
-
const colors = { green: ["#a6f5a8", "#176b3a"], klein: ["#789aff", "#002fa7"], pink: ["#f3a8c8", "#a83e68"] };
|
|
21
|
+
const colors = { green: ["#a6f5a8", "#176b3a"], klein: ["#789aff", "#002fa7"], pink: ["#f3a8c8", "#a83e68"], mono: ["#ffffff", "#000000"] };
|
|
22
22
|
const color = colors[palette][theme === "dark" ? 0 : 1];
|
|
23
23
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><g fill="none" stroke="${color}" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="${color}"/></svg>`;
|
|
24
24
|
document.getElementById("favicon").href = `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
package/src/dashboard/ui.css
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
:root { color-scheme: dark; font-
|
|
1
|
+
:root { color-scheme: dark; --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", "Noto Sans SC", "WenQuanYi Micro Hei", monospace; font-family: var(--font-mono); --page: #0b110d; --surface: #111a13; --text: #e0e9df; --strong: #f0f6ec; --muted: #9aada0; --badge: #a9b9aa; --subtle: #78917d; --quiet: #819987; --footer: #7f9785; --border: #2b3b2f; --top-border: #2a3a2e; --accent: #a6f5a8; --accent-soft: #84e99e; --heading: #83b98b; --bad: #ff947e; --failed: #ff9f91; --incomplete: #e3c77c; --button-border: #45634b; --button-bg: #152219; --button-fg: #b2f1bd; --button-hover: #203526; --selected-bg: #192a1d; --option-hover: #1a2a1e; --table-text: #d8e2d8; --preview: #657d69; --ansi-white: #f5fff5; --ansi-159: #9af5e9; --ansi-123: #75e4d9; --ansi-87: #5ad0d4; --ansi-51: #42b9d8; --ansi-45: #3ca2d0; --ansi-39: #4389c2; --ansi-33: #4775b2; }
|
|
2
2
|
:root[data-theme="light"] { color-scheme: light; --page: #f5f8f3; --surface: #ffffff; --text: #1b2b20; --strong: #122219; --muted: #475d4e; --badge: #475d4e; --subtle: #4b6652; --quiet: #55715c; --footer: #59735f; --border: #c4d2c5; --top-border: #b8c9ba; --accent: #176b3a; --accent-soft: #176b3a; --heading: #235f37; --bad: #a33625; --failed: #a33625; --incomplete: #835600; --button-border: #79a085; --button-bg: #ebf4ec; --button-fg: #185b32; --button-hover: #dbeedd; --selected-bg: #e4f3e7; --option-hover: #edf6ee; --table-text: #233b2b; --preview: #596f60; --ansi-white: #234231; --ansi-159: #116b64; --ansi-123: #0d7771; --ansi-87: #116b75; --ansi-51: #14697e; --ansi-45: #1a6183; --ansi-39: #265f8d; --ansi-33: #365a8d; }
|
|
3
3
|
* { box-sizing: border-box; }
|
|
4
|
+
input, textarea, select, button { font-family: inherit; }
|
|
5
|
+
pre, code, kbd, samp { font-family: var(--font-mono); }
|
|
4
6
|
[hidden] { display: none !important; }
|
|
5
7
|
body { margin: 0; color: var(--text); background: var(--page); font-size: 13px; }
|
|
6
8
|
html { scrollbar-gutter: stable; }
|
|
@@ -350,7 +352,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
350
352
|
.terminal-brand { display:flex; align-items:center; flex-wrap:wrap; gap:14px; margin-bottom:15px; }
|
|
351
353
|
.terminal-brand strong { color:var(--sample-text); display:block; font-size:12px; font-weight:500; line-height:1.7; }
|
|
352
354
|
.terminal-brand div>span { display:block; color:var(--sample-muted); font-size:11px; line-height:1.7; }
|
|
353
|
-
.terminal-sample pre { font-family:
|
|
355
|
+
.terminal-sample pre { font-family:var(--font-mono); padding:0; margin:0; background:transparent; border:0; border-radius:0; letter-spacing:0; }
|
|
354
356
|
.terminal-sample .terminal-logo { color:var(--sample-logo); font-size:12px; line-height:1.15; white-space:pre; }
|
|
355
357
|
.terminal-sample .terminal-table { color:var(--sample-table); font-size:11px; line-height:1.45; white-space:pre; }
|
|
356
358
|
.terminal-sample .terminal-notices { margin-top:10px; font-size:11px; line-height:1.6; white-space:pre-wrap; color:var(--sample-muted); }
|
|
@@ -387,6 +389,27 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
387
389
|
--ansi-51:#e99bbd; --ansi-45:#da8bb0; --ansi-39:#cd7fa5; --ansi-33:#bd739a;
|
|
388
390
|
--bad:#ff947e; --failed:#ff9f91; --incomplete:#e3c77c;
|
|
389
391
|
}
|
|
392
|
+
/* Pure white is a WebUI palette; terminal colors remain independent. */
|
|
393
|
+
:root[data-palette="mono"] {
|
|
394
|
+
--page:#000; --surface:#000; --text:#fff; --strong:#fff;
|
|
395
|
+
--muted:#b3b3b3; --badge:#b3b3b3; --subtle:#b3b3b3; --quiet:#b3b3b3; --footer:#b3b3b3;
|
|
396
|
+
--border:#666; --top-border:#666; --accent:#fff; --accent-soft:#fff; --heading:#fff;
|
|
397
|
+
--button-border:#999; --button-bg:#000; --button-fg:#fff; --button-hover:#242424;
|
|
398
|
+
--selected-bg:#242424; --option-hover:#242424; --table-text:#fff; --preview:#b3b3b3;
|
|
399
|
+
--ansi-white:#fff; --ansi-159:#ddd; --ansi-123:#ccc; --ansi-87:#bbb;
|
|
400
|
+
--ansi-51:#aaa; --ansi-45:#999; --ansi-39:#888; --ansi-33:#777;
|
|
401
|
+
--bad:#fff; --failed:#fff; --incomplete:#fff;
|
|
402
|
+
}
|
|
403
|
+
:root[data-palette="mono"][data-theme="light"] {
|
|
404
|
+
--page:#fff; --surface:#fff; --text:#000; --strong:#000;
|
|
405
|
+
--muted:#4c4c4c; --badge:#4c4c4c; --subtle:#4c4c4c; --quiet:#4c4c4c; --footer:#4c4c4c;
|
|
406
|
+
--border:#999; --top-border:#999; --accent:#000; --accent-soft:#000; --heading:#000;
|
|
407
|
+
--button-border:#666; --button-bg:#fff; --button-fg:#000; --button-hover:#ededed;
|
|
408
|
+
--selected-bg:#ededed; --option-hover:#ededed; --table-text:#000; --preview:#4c4c4c;
|
|
409
|
+
--ansi-white:#000; --ansi-159:#222; --ansi-123:#333; --ansi-87:#444;
|
|
410
|
+
--ansi-51:#555; --ansi-45:#666; --ansi-39:#777; --ansi-33:#888;
|
|
411
|
+
--bad:#000; --failed:#000; --incomplete:#000;
|
|
412
|
+
}
|
|
390
413
|
.terminal-sample[data-terminal-palette="pink"] { --sample-logo:#f3a8c8; --sample-table:#f3a8c8; --sample-motion:#f3a8c8; }
|
|
391
414
|
:root:not([data-theme="light"]) #animation-settings[data-terminal-palette="pink"] { --ansi-white:#f3a8c8;--ansi-159:#f3a8c8;--ansi-123:#f3a8c8;--ansi-87:#f3a8c8;--ansi-51:#f3a8c8;--ansi-45:#f3a8c8;--ansi-39:#f3a8c8;--ansi-33:#f3a8c8; }
|
|
392
415
|
:root[data-theme="light"] #animation-settings[data-terminal-palette="pink"] { --ansi-white:#a83e68;--ansi-159:#a83e68;--ansi-123:#a83e68;--ansi-87:#a83e68;--ansi-51:#a83e68;--ansi-45:#a83e68;--ansi-39:#a83e68;--ansi-33:#a83e68; }
|
|
@@ -458,6 +481,11 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
458
481
|
.flow-column { display:flex;flex-direction:column; }
|
|
459
482
|
.flow-column-title { height:18px;line-height:18px;margin:0 0 18px;color:var(--muted);font-size:11px;text-align:center; }
|
|
460
483
|
.flow-apps,#flow-models { display:flex;flex:1;flex-direction:column;justify-content:center;align-items:center;gap:68px;padding:32px 0;min-width:0; }
|
|
484
|
+
#flow-apps { align-items:flex-end; }
|
|
485
|
+
#flow-apps .flow-node { justify-content:flex-end; }
|
|
486
|
+
#flow-apps .flow-choice { text-align:right; }
|
|
487
|
+
#flow-apps .flow-count { margin-right:9px; }
|
|
488
|
+
#flow-apps .flow-note { left:auto;right:9px;text-align:right; }
|
|
461
489
|
.flow-hub-column { display:flex;align-items:center;justify-content:center;padding-top:36px; }
|
|
462
490
|
.flow-node { position:relative;display:flex;align-items:center;gap:8px;width:max-content;max-width:100%;min-height:34px; }
|
|
463
491
|
.flow-choice { min-width:0;max-width:100%;min-height:34px;padding:7px 9px;border-color:transparent;background:transparent;color:var(--text);font-size:12px;font-weight:600;text-transform:none;text-align:center;overflow-wrap:anywhere; }
|
|
@@ -498,6 +526,8 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
498
526
|
.flow-apps,#flow-models { gap:92px; }
|
|
499
527
|
.flow-count { position:absolute;top:calc(100% + 46px);left:0;font-size:10px; }
|
|
500
528
|
.flow-source,.flow-note { left:4px; }
|
|
529
|
+
#flow-apps .flow-count { left:auto;right:4px;margin-right:0;text-align:right; }
|
|
530
|
+
#flow-apps .flow-note { left:auto;right:4px; }
|
|
501
531
|
}
|
|
502
532
|
@media(max-width:460px) {
|
|
503
533
|
.flow-network { grid-template-columns:minmax(80px,1fr) 48px minmax(100px,1fr);column-gap:12px; }
|
package/src/service-control.mjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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 =
|
|
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") {
|
package/src/startup-ui.mjs
CHANGED
|
@@ -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, "
|
|
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;
|
package/src/terminal-console.mjs
CHANGED
|
@@ -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 {
|
|
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,
|
|
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
|
|
56
|
-
["Output", usage.output_tokens], ["Partial
|
|
57
|
-
const requestRows = [["
|
|
58
|
-
|
|
59
|
-
|
|
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
|
|
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
|
-
|
|
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 || {},
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
const
|
|
83
|
-
const
|
|
84
|
-
const
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
|
95
|
-
content = [clip(heading, width),
|
|
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 ? "
|
|
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() {
|
|
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
|
+
}
|