codex-copilot-dx 1.2.20 → 1.2.22
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 +7 -7
- package/bin/cli.mjs +85 -15
- package/docs/ARCHITECTURE.md +95 -3
- package/docs/REFERENCE.md +148 -13
- package/package.json +2 -1
- package/src/access-settings.mjs +1 -0
- package/src/account-tools.mjs +1 -1
- package/src/adapter.mjs +17 -2
- package/src/api-catalog-refresh.mjs +1 -0
- package/src/api-secrets.mjs +28 -9
- package/src/auth.mjs +2 -0
- package/src/bounded-result-cache.mjs +12 -0
- package/src/client-gateway-keys.mjs +7 -3
- package/src/client-integration.mjs +3 -0
- package/src/client-model-plan.mjs +11 -4
- package/src/clients/codex-models.mjs +2 -2
- package/src/codex-api-config.mjs +94 -26
- package/src/codex-client-doctor.mjs +19 -5
- package/src/codex-config-doctor.mjs +6 -4
- package/src/config.mjs +8 -5
- package/src/connection-runtime.mjs +28 -11
- package/src/dashboard/console.js +6 -1
- package/src/dashboard/flow.js +17 -7
- package/src/dashboard/index.html +6 -0
- package/src/dashboard/language.js +24 -0
- package/src/dashboard/ui.css +16 -2
- package/src/dashboard/ui.js +4 -4
- package/src/dashboard/view-boundary.js +41 -0
- package/src/dashboard-tools.mjs +1 -0
- package/src/dashboard.mjs +26 -5
- package/src/image-mcp.mjs +3 -0
- package/src/image-references.mjs +9 -0
- package/src/local-tools.mjs +1 -1
- package/src/m365-settings.mjs +5 -0
- package/src/nightly-update.mjs +107 -0
- package/src/optional-routes.mjs +19 -5
- package/src/provider-runtime.mjs +3 -2
- package/src/providers/api.mjs +6 -4
- package/src/release-install.mjs +24 -12
- package/src/response-history.mjs +50 -0
- package/src/service-control.mjs +9 -3
- package/src/service-supervisor.mjs +168 -0
- package/src/service-worker.mjs +87 -0
- package/src/terminal-console.mjs +1 -0
- package/src/user-settings.mjs +15 -0
|
@@ -20,8 +20,8 @@ import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from
|
|
|
20
20
|
const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
|
|
21
21
|
export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
|
|
22
22
|
secretStore, createApi = createApiProvider, configureClaude = configureClaudeClients, restoreClaude = restoreClaudeClients,
|
|
23
|
-
configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, now = Date.now, log = () => {} } = {}) {
|
|
24
|
-
const options = { home, env, platform }, secrets = secretStore || createApiSecretStore(options);
|
|
23
|
+
configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, preserveClientConfiguration, now = Date.now, log = () => {} } = {}) {
|
|
24
|
+
const options = { home, env, platform, preserveClientConfiguration }, secrets = secretStore || createApiSecretStore(options);
|
|
25
25
|
const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
|
|
26
26
|
let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
|
|
27
27
|
const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
|
|
@@ -31,7 +31,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
31
31
|
commit: (...args) => enqueue(() => applyCatalog(...args)),
|
|
32
32
|
onState: (id, state) => state ? discoveries.set(id, state) : discoveries.delete(id) });
|
|
33
33
|
const capabilitySupport = inspectClaudeCapabilitySupport(options);
|
|
34
|
-
let sharedSync = null, syncFlight = null, syncAgain = false;const syncTargets = new Set();
|
|
34
|
+
let sharedSync = null, syncFlight = null, syncAgain = false, operations = 0;const syncTargets = new Set();
|
|
35
35
|
function cleanSecrets(id) {
|
|
36
36
|
const refs = retiredSecrets.get(id);if (!refs) return;
|
|
37
37
|
for (const ref of refs) {
|
|
@@ -131,12 +131,19 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
131
131
|
}
|
|
132
132
|
async function performClientSync(targets) {
|
|
133
133
|
if (!managed || closed) return;
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
134
|
+
if (options.preserveClientConfiguration?.()) { for (const id of targets) setup[id] = "preserved";return; }
|
|
135
|
+
const codex = binding("codex"), compiledCodex = plan("codex");
|
|
136
|
+
const explicit = Array.isArray(codex.deployments), native = explicit ? codex.deployments.length > 0 && codex.deployments.every(item => item.source === "github") : codex.source === "github";
|
|
137
|
+
if (targets.has("codex")) try {
|
|
138
|
+
if (codex.enabled && codex.auto_sync === false) setup.codex = "manual_sync";
|
|
139
|
+
else if (codex.enabled && compiledCodex.defaultUnavailable && !native) setup.codex = "default_unavailable";
|
|
140
|
+
else {
|
|
141
|
+
setup.codex = configureCodex({ ...options, ...(codex.enabled && (native || explicit && codex.deployments.length || codex.source?.startsWith("api_"))
|
|
142
|
+
? { baseUrl: `http://127.0.0.1:${corePort}/v1`, native, ...(native ? { nativeModels: compiledCodex.models } : {}), ...(!native ? { apiKey: identities().codex } : {}),
|
|
143
|
+
...(explicit || !native ? { model: compiledCodex.defaultModel || (!compiledCodex.defaultUnavailable ? codex.model : undefined) } : {}) } : { restore: true }) }).state;
|
|
144
|
+
if (codex.enabled && compiledCodex.defaultUnavailable && setup.codex === "configured") setup.codex = "default_unavailable";
|
|
145
|
+
}
|
|
146
|
+
} catch { setup.codex = "configuration_unavailable"; }
|
|
140
147
|
if (!settings.claude_private_keys || !["claude_app", "claude_code"].some(id => targets.has(id))) return;
|
|
141
148
|
let desktopManaged;
|
|
142
149
|
for (const id of ["claude_app", "claude_code"]) {
|
|
@@ -185,8 +192,8 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
185
192
|
save(next);await syncClients(CLIENT_IDS.filter(client => binding(client).source === id || binding(client).deployments?.some(model => model.source === id)));
|
|
186
193
|
}
|
|
187
194
|
}
|
|
188
|
-
function enqueue(work) { const job = serial.then(work);serial = job.catch(() => {});return job; }
|
|
189
|
-
const refreshApis = () => !closed && managed ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id)) : Promise.resolve();
|
|
195
|
+
function enqueue(work) { operations++;const job = serial.then(work).finally(() => { operations--; });serial = job.catch(() => {});return job; }
|
|
196
|
+
const refreshApis = () => !closed && managed && !preserveClientConfiguration?.() ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id)) : Promise.resolve();
|
|
190
197
|
async function change(input) {
|
|
191
198
|
if (closed) throw accessError("ccdx_connections_closed", 503);
|
|
192
199
|
if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "model", "auto_review_model", "auto_review_effort", "deployments", "default_model", "auto_sync"])) throw accessError("ccdx_connections_action_invalid");
|
|
@@ -309,6 +316,16 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
309
316
|
...legacy,
|
|
310
317
|
source: getSource,
|
|
311
318
|
connections: snapshot,
|
|
319
|
+
privateScopes: id => [...new Set(plan(id).models.map(model => model.source_id))].sort().map(source => [source, getSource(source).profileId(id === "codex" ? "responses" : "messages")]),
|
|
320
|
+
validateLocalKeys() {
|
|
321
|
+
if (managed && CLIENT_IDS.some(id => binding(id).enabled && plan(id).models.some(model => model.source_id.startsWith("api_") || id !== "codex" && settings.claude_private_keys))) keys = readClientGatewayKeys({ ...options, create: false });
|
|
322
|
+
},
|
|
323
|
+
exportPrivateState: () => {
|
|
324
|
+
const credentials = secrets.exportState?.(settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)) || [];
|
|
325
|
+
return { credentials, bytes: credentials.reduce((sum, [ref, key]) => sum + 2 * Buffer.byteLength(ref + key) + 64, 0) };
|
|
326
|
+
},
|
|
327
|
+
importPrivateState: state => secrets.importState?.(state?.credentials || [], settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)),
|
|
328
|
+
busy: () => operations > 0 || active.size > 0 || Boolean(syncFlight) || catalogRefresh.busy() || legacy.snapshot().m365.account_change_in_flight === true || legacy.snapshot().m365.state === "checking",
|
|
312
329
|
syncClients,
|
|
313
330
|
async manageConnections(input) {
|
|
314
331
|
if (!input) return snapshot();
|
package/src/dashboard/console.js
CHANGED
|
@@ -105,6 +105,10 @@
|
|
|
105
105
|
window.addEventListener("ccdx:providers", () => { syncSources();if (current === "codex") void loadSourceModels(); });
|
|
106
106
|
function applySettings(data) {
|
|
107
107
|
settings = data;
|
|
108
|
+
const nightly = data.nightly_update;
|
|
109
|
+
el("nightly-update").checked = nightly?.enabled === true;el("nightly-update").disabled = false;
|
|
110
|
+
el("nightly-rules").hidden = nightly?.enabled !== true;
|
|
111
|
+
label(el("nightly-state"), !nightly?.enabled ? "nightly_off" : nightly.effect === "next_start" ? "nightly_next_start" : `nightly_${nightly.phase || "watching"}`);
|
|
108
112
|
el("terminal-color-theme").value = data.color_theme || "green";
|
|
109
113
|
el("terminal-color-theme").disabled = settingsPending;
|
|
110
114
|
el("terminal-color-sample").dataset.terminalPalette = data.color_theme || "green";
|
|
@@ -181,7 +185,7 @@
|
|
|
181
185
|
syncAccountControls();
|
|
182
186
|
const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-enabled")];
|
|
183
187
|
controls.forEach(input => { input.disabled = true; });
|
|
184
|
-
const note = el(body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
|
|
188
|
+
const note = el(body.action === "nightly_update" ? "nightly-state" : body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
|
|
185
189
|
: body.action.startsWith("history_") ? "effect-history" : body.action === "prediction_fix" ? "prediction-note"
|
|
186
190
|
: body.operation === "switch" ? "source-control-note" : body.operation === "auto-review" ? "review-control-note"
|
|
187
191
|
: body.operation === "account" ? "m365-account-note" : "m365-control-note");
|
|
@@ -279,6 +283,7 @@
|
|
|
279
283
|
model: el("source-model").value, ...(settings?.providers?.codex_provider === provider ? {} : {
|
|
280
284
|
auto_review_model: el("source-review").value, auto_review_effort: el("source-review-effort").value || null }) } : {}) }, el("apply-source"));
|
|
281
285
|
});
|
|
286
|
+
el("nightly-update").addEventListener("change", () => void change({ action: "nightly_update", enabled: el("nightly-update").checked }, el("nightly-update")));
|
|
282
287
|
el("save-review").addEventListener("click", () => void change({ action: "provider", operation: "auto-review", provider: el("source-provider").value,
|
|
283
288
|
model: el("source-review").value, auto_review_effort: el("source-review-effort").value || null }, el("save-review")));
|
|
284
289
|
// Only the small in-memory status snapshot is read at this cadence. Catalogs
|
package/src/dashboard/flow.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
const label = (node, key, values = {}) => globalThis.ccdxLanguage.set(node, key, values);
|
|
7
7
|
const format = (key, values = {}) => globalThis.ccdxLanguage.format(key, values);
|
|
8
8
|
const nodes = { apps: new Map(), models: new Map() };
|
|
9
|
+
const detailRows = new Map();
|
|
9
10
|
let rows = [], total = null, omitted = 0, fresh = false, deadline = 0, expiry = null;
|
|
10
11
|
let selected = null, expanded = false, lastSignature = "", geometry = "", known = false;
|
|
11
12
|
let lastApps = [], lastModels = [];
|
|
@@ -27,6 +28,11 @@
|
|
|
27
28
|
function svg(tag, values) { const node = document.createElementNS(ns, tag);for (const [key, value] of Object.entries(values)) node.setAttribute(key, value);return node; }
|
|
28
29
|
const logo = el("status-icon")?.cloneNode(true);
|
|
29
30
|
if (logo) { logo.removeAttribute("id");logo.setAttribute("class", "flow-logo");el("flow-hub").prepend(logo); }
|
|
31
|
+
const halo = svg("svg", { class: "flow-halo", viewBox: "0 0 60 60", "aria-hidden": "true" });
|
|
32
|
+
halo.append(svg("circle", { class: "flow-halo-track", cx: 30, cy: 30, r: 28 }));
|
|
33
|
+
const orbit = svg("svg", { class: "flow-halo flow-halo-turn", viewBox: "0 0 60 60", "aria-hidden": "true" });
|
|
34
|
+
orbit.append(svg("circle", { cx: 30, cy: 30, r: 28 }));
|
|
35
|
+
el("flow-hub").append(halo, orbit);
|
|
30
36
|
|
|
31
37
|
function group(type) {
|
|
32
38
|
const map = new Map();
|
|
@@ -76,14 +82,18 @@
|
|
|
76
82
|
function details() {
|
|
77
83
|
label(el("flow-active-title"), fresh ? "flow_active_count" : "flow_last_count", { count: rows.filter(related).length });
|
|
78
84
|
if (!el("flow-active").open) return;
|
|
79
|
-
const body = el("flow-active-body"), records = rows.filter(related)
|
|
80
|
-
for (const row of records) {
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
}
|
|
85
|
-
|
|
85
|
+
const body = el("flow-active-body"), records = rows.filter(related), wanted = new Set();
|
|
86
|
+
for (const [index, row] of records.entries()) {
|
|
87
|
+
const id = row.request_id || JSON.stringify([row.application, row.provider, row.model, index]);wanted.add(id);
|
|
88
|
+
let tr = detailRows.get(id);
|
|
89
|
+
if (!tr) { tr = entry("tr");for (let i = 0; i < 6; i++) tr.append(entry("td"));detailRows.set(id, tr); }
|
|
90
|
+
const values = [appName(row.application), sourceName(row.provider), modelName(row.model), format(fresh ? status(row) : "flow_last_observed"), `${(row.elapsed_ms / 1000).toFixed(1)} s`, row.upstream_attempts.toLocaleString()];
|
|
91
|
+
values.forEach((value, i) => { if (tr.children[i].textContent !== value) tr.children[i].textContent = value; });
|
|
92
|
+
if (body.children[index] !== tr) body.insertBefore(tr, body.children[index] || null);
|
|
86
93
|
}
|
|
94
|
+
for (const [id, tr] of detailRows) if (!wanted.has(id)) { tr.remove();detailRows.delete(id); }
|
|
95
|
+
const kept = new Set(detailRows.values());
|
|
96
|
+
for (const tr of [...body.children]) if (!kept.has(tr)) tr.remove();
|
|
87
97
|
if (!records.length) { const tr = entry("tr"), td = entry("td");td.colSpan = 6;label(td, known ? "flow_no_active" : "flow_status_unknown");tr.append(td);body.append(tr); }
|
|
88
98
|
}
|
|
89
99
|
function render() {
|
package/src/dashboard/index.html
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
<script src="/refresh.js" defer></script>
|
|
12
12
|
<script src="/icons.js" defer></script>
|
|
13
13
|
<script src="/time.js" defer></script>
|
|
14
|
+
<script src="/view-boundary.js" defer></script>
|
|
14
15
|
<script src="/status.js" defer></script>
|
|
15
16
|
<script src="/activity.js" defer></script>
|
|
16
17
|
<script src="/flow.js" defer></script>
|
|
@@ -391,6 +392,11 @@
|
|
|
391
392
|
<section class="panel dashboard-section" id="version-updates" aria-labelledby="version-updates-title">
|
|
392
393
|
<div class="version-heading"><h2 id="version-updates-title" data-i18n="version_updates">VERSION & UPDATES</h2><button id="check-updates" type="button" data-i18n="check_updates">Check for updates</button></div>
|
|
393
394
|
<dl class="version-list"><div><dt data-i18n="current_version">Current version</dt><dd id="update-current-version">—</dd><dd id="update-current-date" class="hint">—</dd></div><div id="update-latest-row" hidden><dt data-i18n="available_update">Update available</dt><dd id="update-latest-version">—</dd><dd id="update-latest-date" class="hint">—</dd></div></dl>
|
|
395
|
+
<div class="nightly-update">
|
|
396
|
+
<div class="setting-row"><label for="nightly-update" data-i18n="nightly_update">Update overnight</label><input id="nightly-update" type="checkbox" role="switch" aria-describedby="nightly-risk" disabled><span id="nightly-state" class="hint" role="status"></span></div>
|
|
397
|
+
<p id="nightly-risk" class="hint" data-i18n="nightly_risk">Updates install a new version and restart CCDX. Continuing a conversation may be affected.</p>
|
|
398
|
+
<div id="nightly-rules" hidden><dl class="nightly-rules"><div><dt data-i18n="nightly_window">Update window</dt><dd data-i18n="nightly_window_value">00:00–04:00 · Local time</dd></div><div><dt data-i18n="nightly_when">When to update</dt><dd data-i18n="nightly_when_value">Idle for 10 minutes, after checks pass</dd></div><div><dt data-i18n="nightly_versions">Versions</dt><dd data-i18n="nightly_versions_value">Stable patches released at least 24 hours ago</dd></div><div><dt data-i18n="nightly_failure">If an update fails</dt><dd data-i18n="nightly_failure_value">Try restoring the previous version and pause this update</dd></div></dl></div>
|
|
399
|
+
</div>
|
|
394
400
|
<p id="update-state" class="hint" role="status" data-i18n="reading">READING</p>
|
|
395
401
|
<div id="update-command-row" class="update-command"><code id="update-command">ccdx update github</code><button type="button" id="copy-update" data-i18n="copy_command">Copy command</button></div>
|
|
396
402
|
<p class="hint" data-i18n="update_restart">Run in your terminal, then restart CCDX.</p>
|
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
"nightly_update": ["Update overnight", "夜间自动更新"],
|
|
4
|
+
"nightly_risk": ["Updates install a new version and restart CCDX. Continuing a conversation may be affected.", "开启后会自动安装新版并重启 CCDX,可能影响会话续接。"],
|
|
5
|
+
"nightly_window": ["Update window", "更新时间"],
|
|
6
|
+
"nightly_window_value": ["00:00–04:00 · Local time", "00:00–04:00 · 本机时间"],
|
|
7
|
+
"nightly_when": ["When to update", "执行条件"],
|
|
8
|
+
"nightly_when_value": ["Idle for 10 minutes, after checks pass", "持续空闲 10 分钟,且检查通过"],
|
|
9
|
+
"nightly_versions": ["Versions", "更新范围"],
|
|
10
|
+
"nightly_versions_value": ["Stable patches released at least 24 hours ago", "仅发布满 24 小时的稳定补丁版"],
|
|
11
|
+
"nightly_failure": ["If an update fails", "更新失败"],
|
|
12
|
+
"nightly_failure_value": ["Try restoring the previous version and pause this update", "尝试恢复原版,并暂停该版本"],
|
|
13
|
+
"nightly_off": ["Off by default", "默认关闭"],
|
|
14
|
+
"nightly_next_start": ["On · Starts next time you run CCDX", "已开启 · 下次启动 CCDX 生效"],
|
|
15
|
+
"nightly_watching": ["On · Waiting for an idle overnight window", "已开启 · 等待夜间空闲时段"],
|
|
16
|
+
"nightly_checking": ["Checking for updates", "正在检查更新"],
|
|
17
|
+
"nightly_preparing": ["Preparing an update; service stays available", "正在准备新版,当前服务继续运行"],
|
|
18
|
+
"nightly_deferred": ["Deferred until another idle window", "已延后,等待下个空闲时段"],
|
|
19
|
+
"nightly_switching": ["Switching versions", "正在切换版本"],
|
|
20
|
+
"nightly_updated": ["Update complete", "更新完成"],
|
|
21
|
+
"nightly_cancelled": ["Automatic update cancelled", "已取消自动更新"],
|
|
22
|
+
"nightly_paused": ["Update paused; check the terminal for details", "更新已暂停,请查看终端"],
|
|
23
|
+
"nightly_unavailable": ["Automatic update unavailable; service is unaffected", "自动更新不可用,服务不受影响"],
|
|
24
|
+
|
|
25
|
+
"view_unavailable": ["This area is unavailable.", "此区域暂时不可用。"],
|
|
26
|
+
"view_retry": ["Try again", "重试"],
|
|
3
27
|
"api_saving": ["Saving…", "保存中…"],
|
|
4
28
|
"api_reading": ["Reading…", "读取中…"],
|
|
5
29
|
"api_read_cancelled": ["Read cancelled. Saved metadata is kept.", "已取消读取,保留已存资料。"],
|
package/src/dashboard/ui.css
CHANGED
|
@@ -446,10 +446,18 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
446
446
|
.flow-note { position:absolute;top:calc(100% + 4px);left:9px;max-width:100%;margin:0;color:var(--muted);font-size:10px; }
|
|
447
447
|
.flow-source { position:absolute;bottom:calc(100% + 9px);left:9px;color:var(--muted);font-size:10px;white-space:nowrap; }
|
|
448
448
|
.flow-node[data-related="false"] { opacity:.5; }
|
|
449
|
-
#flow-hub { position:relative;display:flex;align-items:center;justify-content:center;width:
|
|
449
|
+
#flow-hub { position:relative;display:flex;align-items:center;justify-content:center;width:60px;height:60px;border:0;background:var(--surface);color:var(--text);padding:0;text-transform:none; }
|
|
450
450
|
#flow-hub b { position:absolute;top:calc(100% + 10px);left:50%;transform:translateX(-50%); }
|
|
451
451
|
#flow-hub:hover { color:var(--accent); }
|
|
452
452
|
.flow-logo { width:34px;height:34px;color:var(--accent); }
|
|
453
|
+
.flow-halo { position:absolute;inset:0;width:60px;height:60px;color:var(--accent);pointer-events:none; }
|
|
454
|
+
.flow-halo-track { fill:none;stroke:currentColor;stroke-width:1;opacity:.26; }
|
|
455
|
+
.flow-halo-turn { transform-origin:center;animation:flow-orbit 5s linear infinite;animation-play-state:paused;opacity:0;transition:opacity 180ms ease-out; }
|
|
456
|
+
.flow-halo-turn circle { fill:none;stroke:currentColor;stroke-width:1.15;stroke-linecap:round;stroke-dasharray:155.93 20; }
|
|
457
|
+
#request-flow[data-state="active"] .flow-halo-turn { animation-play-state:running;opacity:.9; }
|
|
458
|
+
#request-flow[data-state="unknown"] .flow-halo-track { opacity:.15; }
|
|
459
|
+
#request-flow[data-paused="true"] .flow-halo-turn { animation-play-state:paused; }
|
|
460
|
+
@keyframes flow-orbit { from { transform:rotate(-90deg); } to { transform:rotate(270deg); } }
|
|
453
461
|
.flow-caption { display:flex;align-items:center;flex-wrap:wrap;gap:10px 16px;min-height:30px;font-size:11px;color:var(--muted); }
|
|
454
462
|
.flow-caption button { padding:5px 9px; }
|
|
455
463
|
.flow-wire { fill:none;stroke:var(--border);stroke-width:1;stroke-linecap:round;stroke-linejoin:round; }
|
|
@@ -474,8 +482,9 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
474
482
|
.flow-network { grid-template-columns:minmax(80px,1fr) 48px minmax(100px,1fr);column-gap:12px; }
|
|
475
483
|
.flow-column-title,.flow-source,.flow-note { font-size:10px; }
|
|
476
484
|
.flow-logo { width:26px;height:26px; }
|
|
485
|
+
#flow-hub,.flow-halo { width:48px;height:48px; }
|
|
477
486
|
}
|
|
478
|
-
@media(prefers-reduced-motion:reduce) { .flow-packet,#request-flow[data-state="idle"] #flow-state::before { animation:none; } }
|
|
487
|
+
@media(prefers-reduced-motion:reduce) { .flow-packet,.flow-halo-turn,#request-flow[data-state="idle"] #flow-state::before { animation:none;transition:none; } }
|
|
479
488
|
|
|
480
489
|
/* Model capability and application binding controls share the existing palette. */
|
|
481
490
|
.client-segments { margin-bottom: 18px; }
|
|
@@ -512,3 +521,8 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
512
521
|
.binding-table td:last-child button { min-width: 88px; padding: 9px; }
|
|
513
522
|
.binding-table td[colspan] { grid-column: 1 / -1; }
|
|
514
523
|
}
|
|
524
|
+
|
|
525
|
+
.view-error { display:flex;align-items:center;gap:14px;flex-wrap:wrap;margin-top:18px;color:var(--bad);font-size:11px; }
|
|
526
|
+
|
|
527
|
+
.nightly-update { margin:26px 0; }.nightly-rules { display:grid;grid-template-columns:1fr 1fr;gap:20px 30px;margin:22px 0; }.nightly-rules dt { color:var(--muted);font-size:11px;margin-bottom:8px; }.nightly-rules dd { margin:0;font-size:12px;line-height:1.7; }
|
|
528
|
+
@media(max-width:640px) { .nightly-rules { grid-template-columns:1fr; } }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -18,8 +18,8 @@ const mib = (value) => finite(value) ? `${(Number(value) / 1048576).toFixed(1)}
|
|
|
18
18
|
const time = (value, options) => globalThis.ccdxTime?.format(value, options) ?? (value ? new Date(value).toLocaleTimeString() : "—");
|
|
19
19
|
const viewHelpers = { time, element, phrase, localize, text, finite, number, mib, tableRow, emptyTable, document, navigator: globalThis.navigator,
|
|
20
20
|
motionAllowed: () => !reducedMotion.matches && document.visibilityState === "visible" && element("usage-analytics").open && !element("usage-analytics").closest("[hidden]") };
|
|
21
|
-
const { render, renderProviders, renderFailures, renderContext } = globalThis.ccdxDashboardStatus.create(viewHelpers);
|
|
22
|
-
const usageView = globalThis.ccdxDashboardUsage.create(viewHelpers);
|
|
21
|
+
const { render, renderProviders, renderFailures, renderContext } = globalThis.ccdxViewBoundary.create("client-features", () => globalThis.ccdxDashboardStatus.create(viewHelpers), ["render", "renderProviders", "renderFailures", "renderContext"]);
|
|
22
|
+
const usageView = globalThis.ccdxViewBoundary.create("usage-analytics", () => globalThis.ccdxDashboardUsage.create(viewHelpers), ["applyUsage", "renderUsageState", "renderAnalytics", "renderUsageTable", "selectUsageDay", "usageValues", "setChartVisible", "revealChart", "stopMotion"]);
|
|
23
23
|
const { applyUsage, renderUsageState, renderAnalytics, renderUsageTable, selectUsageDay } = usageView;
|
|
24
24
|
const loadAuth = () => dashboardRefresh.refresh("auth", { force: true });
|
|
25
25
|
|
|
@@ -38,8 +38,8 @@ element("refresh").addEventListener("click", () => {
|
|
|
38
38
|
});
|
|
39
39
|
|
|
40
40
|
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
|
41
|
-
const animationView = globalThis.ccdxDashboardAnimation.create({ element, phrase, localize, text, reducedMotion,
|
|
42
|
-
getRefresh: () => dashboardRefresh, document });
|
|
41
|
+
const animationView = globalThis.ccdxViewBoundary.create("animation-settings", () => globalThis.ccdxDashboardAnimation.create({ element, phrase, localize, text, reducedMotion,
|
|
42
|
+
getRefresh: () => dashboardRefresh, document }), ["apply", "load", "save", "sync", "stop"]);
|
|
43
43
|
const { apply: applyAnimation, load: loadAnimation, save: saveAnimation, sync: syncAnimationPreview, stop: stopAnimationPreview } = animationView;
|
|
44
44
|
reducedMotion.addEventListener("change", () => { if (reducedMotion.matches) usageView.stopMotion(); });
|
|
45
45
|
document.addEventListener("visibilitychange", () => { if (document.visibilityState !== "visible") usageView.stopMotion(); });
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
// One optional view owns its failure and retry; the shell and other views keep running.
|
|
3
|
+
function create(rootId, factory, methods) {
|
|
4
|
+
let view, failure, notice;
|
|
5
|
+
const wrappers = new Map(), pending = new Map();
|
|
6
|
+
function failed() {
|
|
7
|
+
if (notice) return;
|
|
8
|
+
const root = document.getElementById(rootId);if (!root) return;
|
|
9
|
+
notice = document.createElement('div');notice.className = 'view-error';notice.setAttribute('role', 'alert');
|
|
10
|
+
const message = document.createElement('span'), retry = document.createElement('button');retry.type = 'button';
|
|
11
|
+
globalThis.ccdxLanguage.set(message, 'view_unavailable');globalThis.ccdxLanguage.set(retry, 'view_retry');
|
|
12
|
+
retry.addEventListener('click', () => {
|
|
13
|
+
failure = false;notice.remove();notice = null;
|
|
14
|
+
if (!initialize()) return;
|
|
15
|
+
const calls = [...pending];pending.clear();
|
|
16
|
+
for (const [name, args] of calls) invoke(name, args);
|
|
17
|
+
});
|
|
18
|
+
notice.append(message, retry);root.append(notice);
|
|
19
|
+
}
|
|
20
|
+
function initialize() {
|
|
21
|
+
if (view) return true;
|
|
22
|
+
try { view = factory();return true; } catch { failure = true;failed();return false; }
|
|
23
|
+
}
|
|
24
|
+
function invoke(name, args) {
|
|
25
|
+
if (failure && !['stop', 'stopMotion'].includes(name)) { pending.set(name, args);return; }
|
|
26
|
+
if (!initialize()) { pending.set(name, args);return; }
|
|
27
|
+
const fail = () => { pending.set(name, args);failure = true;failed(); };
|
|
28
|
+
try {
|
|
29
|
+
const value = view[name](...args);
|
|
30
|
+
return value?.then ? value.catch(fail) : value;
|
|
31
|
+
} catch { fail(); }
|
|
32
|
+
}
|
|
33
|
+
initialize();
|
|
34
|
+
return new Proxy({}, { get(_target, name) {
|
|
35
|
+
if (!methods.includes(name)) return view?.[name];
|
|
36
|
+
if (!wrappers.has(name)) wrappers.set(name, (...args) => invoke(name, args));
|
|
37
|
+
return wrappers.get(name);
|
|
38
|
+
} });
|
|
39
|
+
}
|
|
40
|
+
globalThis.ccdxViewBoundary = { create };
|
|
41
|
+
})();
|
package/src/dashboard-tools.mjs
CHANGED
|
@@ -7,6 +7,7 @@ export function createDashboardTools(options = {}) {
|
|
|
7
7
|
const accounts = options.accountTools || createAccountTools({ ...options, onChanged: options.credentialsChanged });
|
|
8
8
|
const local = options.localTools || createLocalTools(options);
|
|
9
9
|
return {
|
|
10
|
+
busy: () => accounts.busy?.() === true || local.busy?.() === true,
|
|
10
11
|
dispose() { accounts.dispose(); },
|
|
11
12
|
async handle(req, res, pathname, sendJson, sameOrigin) {
|
|
12
13
|
const account = pathname === "/_ccdx/ui/account";
|
package/src/dashboard.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { ADAPTER_VERSION } from "./running-adapter.mjs";
|
|
3
5
|
|
|
4
6
|
const ASSETS = new Map([
|
|
5
7
|
["/", ["./dashboard/index.html", "text/html; charset=utf-8"]],
|
|
@@ -11,6 +13,7 @@ const ASSETS = new Map([
|
|
|
11
13
|
["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
|
|
12
14
|
["/updates.js", ["./dashboard/updates.js", "text/javascript; charset=utf-8"]],
|
|
13
15
|
["/time.js", ["./dashboard/time.js", "text/javascript; charset=utf-8"]],
|
|
16
|
+
["/view-boundary.js", ["./dashboard/view-boundary.js", "text/javascript; charset=utf-8"]],
|
|
14
17
|
["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
|
|
15
18
|
["/activity.js", ["./dashboard/activity.js", "text/javascript; charset=utf-8"]],
|
|
16
19
|
["/flow.js", ["./dashboard/flow.js", "text/javascript; charset=utf-8"]],
|
|
@@ -20,6 +23,19 @@ const ASSETS = new Map([
|
|
|
20
23
|
["/tools.js", ["./dashboard/tools.js", "text/javascript; charset=utf-8"]],
|
|
21
24
|
["/connections.js", ["./dashboard/connections.js", "text/javascript; charset=utf-8"]],
|
|
22
25
|
]);
|
|
26
|
+
let bundle;
|
|
27
|
+
function assets() {
|
|
28
|
+
bundle ||= Promise.all([...ASSETS].map(async ([name, [file, type]]) => {
|
|
29
|
+
let body = await readFile(new URL(file, import.meta.url));
|
|
30
|
+
if (name === "/") body = Buffer.from(body.toString().replace(/(src|href)="(\/[a-z-]+\.(?:js|css))"/g, `$1="$2?v=${ADAPTER_VERSION}"`));
|
|
31
|
+
return [name, { body, type, etag: `"${createHash("sha256").update(body).digest("hex")}"` }];
|
|
32
|
+
})).then(async entries => {
|
|
33
|
+
const installed = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
|
|
34
|
+
if (installed.version !== ADAPTER_VERSION) throw new Error("Dashboard files changed; restart CCDX before loading the new dashboard");
|
|
35
|
+
return new Map(entries);
|
|
36
|
+
}).catch(error => { bundle = null;throw error; });
|
|
37
|
+
return bundle;
|
|
38
|
+
}
|
|
23
39
|
|
|
24
40
|
export async function serveDashboard(req, res, pathname) {
|
|
25
41
|
if (!isLoopbackAddress(req.socket?.remoteAddress)
|
|
@@ -30,15 +46,20 @@ export async function serveDashboard(req, res, pathname) {
|
|
|
30
46
|
return;
|
|
31
47
|
}
|
|
32
48
|
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
49
|
+
const version = new URL(req.url || pathname, "http://localhost").searchParams.get("v");
|
|
50
|
+
if (version && version !== ADAPTER_VERSION) {
|
|
51
|
+
res.writeHead(409, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });res.end("Dashboard version changed. Reload this page.");return;
|
|
52
|
+
}
|
|
53
|
+
const { body, type: contentType, etag } = (await assets()).get(pathname);
|
|
54
|
+
const unchanged = pathname !== "/" && String(req.headers?.["if-none-match"] || "").split(/\s*,\s*/).includes(etag);
|
|
55
|
+
res.writeHead(unchanged ? 304 : 200, {
|
|
36
56
|
"Content-Type": contentType,
|
|
37
|
-
"Cache-Control": "no-store",
|
|
57
|
+
"Cache-Control": pathname === "/" ? "no-store" : "no-cache",
|
|
58
|
+
...(pathname === "/" ? {} : { ETag: etag }),
|
|
38
59
|
"Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
|
|
39
60
|
"X-Content-Type-Options": "nosniff",
|
|
40
61
|
"X-Frame-Options": "DENY",
|
|
41
62
|
"Referrer-Policy": "no-referrer",
|
|
42
63
|
});
|
|
43
|
-
res.end(req.method === "HEAD" ? undefined : body);
|
|
64
|
+
res.end(unchanged || req.method === "HEAD" ? undefined : body);
|
|
44
65
|
}
|
package/src/image-mcp.mjs
CHANGED
|
@@ -321,5 +321,8 @@ export function createImageMcpHandler({
|
|
|
321
321
|
};
|
|
322
322
|
// Status never reads credentials, loads image guidance, or probes a provider.
|
|
323
323
|
handler.stats = () => ({ ...metrics, active, max_concurrent: maxConcurrent });
|
|
324
|
+
handler.exportState = () => { if (active) throw new Error("Image requests are active");return imageReferences.exportState(); };
|
|
325
|
+
handler.importState = state => imageReferences.importState(state);
|
|
326
|
+
handler.referenceBytes = () => imageReferences.stats().bytes;
|
|
324
327
|
return handler;
|
|
325
328
|
}
|
package/src/image-references.mjs
CHANGED
|
@@ -36,6 +36,15 @@ export function createImageReferenceStore({ maxBytes = 64 * 1024 * 1024 } = {})
|
|
|
36
36
|
return JSON.parse(value);
|
|
37
37
|
},
|
|
38
38
|
clear() { cache.clear(); },
|
|
39
|
+
exportState() { return cache.exportEntries(); },
|
|
40
|
+
importState(values) {
|
|
41
|
+
if (!Array.isArray(values) || values.some(pair => !Array.isArray(pair) || !/^[a-f0-9]{64}:ccdx_img_[0-9a-f-]{36}$/.test(pair[0]) || typeof pair[1] !== "string")) throw new Error("Invalid image-reference handoff");
|
|
42
|
+
for (const [, value] of values) {
|
|
43
|
+
const item = JSON.parse(value);
|
|
44
|
+
if (typeof item.image !== "string" || !/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(item.image)) throw new Error("Invalid image-reference handoff");
|
|
45
|
+
}
|
|
46
|
+
cache.importEntries(values);
|
|
47
|
+
},
|
|
39
48
|
stats() { return cache.stats(); },
|
|
40
49
|
};
|
|
41
50
|
}
|
package/src/local-tools.mjs
CHANGED
|
@@ -48,6 +48,6 @@ export function createLocalTools({ home = os.homedir(), env = process.env, host
|
|
|
48
48
|
const value = inspectNetwork({ env, platform });
|
|
49
49
|
return { source: "network_check", checked_at: new Date().toISOString(), summary: safe(formatPredictionEnvironment(value.summary)) };
|
|
50
50
|
}
|
|
51
|
-
return { snapshot, check, preview, repair, network, report: () => ({ version: localPackageVersion(),
|
|
51
|
+
return { snapshot, check, preview, repair, network, busy: () => Boolean(flight), report: () => ({ version: localPackageVersion(),
|
|
52
52
|
exported_at: new Date().toISOString(), scope: "local checks only; accounts and credentials omitted", ...snapshot() }) };
|
|
53
53
|
}
|
package/src/m365-settings.mjs
CHANGED
|
@@ -95,6 +95,11 @@ export function writeM365Binding(account, catalog, { expectedAccount, ...options
|
|
|
95
95
|
|
|
96
96
|
export function ensureM365GatewayKey(options = {}) {
|
|
97
97
|
const file = m365Paths(options).gateway;
|
|
98
|
+
if (options.create === false) {
|
|
99
|
+
const saved = readM365Json(file);
|
|
100
|
+
if (!/^ccdx_m365_[a-f0-9]{64}$/.test(saved?.key || "")) throw Object.assign(new Error("Saved M365 gateway key is unavailable"), { code: "m365_gateway_key_invalid" });
|
|
101
|
+
return saved.key;
|
|
102
|
+
}
|
|
98
103
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
99
104
|
return withFileLockSync(`${file}.lock`, () => {
|
|
100
105
|
const saved = readM365Json(file);
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { inspectPackageUpdateEnvironment } from './package-update.mjs';
|
|
7
|
+
import { downloadRelease, createNpmReleaseFetch, protectInstallation, stableVersion, writePrivateLaunchers, privateUnixLauncher } from './release-install.mjs';
|
|
8
|
+
import { inspectWindowsCommand } from './windows-command.mjs';
|
|
9
|
+
import { isVersionGreater } from './version.mjs';
|
|
10
|
+
import { readBoundedResponseText } from './upstream-body.mjs';
|
|
11
|
+
import { readBoundedFileSync } from './bounded-file.mjs';
|
|
12
|
+
|
|
13
|
+
const run = promisify(execFile);
|
|
14
|
+
export const NIGHTLY_IDLE_MS = 10 * 60 * 1000;
|
|
15
|
+
export function nightlyWindow(now) { return now.getHours() < 4; }
|
|
16
|
+
export function nightlyDay(now) { return `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`; }
|
|
17
|
+
export function eligiblePatch(current, release, now = Date.now()) {
|
|
18
|
+
const version = stableVersion(release?.version), before = stableVersion(current), published = Date.parse(release?.published_at);
|
|
19
|
+
return Boolean(before && version && isVersionGreater(version, before) && version.split('.').slice(0,2).join('.') === before.split('.').slice(0,2).join('.')
|
|
20
|
+
&& Number.isFinite(published) && now - published >= 24 * 60 * 60 * 1000);
|
|
21
|
+
}
|
|
22
|
+
export function installedUpdateEnvironment(options = {}) {
|
|
23
|
+
const environment = inspectPackageUpdateEnvironment(options);
|
|
24
|
+
if (environment.state !== 'matched') throw new Error('installation_not_owned');
|
|
25
|
+
fs.accessSync(path.dirname(environment.target), fs.constants.W_OK);
|
|
26
|
+
const windows = (options.platform || process.platform) === 'win32';
|
|
27
|
+
const cli = windows ? path.win32.join(path.win32.dirname(environment.npm), 'node_modules/npm/bin/npm-cli.js') : fs.realpathSync(environment.npm);
|
|
28
|
+
if (!fs.statSync(cli).isFile()) throw new Error('npm_unavailable');
|
|
29
|
+
if (windows) {
|
|
30
|
+
if (inspectWindowsCommand({ packageRoot: environment.target }).status !== 'ready') throw new Error('command_not_owned');
|
|
31
|
+
} else {
|
|
32
|
+
const privateInstall = options.env?.CCDX_PRIVATE_INSTALL_PREFIX || process.env.CCDX_PRIVATE_INSTALL_PREFIX;
|
|
33
|
+
for (const name of ['ccdx','codex-copilot-dx']) {
|
|
34
|
+
const file = path.join(environment.prefix,'bin',name);
|
|
35
|
+
if (privateInstall && path.resolve(privateInstall) === path.resolve(environment.prefix)) {
|
|
36
|
+
if (readBoundedFileSync(file,{encoding:'utf8',maxBytes:16384}) !== privateUnixLauncher({...environment,name})) throw new Error('command_not_owned');
|
|
37
|
+
} else if (fs.realpathSync(file) !== fs.realpathSync(path.join(environment.target,'bin',name === 'ccdx' ? 'cli.mjs' : 'codex-copilot-dx.mjs'))) throw new Error('command_not_owned');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { ...environment, npmCli: cli };
|
|
41
|
+
}
|
|
42
|
+
export async function lookupNightlyRelease(fetchImpl, { signal } = {}) {
|
|
43
|
+
const response = await fetchImpl('https://api.github.com/repos/DaleXiao/codex-copilot-dx/releases/latest', {
|
|
44
|
+
signal: AbortSignal.any([signal || new AbortController().signal, AbortSignal.timeout(10000)]), redirect:'error',
|
|
45
|
+
headers:{Accept:'application/vnd.github+json','User-Agent':'codex-copilot-dx'},
|
|
46
|
+
});
|
|
47
|
+
if (!response.ok) { await response.body?.cancel();throw new Error('release_unavailable'); }
|
|
48
|
+
const value = JSON.parse(await readBoundedResponseText(response,{maxBytes:128*1024,signal,label:'Release metadata'}));
|
|
49
|
+
const version = stableVersion(value.tag_name);
|
|
50
|
+
if (!version || value.draft !== false || value.prerelease !== false || !Number.isFinite(Date.parse(value.published_at))) throw new Error('release_invalid');
|
|
51
|
+
return {version,published_at:value.published_at};
|
|
52
|
+
}
|
|
53
|
+
export async function verifyNightlyRuntime(target, version, { signal, brokerRequired = false } = {}) {
|
|
54
|
+
const program = `const {createRequire}=require('node:module');const r=createRequire(${JSON.stringify(path.join(target,'package.json'))});const p=r('./package.json');if(p.name!=='codex-copilot-dx'||p.version!==${JSON.stringify(version)})throw Error('version');r('sharp')({create:{width:1,height:1,channels:3,background:'white'}}).png().toBuffer().then(()=>{${brokerRequired?"if(!r('@azure/msal-node-runtime').msalNodeRuntime)throw Error('broker');":''}}).catch(()=>process.exitCode=1);`;
|
|
55
|
+
await run(process.execPath,['-e',program],{signal,timeout:30000,maxBuffer:65536,windowsHide:true});
|
|
56
|
+
const {stdout}=await run(process.execPath,[path.join(target,'bin/cli.mjs'),'version'],{signal,timeout:15000,maxBuffer:65536,windowsHide:true});
|
|
57
|
+
if (!stdout.includes(`ccdx v${version} `)) throw new Error('command_version_invalid');
|
|
58
|
+
}
|
|
59
|
+
export function nightlyRuntimeRoot({home=os.homedir()}={}) { return path.join(home,'.local/share/codex-copilot-dx/runtime'); }
|
|
60
|
+
export async function prepareNightlyRelease(release, { environment, root=nightlyRuntimeRoot(), env=process.env, signal,
|
|
61
|
+
fetchImpl=createNpmReleaseFetch(environment.npmCli,{env}), execute=run, verify=verifyNightlyRuntime }={}) {
|
|
62
|
+
const version=stableVersion(release?.version);if(!version)throw new Error('release_invalid');
|
|
63
|
+
fs.mkdirSync(root,{recursive:true,mode:0o700});const directory=fs.mkdtempSync(path.join(root,'candidate-'));
|
|
64
|
+
const target=path.join(directory,...(process.platform==='win32'?[]:['lib']),'node_modules/codex-copilot-dx');
|
|
65
|
+
const brokerRequired=fs.existsSync(path.join(environment.target,'node_modules/@azure/msal-node-runtime'));
|
|
66
|
+
try {
|
|
67
|
+
const artifact=await downloadRelease(version,{directory,fetchImpl,signal});
|
|
68
|
+
const args=['install','--global','--ignore-scripts','--no-audit','--no-fund'];
|
|
69
|
+
await execute(process.execPath,[environment.npmCli,...args,'--prefix',directory,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
|
|
70
|
+
await verify(target,version,{signal,brokerRequired});
|
|
71
|
+
return { version, target, directory,
|
|
72
|
+
async install() {
|
|
73
|
+
signal?.throwIfAborted();const transaction=protectInstallation(environment);
|
|
74
|
+
try {
|
|
75
|
+
await execute(process.execPath,[environment.npmCli,...args,'--prefix',environment.prefix,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
|
|
76
|
+
await verify(environment.target,version,{signal,brokerRequired});
|
|
77
|
+
const normalize=value=>process.platform==='win32'?path.resolve(value).toLowerCase():path.resolve(value);
|
|
78
|
+
if(env.CCDX_PRIVATE_INSTALL_PREFIX&&normalize(env.CCDX_PRIVATE_INSTALL_PREFIX)===normalize(environment.prefix))await writePrivateLaunchers(environment);
|
|
79
|
+
if (process.platform==='win32') {
|
|
80
|
+
const {inspectWindowsCommand}=await import(new URL('./windows-command.mjs',import.meta.url));
|
|
81
|
+
if(inspectWindowsCommand({packageRoot:environment.target,repair:true}).status!=='ready')throw new Error('command_setup_failed');
|
|
82
|
+
}
|
|
83
|
+
return transaction;
|
|
84
|
+
}catch(error){transaction.rollback();throw error;}
|
|
85
|
+
},
|
|
86
|
+
cleanup(){fs.rmSync(directory,{recursive:true,force:true});},
|
|
87
|
+
};
|
|
88
|
+
}catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
|
|
89
|
+
}
|
|
90
|
+
// The foreground supervisor keeps its workers on immutable package trees, so a
|
|
91
|
+
// global npm install cannot replace modules under an in-flight request.
|
|
92
|
+
export function retainCurrentRuntime(environment,{root=nightlyRuntimeRoot(),copy=fs.cpSync}={}) {
|
|
93
|
+
fs.mkdirSync(root,{recursive:true,mode:0o700});const directory=fs.mkdtempSync(path.join(root,'current-'));
|
|
94
|
+
const target=path.join(directory,'codex-copilot-dx');
|
|
95
|
+
try {copy(environment.package_root,target,{recursive:true,verbatimSymlinks:true,mode:fs.constants.COPYFILE_FICLONE});return {target,directory,cleanup(){fs.rmSync(directory,{recursive:true,force:true});}};}
|
|
96
|
+
catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function readNightlyState(file) {
|
|
100
|
+
try {
|
|
101
|
+
const value=JSON.parse(readBoundedFileSync(file,{encoding:'utf8',maxBytes:8192}));
|
|
102
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).some(key=>!['attempted_day','paused_version'].includes(key))
|
|
103
|
+
||value.attempted_day!==null&&!/^\d{4}-\d{1,2}-\d{1,2}$/.test(value.attempted_day||'')
|
|
104
|
+
||value.paused_version!==null&&!stableVersion(value.paused_version))throw new Error('invalid_update_state');
|
|
105
|
+
return value;
|
|
106
|
+
}catch(error){if(error.code==='ENOENT')return {attempted_day:null,paused_version:null};throw error;}
|
|
107
|
+
}
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.js"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.js"]);
|
|
2
2
|
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
@@ -11,29 +11,43 @@ export function isOptionalRoute(method, pathname) {
|
|
|
11
11
|
export function createOptionalRoutes(options = {}) {
|
|
12
12
|
let imageMcpHandler = options.imageMcpHandler || null;
|
|
13
13
|
let tools = null;
|
|
14
|
+
let pending = 0;
|
|
14
15
|
return {
|
|
15
16
|
dispose() { tools?.dispose(); },
|
|
17
|
+
busy: () => pending > 0 || tools?.busy?.() === true,
|
|
18
|
+
exportState() { const images = imageMcpHandler?.exportState?.() || [];return { images, bytes: (imageMcpHandler?.referenceBytes?.() || 0) + images.length * 64 }; },
|
|
19
|
+
async importState(state) {
|
|
20
|
+
if (!state || !Array.isArray(state.images)) throw new Error("Invalid optional-service handoff");
|
|
21
|
+
if (state.images.length) {
|
|
22
|
+
const { createImageMcpHandler } = await import("./image-mcp.mjs");
|
|
23
|
+
imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
|
|
24
|
+
imageMcpHandler.importState(state.images);
|
|
25
|
+
}
|
|
26
|
+
},
|
|
16
27
|
imageStats() { return imageMcpHandler?.stats?.(); },
|
|
17
28
|
async handle(req, res, pathname) {
|
|
29
|
+
pending++;
|
|
30
|
+
try {
|
|
18
31
|
if (DASHBOARD_API_PATHS.has(pathname)) {
|
|
19
32
|
const { handleDashboardApi } = await import("./dashboard-api.mjs");
|
|
20
33
|
if (["/_ccdx/ui/account", "/_ccdx/ui/checks"].includes(pathname)) {
|
|
21
34
|
const { createDashboardTools } = await import("./dashboard-tools.mjs");
|
|
22
35
|
tools ||= createDashboardTools(options.dashboardOptions);
|
|
23
36
|
}
|
|
24
|
-
return handleDashboardApi(req, res, pathname, { ...options.dashboardOptions, tools });
|
|
37
|
+
return await handleDashboardApi(req, res, pathname, { ...options.dashboardOptions, tools });
|
|
25
38
|
}
|
|
26
39
|
if ((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname)) {
|
|
27
40
|
const { serveDashboard } = await import("./dashboard.mjs");
|
|
28
|
-
return serveDashboard(req, res, pathname);
|
|
41
|
+
return await serveDashboard(req, res, pathname);
|
|
29
42
|
}
|
|
30
43
|
if (pathname === "/mcp/image") {
|
|
31
|
-
if (imageMcpHandler) return imageMcpHandler(req, res);
|
|
32
|
-
return import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
|
|
44
|
+
if (imageMcpHandler) return await imageMcpHandler(req, res);
|
|
45
|
+
return await import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
|
|
33
46
|
imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
|
|
34
47
|
return imageMcpHandler(req, res);
|
|
35
48
|
});
|
|
36
49
|
}
|
|
50
|
+
} finally { pending--; }
|
|
37
51
|
},
|
|
38
52
|
};
|
|
39
53
|
}
|