codex-copilot-dx 1.2.2 → 1.2.4
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 +4 -3
- package/docs/ARCHITECTURE.md +6 -0
- package/docs/README.md +2 -0
- package/docs/REFERENCE.md +24 -5
- package/package.json +1 -1
- package/src/adapter.mjs +2 -1
- package/src/cli-m365.mjs +27 -2
- package/src/cli-options.mjs +6 -5
- package/src/dashboard/console.js +50 -5
- package/src/dashboard/index.html +31 -9
- package/src/dashboard/language.js +47 -0
- package/src/dashboard/status.js +5 -6
- package/src/dashboard/ui.css +20 -4
- package/src/dashboard/ui.js +10 -9
- package/src/dashboard/updates.js +73 -0
- package/src/dashboard-api.mjs +21 -1
- package/src/dashboard-updates.mjs +71 -0
- package/src/dashboard.mjs +1 -0
- package/src/m365-settings.mjs +23 -1
- package/src/optional-routes.mjs +2 -2
- package/src/provider-management.mjs +3 -2
- package/src/provider-runtime.mjs +60 -5
- package/src/providers/m365-accounts.mjs +66 -0
- package/src/providers/m365-auth-helper.mjs +12 -10
- package/src/providers/m365-auth.mjs +13 -4
- package/src/providers/m365-conversation-accounts.mjs +42 -0
- package/src/providers/m365.mjs +19 -8
- package/src/service-control.mjs +5 -3
package/src/dashboard/ui.css
CHANGED
|
@@ -159,9 +159,6 @@ footer { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; color:
|
|
|
159
159
|
.sidebar nav a[aria-current="page"] { color: var(--accent); background: var(--selected-bg); border-left-color: var(--accent); }
|
|
160
160
|
.sidebar nav a:focus-visible, .sidebar-brand:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
|
161
161
|
.nav-group { color: var(--subtle); font-size: 10px; padding: 18px 12px 4px; text-transform: uppercase; letter-spacing: .08em; }
|
|
162
|
-
.sidebar-bottom { margin-top: auto; padding-top: 24px; }
|
|
163
|
-
.sidebar-bottom button { width: 100%; text-align: left; }
|
|
164
|
-
.sidebar-bottom p { color: var(--subtle); font-size: 11px; line-height: 1.7; }
|
|
165
162
|
.topbar, main, footer { grid-column: 2; min-width: 0; }
|
|
166
163
|
.topbar { min-height: 76px; gap: 14px; }
|
|
167
164
|
.brand { font-size: 12px; }
|
|
@@ -188,7 +185,7 @@ input[role="switch"]:focus-visible, input[type="number"]:focus-visible { outline
|
|
|
188
185
|
input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
189
186
|
#process-queues { overflow-wrap: anywhere; font-size: 11px; }
|
|
190
187
|
@media (max-width: 900px) { .shell { grid-template-columns: 170px minmax(0, 1fr); column-gap: 20px; padding: 0 20px; } .topbar .brand { display: none; } .topbar { justify-content: flex-end; } .setting-row { grid-template-columns: minmax(0, 1fr) 44px; } .setting-row .hint { grid-column: 1 / -1; } .overview { grid-template-columns: 1fr; } }
|
|
191
|
-
@media (max-width: 640px) { .shell { display: block; padding: 0 16px; } .sidebar { position: static; height: auto; padding: 20px 0 14px; border-right: 0; border-bottom: 1px solid var(--border); } .sidebar-brand { font-size: 20px; width: fit-content; } .sidebar-brand .brand-caption { margin-top: 4px; } .sidebar nav { display: flex; flex-direction: row; flex-wrap: wrap; gap: 4px; margin-top: 16px; } .sidebar nav a { padding: 9px 10px; font-size: 12px; border-left: 0; border-bottom: 2px solid transparent; } .sidebar nav a[aria-current="page"] { border-bottom-color: var(--accent); } .nav-group
|
|
188
|
+
@media (max-width: 640px) { .shell { display: block; padding: 0 16px; } .sidebar { position: static; height: auto; padding: 20px 0 14px; border-right: 0; border-bottom: 1px solid var(--border); } .sidebar-brand { font-size: 20px; width: fit-content; } .sidebar-brand .brand-caption { margin-top: 4px; } .sidebar nav { display: flex; flex-direction: row; flex-wrap: wrap; gap: 4px; margin-top: 16px; } .sidebar nav a { padding: 9px 10px; font-size: 12px; border-left: 0; border-bottom: 2px solid transparent; } .sidebar nav a[aria-current="page"] { border-bottom-color: var(--accent); } .nav-group { display: none; } .topbar { min-height: 62px; justify-content: flex-start; } .topbar-actions { justify-content: flex-start; gap: 9px; } .intro { padding: 24px 0 18px; } .panel, .lower { padding: 17px; } .section-actions > label { width: 100%; } .stats { gap: 12px; } }
|
|
192
189
|
|
|
193
190
|
/* Keep forms aligned with the existing dashboard controls. */
|
|
194
191
|
.dashboard-section + .client-overview { margin-top: 10px; }
|
|
@@ -234,6 +231,25 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
234
231
|
.appearance-select { width:100%; max-width:100%; min-width:0; height:36px; box-sizing:border-box; border-radius:2px; padding:0 10px; font-size:12px; }
|
|
235
232
|
.appearance-note { color:var(--subtle); margin:17px 0 0; font-size:12px; line-height:1.7; }
|
|
236
233
|
.appearance-animation { margin-top:22px; border-top:1px solid var(--border); padding-top:18px; }
|
|
234
|
+
.terminal-animation-toggle { border-bottom:0; }
|
|
235
|
+
.sidebar nav a { display:flex; align-items:center; gap:10px; }
|
|
236
|
+
.nav-icon { width:17px; height:17px; flex:none; fill:none; stroke:currentColor; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:round; }
|
|
237
|
+
#source-detail { display:flex; flex-wrap:wrap; gap:5px 22px; }
|
|
238
|
+
.version-heading, .install-command-heading { display:flex; align-items:center; justify-content:space-between; gap:14px; flex-wrap:wrap; }
|
|
239
|
+
.version-heading h2 { margin:0; }
|
|
240
|
+
.version-list { margin:18px 0 0; }
|
|
241
|
+
.version-list > div { display:grid; grid-template-columns:minmax(110px,1fr) auto minmax(150px,1fr); align-items:baseline; gap:16px; padding:14px 0; border-bottom:1px solid var(--border); }
|
|
242
|
+
.version-list dt { font-size:12px; }
|
|
243
|
+
.version-list dd { margin:0; }
|
|
244
|
+
.version-list dd:nth-child(2) { font-size:18px; font-weight:650; color:var(--strong); }
|
|
245
|
+
.version-list dd:last-child { text-align:right; }
|
|
246
|
+
.update-command { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px; padding:12px; margin-top:16px; background:var(--page); border:1px solid var(--border); }
|
|
247
|
+
.update-command code { overflow-wrap:anywhere; }
|
|
248
|
+
.update-install { margin-top:20px; padding-top:16px; border-top:1px solid var(--border); }
|
|
249
|
+
.update-install > summary { color:var(--heading); font-size:12px; }
|
|
250
|
+
.install-command-heading { margin-top:16px; }
|
|
251
|
+
.install-command { white-space:pre-wrap; overflow-wrap:anywhere; word-break:break-word; font-size:12px; line-height:1.75; padding:14px; background:var(--page); border:1px solid var(--border); }
|
|
252
|
+
@media(max-width:700px) { .version-list > div { grid-template-columns:1fr auto; gap:8px; } .version-list dd:last-child { grid-column:1/-1; text-align:left; } }
|
|
237
253
|
.appearance-animation > summary { color:var(--heading); font-size:12px; font-weight:700; }
|
|
238
254
|
.terminal-sample { --sample-bg:#0F151D; --sample-text:#DFE7F2; --sample-muted:#A2B0C2; --sample-line:#304054; --sample-logo:#A6F5A8; --sample-table:#DFE7F2; --sample-motion:#84E99E; padding:16px; margin-top:20px; border:1px solid var(--sample-line); border-radius:2px; background:var(--sample-bg); color:var(--sample-text); }
|
|
239
255
|
.terminal-sample[data-terminal-palette="klein"] { --sample-logo:#4C9FFF; --sample-table:#4C9FFF; --sample-motion:#4C9FFF; }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -362,15 +362,22 @@ for (const [key, ids] of [["auth", ["account-authorization"]], ["status", ["clie
|
|
|
362
362
|
}));
|
|
363
363
|
}
|
|
364
364
|
|
|
365
|
+
const updateView = globalThis.ccdxDashboardUpdates.create(viewHelpers);
|
|
365
366
|
const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
366
367
|
visible: () => document.visibilityState === "visible",
|
|
367
368
|
onState: ({ pendingKeys }) => {
|
|
368
|
-
//
|
|
369
|
-
const busy = pendingKeys.some(key => key !== "auth");
|
|
369
|
+
// Account and release reads must not block normal dashboard refreshes.
|
|
370
|
+
const busy = pendingKeys.some(key => key !== "auth" && key !== "updates");
|
|
370
371
|
element("refresh").disabled = busy;
|
|
371
372
|
element("refresh").setAttribute("aria-busy", String(busy));
|
|
372
373
|
},
|
|
373
374
|
resources: {
|
|
375
|
+
updates: {
|
|
376
|
+
visible: () => !element("version-updates").closest("[hidden]"),
|
|
377
|
+
load: ({ signal }) => readDashboard("/_ccdx/ui/updates", { signal, timeout: 20000, source: "release_status" }),
|
|
378
|
+
apply: updateView.render,
|
|
379
|
+
state: updateView.state,
|
|
380
|
+
},
|
|
374
381
|
status: {
|
|
375
382
|
visible: () => true,
|
|
376
383
|
load: async ({ signal }) => {
|
|
@@ -522,17 +529,11 @@ for (const [id, key] of [["account-authorization", "auth"], ["client-features",
|
|
|
522
529
|
}
|
|
523
530
|
|
|
524
531
|
element("save-animation").addEventListener("click", saveAnimation);
|
|
532
|
+
element("check-updates").addEventListener("click", () => dashboardRefresh.refresh("updates", { force: true }));
|
|
525
533
|
element("animation-settings").addEventListener("toggle", () => {
|
|
526
|
-
element("open-animation").setAttribute("aria-expanded", String(element("animation-settings").open));
|
|
527
534
|
if (element("animation-settings").open) loadAnimation();
|
|
528
535
|
syncAnimationPreview();
|
|
529
536
|
});
|
|
530
|
-
element("open-animation").addEventListener("click", () => {
|
|
531
|
-
const settings = element("animation-settings");
|
|
532
|
-
settings.open = true;
|
|
533
|
-
settings.scrollIntoView({ block: "center" });
|
|
534
|
-
settings.querySelector("summary").focus();
|
|
535
|
-
});
|
|
536
537
|
element("usage-analytics").addEventListener("toggle", () => {
|
|
537
538
|
if (element("usage-analytics").open && element("model-usage").open) dashboardRefresh.refresh("usage");
|
|
538
539
|
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const stable = value => typeof value === "string" && /^(0|[1-9]\d{0,14})\.(0|[1-9]\d{0,14})\.(0|[1-9]\d{0,14})$/.test(value) ? value : null;
|
|
3
|
+
function installationCommand(platform, version, latestVersion) {
|
|
4
|
+
const current = stable(version), latest = stable(latestVersion);
|
|
5
|
+
if (latest && (!current || ([0, 1, 2].map(index => Number(latest.split(".")[index]) - Number(current.split(".")[index])).find(value => value !== 0) || 0) > 0)) version = latest;
|
|
6
|
+
if (!stable(version)) return "";
|
|
7
|
+
const base = `https://github.com/DaleXiao/codex-copilot-dx/releases/download/v${version}`;
|
|
8
|
+
if (platform === "windows") return `$ccdxInstallDir = Join-Path ([IO.Path]::GetTempPath()) ("ccdx-install-" + [guid]::NewGuid().ToString("N"))
|
|
9
|
+
New-Item -ItemType Directory -Path $ccdxInstallDir -ErrorAction Stop | Out-Null
|
|
10
|
+
try {
|
|
11
|
+
$ccdxInstaller = Join-Path $ccdxInstallDir "install.ps1"
|
|
12
|
+
Invoke-WebRequest -UseBasicParsing -Uri "${base}/install.ps1" -OutFile $ccdxInstaller -TimeoutSec 300 -ErrorAction Stop
|
|
13
|
+
& $ccdxInstaller
|
|
14
|
+
} finally {
|
|
15
|
+
Remove-Item -LiteralPath $ccdxInstallDir -Recurse -Force
|
|
16
|
+
}`;
|
|
17
|
+
return `(
|
|
18
|
+
set -e
|
|
19
|
+
ccdx_install_dir="$(mktemp -d)"
|
|
20
|
+
trap 'rm -rf "$ccdx_install_dir"' EXIT
|
|
21
|
+
curl --fail --location --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 300 \\
|
|
22
|
+
${base}/install.sh \\
|
|
23
|
+
--output "$ccdx_install_dir/install.sh"
|
|
24
|
+
sh "$ccdx_install_dir/install.sh"
|
|
25
|
+
)`;
|
|
26
|
+
}
|
|
27
|
+
function create({ element, localize, navigator }) {
|
|
28
|
+
let snapshot = null, platform = "macos";
|
|
29
|
+
const date = value => typeof value === "string" && Number.isFinite(Date.parse(value)) ? value.slice(0, 10) : null;
|
|
30
|
+
function install() {
|
|
31
|
+
const command = installationCommand(platform, snapshot?.current?.version, snapshot?.latest?.version);
|
|
32
|
+
element("install-command").textContent = command;
|
|
33
|
+
element("copy-install").disabled = !command;
|
|
34
|
+
element("install-shell").textContent = platform === "windows" ? "Windows · PowerShell" : "macOS · Terminal";
|
|
35
|
+
element("install-windows-policy").hidden = platform !== "windows";
|
|
36
|
+
}
|
|
37
|
+
function render(data) {
|
|
38
|
+
snapshot = data;
|
|
39
|
+
const checked = data.status === "checked", latest = stable(data.latest?.version), current = stable(data.current?.version);
|
|
40
|
+
element("update-current-version").textContent = current ? `v${current}` : "—";
|
|
41
|
+
const currentDate = date(data.current?.published_at), latestDate = date(data.latest?.published_at);
|
|
42
|
+
localize(element("update-current-date"), currentDate ? "released_date" : "release_date_unknown", { date: currentDate });
|
|
43
|
+
element("update-latest-row").hidden = !latest || checked && !data.update_available;
|
|
44
|
+
localize(element("update-latest-row").querySelector("dt"), checked ? "available_update" : "last_known_version");
|
|
45
|
+
element("update-latest-version").textContent = latest ? `v${latest}` : "—";
|
|
46
|
+
localize(element("update-latest-date"), latestDate ? "released_date" : "release_date_unknown", { date: latestDate });
|
|
47
|
+
localize(element("update-state"), checked ? data.update_available ? "new_version_available" : "already_latest" : data.status === "rate_limited" ? "update_rate_limited" : "update_check_failed");
|
|
48
|
+
element("update-command-row").hidden = checked && !data.update_available;
|
|
49
|
+
const time = typeof data.checked_at === "string" && Number.isFinite(Date.parse(data.checked_at)) ? new Date(data.checked_at).toLocaleString() : "—";
|
|
50
|
+
localize(element("update-checked"), checked ? "update_checked_time" : "update_attempted_time", { time });
|
|
51
|
+
install();
|
|
52
|
+
}
|
|
53
|
+
function state(value) {
|
|
54
|
+
element("check-updates").disabled = Boolean(value.pending);
|
|
55
|
+
localize(element("check-updates"), value.pending ? "checking_updates" : "check_updates");
|
|
56
|
+
if (value.error) {
|
|
57
|
+
render({ ...snapshot, status: "unavailable", checked_at: new Date().toISOString(), current: snapshot?.current || { version: stable(element("version").textContent.replace(/^v/, "")) } });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
for (const button of document.querySelectorAll("[data-install-platform]")) button.addEventListener("click", () => {
|
|
61
|
+
platform = button.dataset.installPlatform;
|
|
62
|
+
for (const item of document.querySelectorAll("[data-install-platform]")) item.setAttribute("aria-pressed", String(item === button));
|
|
63
|
+
install();
|
|
64
|
+
});
|
|
65
|
+
for (const [button, target] of [["copy-update", "update-command"], ["copy-install", "install-command"]]) element(button).addEventListener("click", async () => {
|
|
66
|
+
try { await navigator.clipboard.writeText(element(target).textContent);localize(element("update-copy-note"), "copied"); }
|
|
67
|
+
catch { localize(element("update-copy-note"), "update_copy_unavailable"); }
|
|
68
|
+
});
|
|
69
|
+
element("copy-install").disabled = true;
|
|
70
|
+
return { render, state };
|
|
71
|
+
}
|
|
72
|
+
globalThis.ccdxDashboardUpdates = { create, installationCommand };
|
|
73
|
+
})();
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -142,6 +142,8 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
142
142
|
authStatusFn = () => authStatus({ home }),
|
|
143
143
|
providerCatalogFn,
|
|
144
144
|
providerStateFn,
|
|
145
|
+
providerAccountsFn,
|
|
146
|
+
updateStatusFn,
|
|
145
147
|
serviceControl,
|
|
146
148
|
applyAnimation,
|
|
147
149
|
} = {}) {
|
|
@@ -162,6 +164,23 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
162
164
|
return;
|
|
163
165
|
}
|
|
164
166
|
|
|
167
|
+
if (pathname === "/_ccdx/ui/updates") {
|
|
168
|
+
if (req.method !== "GET") { sendJson(res, 405, { error: "Use GET" });return; }
|
|
169
|
+
const { dashboardUpdateStatus } = await import("./dashboard-updates.mjs");
|
|
170
|
+
try { sendJson(res, 200, await (updateStatusFn || dashboardUpdateStatus)()); }
|
|
171
|
+
catch { sendJson(res, 503, { error: "Could not check releases" }); }
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (pathname === "/_ccdx/ui/m365/accounts" && req.method === "GET") {
|
|
176
|
+
if (!providerAccountsFn) { sendJson(res, 503, { error: "Account selection requires the updated running service" });return; }
|
|
177
|
+
try {
|
|
178
|
+
const result = await providerAccountsFn();
|
|
179
|
+
sendJson(res, 200, { accounts: result.accounts.map(value => ({ id: value.id, login: safeText(value.login, 320), tenant: safeText(value.tenant, 128), selected: value.selected === true, current_windows: value.current_windows === true })) });
|
|
180
|
+
} catch (error) { sendJson(res, error.statusCode || 503, { error: "Could not read company accounts", code: /^m365_[a-z_]+$/.test(error.code || "") ? error.code : "m365_accounts_unavailable" }); }
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
165
184
|
if (pathname === "/_ccdx/ui/settings") {
|
|
166
185
|
if (!serviceControl) { sendJson(res, 503, { error: "Settings require the running service; restart the updated CCDX" });return; }
|
|
167
186
|
if (req.method === "GET") {
|
|
@@ -177,7 +196,8 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
177
196
|
abort.clearTimeout();const data = await serviceControl.action(input);
|
|
178
197
|
if (!res.destroyed && !res.writableEnded) sendJson(res, 200, data);
|
|
179
198
|
} catch (error) {
|
|
180
|
-
sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300)
|
|
199
|
+
sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300),
|
|
200
|
+
...(/^m365_[a-z_]+$/.test(error.code || "") ? { code: error.code } : {}) });
|
|
181
201
|
} finally { abort.cleanup(); }
|
|
182
202
|
return;
|
|
183
203
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { createNpmReleaseFetch, stableVersion } from "./release-install.mjs";
|
|
6
|
+
import { isVersionGreater } from "./version.mjs";
|
|
7
|
+
import { ADAPTER_VERSION } from "./running-adapter.mjs";
|
|
8
|
+
import { readBoundedResponseText } from "./upstream-body.mjs";
|
|
9
|
+
|
|
10
|
+
const API = "https://api.github.com/repos/DaleXiao/codex-copilot-dx/releases";
|
|
11
|
+
const run = promisify(execFile);
|
|
12
|
+
|
|
13
|
+
async function releaseFetch() {
|
|
14
|
+
const env = process.env, windows = process.platform === "win32", paths = windows ? path.win32 : path;
|
|
15
|
+
const search = Object.entries(env).find(([key]) => key.toLowerCase() === "path")?.[1] || "";
|
|
16
|
+
const npm = search.split(windows ? ";" : ":").filter(Boolean)
|
|
17
|
+
.map(directory => paths.join(directory.replace(/^"|"$/g, ""), windows ? "npm.cmd" : "npm"))
|
|
18
|
+
.find(file => { try { return fs.statSync(file).isFile(); } catch { return false; } });
|
|
19
|
+
if (!npm) throw new Error("npm unavailable");
|
|
20
|
+
const cli = windows ? paths.join(paths.dirname(npm), "node_modules", "npm", "bin", "npm-cli.js") : fs.realpathSync(npm);
|
|
21
|
+
// Read only the installer's named network settings, off the service event loop.
|
|
22
|
+
const { stdout } = await run(process.execPath, [cli, "config", "get", "--global", "https-proxy", "proxy", "noproxy", "cafile", "strict-ssl", "offline"],
|
|
23
|
+
{ env, encoding: "utf8", timeout: 5000, maxBuffer: 128 * 1024, windowsHide: true });
|
|
24
|
+
return createNpmReleaseFetch(cli, { env, exec: () => stdout });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createDashboardUpdateStatus({ currentVersion = ADAPTER_VERSION, fetchFactory = releaseFetch, now = Date.now, timeoutMs = 4000 } = {}) {
|
|
28
|
+
let pending, snapshot, attemptedAt = -Infinity, currentDate = null;
|
|
29
|
+
const current = () => ({ version: currentVersion, published_at: currentDate });
|
|
30
|
+
async function metadata(fetchImpl, suffix, expectedVersion) {
|
|
31
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
32
|
+
const response = await fetchImpl(`${API}/${suffix}`, { signal, redirect: "error",
|
|
33
|
+
headers: { Accept: "application/vnd.github+json", "User-Agent": "codex-copilot-dx", "X-GitHub-Api-Version": "2022-11-28" } });
|
|
34
|
+
if (!response.ok) {
|
|
35
|
+
await response.body?.cancel();
|
|
36
|
+
throw Object.assign(new Error("Release metadata unavailable"), { code: [403, 429].includes(response.status) ? "rate_limited" : "unavailable" });
|
|
37
|
+
}
|
|
38
|
+
const value = JSON.parse(await readBoundedResponseText(response, { maxBytes: 128 * 1024, signal, label: "Release metadata" }));
|
|
39
|
+
const version = stableVersion(value.tag_name);
|
|
40
|
+
if (!version || value.draft !== false || value.prerelease !== false || expectedVersion && version !== expectedVersion) throw new Error("Invalid stable release");
|
|
41
|
+
const date = typeof value.published_at === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(value.published_at) && Number.isFinite(Date.parse(value.published_at))
|
|
42
|
+
&& new Date(value.published_at).toISOString().replace(".000Z", "Z") === value.published_at
|
|
43
|
+
? new Date(value.published_at).toISOString() : null;
|
|
44
|
+
return { version, published_at: date };
|
|
45
|
+
}
|
|
46
|
+
return async () => {
|
|
47
|
+
if (pending) return structuredClone(await pending);
|
|
48
|
+
const ttl = snapshot?.status === "checked" ? 5 * 60 * 1000 : 60 * 1000;
|
|
49
|
+
if (snapshot && now() - attemptedAt < ttl) return structuredClone(snapshot);
|
|
50
|
+
attemptedAt = now();
|
|
51
|
+
pending = (async () => {
|
|
52
|
+
try {
|
|
53
|
+
const fetchImpl = await fetchFactory();
|
|
54
|
+
const latest = await metadata(fetchImpl, "latest");
|
|
55
|
+
if (latest.version === currentVersion) currentDate = latest.published_at;
|
|
56
|
+
else if (!currentDate && stableVersion(currentVersion)) {
|
|
57
|
+
try { currentDate = (await metadata(fetchImpl, `tags/v${currentVersion}`, currentVersion)).published_at; } catch { /* The date can be unknown without hiding a verified newer release. */ }
|
|
58
|
+
}
|
|
59
|
+
snapshot = { source: "release_status", status: "checked", current: current(), latest,
|
|
60
|
+
update_available: isVersionGreater(latest.version, currentVersion), checked_at: new Date(now()).toISOString(), last_success_at: new Date(now()).toISOString() };
|
|
61
|
+
} catch (error) {
|
|
62
|
+
snapshot = { source: "release_status", status: error.code === "rate_limited" ? "rate_limited" : "unavailable", current: current(),
|
|
63
|
+
latest: snapshot?.latest || null, update_available: false, checked_at: new Date(now()).toISOString(), last_success_at: snapshot?.last_success_at || null };
|
|
64
|
+
}
|
|
65
|
+
return snapshot;
|
|
66
|
+
})();
|
|
67
|
+
try { return structuredClone(await pending); } finally { pending = null; }
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const dashboardUpdateStatus = createDashboardUpdateStatus();
|
package/src/dashboard.mjs
CHANGED
|
@@ -8,6 +8,7 @@ const ASSETS = new Map([
|
|
|
8
8
|
["/language.js", ["./dashboard/language.js", "text/javascript; charset=utf-8"]],
|
|
9
9
|
["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
|
|
10
10
|
["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
|
|
11
|
+
["/updates.js", ["./dashboard/updates.js", "text/javascript; charset=utf-8"]],
|
|
11
12
|
["/status.js", ["./dashboard/status.js", "text/javascript; charset=utf-8"]],
|
|
12
13
|
["/usage.js", ["./dashboard/usage.js", "text/javascript; charset=utf-8"]],
|
|
13
14
|
["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
|
package/src/m365-settings.mjs
CHANGED
|
@@ -10,7 +10,7 @@ export function m365Paths({ home = os.homedir() } = {}) {
|
|
|
10
10
|
const directory = path.join(home, ".local", "share", "codex-copilot-dx", "profiles", "m365");
|
|
11
11
|
return { directory, settings: path.join(directory, "settings.json"), account: path.join(directory, "account.json"),
|
|
12
12
|
catalog: path.join(directory, "models.json"), gateway: path.join(directory, "gateway.json"),
|
|
13
|
-
ownership: path.join(directory, "client-config.json") };
|
|
13
|
+
ownership: path.join(directory, "client-config.json"), conversations: path.join(directory, "conversations.json") };
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
export function readM365Json(file, fallback = null) {
|
|
@@ -71,6 +71,28 @@ export function readM365Account(options = {}) {
|
|
|
71
71
|
return account;
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
export function writeM365Binding(account, catalog, { expectedAccount, ...options } = {}) {
|
|
75
|
+
const paths = m365Paths(options);m365AccountKey(account);
|
|
76
|
+
fs.mkdirSync(paths.directory, { recursive: true, mode: 0o700 });
|
|
77
|
+
return withFileLockSync(path.join(paths.directory, "binding.lock"), () => {
|
|
78
|
+
const previous = readM365Account(options), oldCatalog = readM365Json(paths.catalog);
|
|
79
|
+
if (expectedAccount !== undefined && (previous ? m365AccountKey(previous) : null) !== (expectedAccount ? m365AccountKey(expectedAccount) : null)) {
|
|
80
|
+
throw Object.assign(new Error("The company account changed. Refresh the account list."), { code: "m365_account_selection_stale", statusCode: 409 });
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
writeM365Json(paths.catalog, catalog);
|
|
84
|
+
writeM365Json(paths.account, account);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
try {
|
|
87
|
+
if (oldCatalog) writeM365Json(paths.catalog, oldCatalog);else fs.rmSync(paths.catalog, { force: true });
|
|
88
|
+
if (previous) writeM365Json(paths.account, previous);else fs.rmSync(paths.account, { force: true });
|
|
89
|
+
}
|
|
90
|
+
catch { throw Object.assign(new Error("Company account save failed; its model cache could not be restored. Existing account binding was preserved."), { code: "m365_account_save_failed", cause: error }); }
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
74
96
|
export function ensureM365GatewayKey(options = {}) {
|
|
75
97
|
const file = m365Paths(options).gateway;
|
|
76
98
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js", "/console.js"]);
|
|
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"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js", "/console.js", "/updates.js"]);
|
|
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"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
5
5
|
return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
|
|
@@ -15,9 +15,10 @@ export async function handleProviderManagement(req, res, runtime) {
|
|
|
15
15
|
const abort = createRequestAbort(req, res);abort.setTimeout(2000, "request_body_timeout");
|
|
16
16
|
try {
|
|
17
17
|
const input = await readJsonBody(req, { maxBodyBytes: 4096, maxDecodedBodyBytes: 4096, signal: abort.signal });
|
|
18
|
-
const allowed = new Set(["action", "provider", "model", "auto_review_model", "family", "effort"]);
|
|
18
|
+
const allowed = new Set(["action", "provider", "model", "auto_review_model", "family", "effort", "account_id"]);
|
|
19
19
|
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !allowed.has(key))
|
|
20
|
-
|| !["models", "switch", "on", "off", "remove", "auto-review"].includes(input.action)) throw httpError("Invalid provider action", 400);
|
|
20
|
+
|| !["models", "switch", "on", "off", "remove", "auto-review", "accounts", "account"].includes(input.action)) throw httpError("Invalid provider action", 400);
|
|
21
|
+
if (input.action === "account" && (typeof input.account_id !== "string" || !/^[a-f0-9]{64}$/.test(input.account_id))) throw httpError("Select an available company account", 400);
|
|
21
22
|
if (input.effort !== undefined && input.effort !== null && (typeof input.effort !== "string" || input.effort.length > 16)) throw httpError("Invalid reasoning effort", 400);
|
|
22
23
|
for (const key of ["provider", "model", "auto_review_model", "family"]) if (input[key] !== undefined && (typeof input[key] !== "string" || input[key].length > 128)) throw httpError("Invalid provider selection", 400);
|
|
23
24
|
abort.clearTimeout();
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -4,7 +4,9 @@ import { autoReviewReasoningEfforts, DEFAULT_CODEX_AUTO_REVIEW_MODEL, responsesM
|
|
|
4
4
|
import { publicModelCatalog } from "./provider-metadata.mjs";
|
|
5
5
|
import { createGithubProvider } from "./providers/github.mjs";
|
|
6
6
|
import { readProviderSettings, writeProviderSettings } from "./provider-settings.mjs";
|
|
7
|
-
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey } from "./m365-settings.mjs";
|
|
7
|
+
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey, readM365Account, m365AccountKey } from "./m365-settings.mjs";
|
|
8
|
+
import { requestM365Accounts } from "./providers/m365-auth.mjs";
|
|
9
|
+
import { publicM365Accounts, accountChoiceId, m365AccountMessage } from "./providers/m365-accounts.mjs";
|
|
8
10
|
import { providerRegistry } from "./provider-registry.mjs";
|
|
9
11
|
import { createClaudeClientLifecycle } from "./claude-client-lifecycle.mjs";
|
|
10
12
|
|
|
@@ -14,12 +16,14 @@ const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavaila
|
|
|
14
16
|
// Composition owns source selection. Providers never modify Codex, prediction,
|
|
15
17
|
// image configuration or each other's credentials.
|
|
16
18
|
export function createProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", home, env = process.env, platform = process.platform,
|
|
17
|
-
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients
|
|
19
|
+
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
|
|
20
|
+
discoverM365 = requestM365Accounts } = {}) {
|
|
18
21
|
const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
|
|
19
22
|
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
20
23
|
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
21
24
|
let selection = readProviderSettings(options), m365 = null, gateway = null, pending = null, closed = false, serial = null;
|
|
22
25
|
let reason = null, claudeReason = null, lastClients = {};
|
|
26
|
+
let changingAccount = false;
|
|
23
27
|
const clientLifecycle = createClaudeClientLifecycle({ options, configureClients, restoreClients });
|
|
24
28
|
const sources = new Map([[github.id, github]]);
|
|
25
29
|
const dashboardProfiles = new Map();
|
|
@@ -76,7 +80,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
76
80
|
return m365;
|
|
77
81
|
})().catch(error => {
|
|
78
82
|
reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_unavailable";
|
|
79
|
-
log("info",
|
|
83
|
+
log("info", m365AccountMessage(reason));return null;
|
|
80
84
|
}).finally(() => { if (pending === operation) pending = null; });
|
|
81
85
|
pending = operation;return operation;
|
|
82
86
|
}
|
|
@@ -86,6 +90,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
86
90
|
m365: { ...(m365?.snapshot() || {}), enabled, state: !enabled ? "disabled" : pending ? "checking"
|
|
87
91
|
: !["darwin", "win32"].includes(platform) ? "unsupported" : m365?.snapshot().state || (reason ? "unavailable" : "idle"),
|
|
88
92
|
reason: reason || m365?.snapshot().reason || null,
|
|
93
|
+
account_change_in_flight: changingAccount,
|
|
89
94
|
preference: selection.m365 || null,
|
|
90
95
|
active_requests: activeM365Requests,
|
|
91
96
|
claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway ? corePort : null,
|
|
@@ -93,6 +98,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
93
98
|
observed_clients: { ...lastClients }, requests: gateway?.snapshot?.() || null } } });
|
|
94
99
|
|
|
95
100
|
function current() {
|
|
101
|
+
if (selection.codex === "m365" && changingAccount) throw Object.assign(new Error(m365AccountMessage("m365_account_busy")), { code: "m365_account_busy", statusCode: 409 });
|
|
96
102
|
const source = sources.get(selection.codex);
|
|
97
103
|
if (!source || selection.codex === "m365" && (!enabled || source.snapshot().state === "disabled")) throw unavailable(reason || "m365_not_ready");
|
|
98
104
|
return source;
|
|
@@ -101,6 +107,47 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
101
107
|
const next = (serial || Promise.resolve()).then(task);
|
|
102
108
|
serial = next.catch(() => {});return next;
|
|
103
109
|
};
|
|
110
|
+
async function discoverAccounts() {
|
|
111
|
+
if (!["darwin", "win32"].includes(platform)) throw unavailable("m365_platform_unsupported");
|
|
112
|
+
const result = await discoverM365({ env });
|
|
113
|
+
return { ...result, binding: readM365Account(options) };
|
|
114
|
+
}
|
|
115
|
+
async function selectAccount(id) {
|
|
116
|
+
if (typeof id !== "string" || !/^[a-f0-9]{64}$/.test(id)) throw Object.assign(new Error("Use an account ID from ccdx m365 accounts"), { statusCode: 400 });
|
|
117
|
+
if (!enabled) throw unavailable("m365_disabled");
|
|
118
|
+
if (activeM365Requests > 0 || gateway?.snapshot?.().active > 0 || pending) {
|
|
119
|
+
throw Object.assign(new Error(m365AccountMessage("m365_account_busy")), { code: "m365_account_busy", statusCode: 409 });
|
|
120
|
+
}
|
|
121
|
+
changingAccount = true;
|
|
122
|
+
let candidate, opened;
|
|
123
|
+
try {
|
|
124
|
+
const discovered = await discoverAccounts();
|
|
125
|
+
const chosen = discovered.accounts.find(value => accountChoiceId(value) === id);
|
|
126
|
+
if (!chosen) throw Object.assign(new Error("Account list changed. Check again and select an available account."), { code: "m365_account_selection_stale", statusCode: 409 });
|
|
127
|
+
const switched = discovered.binding && m365AccountKey(discovered.binding) !== m365AccountKey(chosen);
|
|
128
|
+
const factory = createM365 || (await import("./providers/m365.mjs")).createM365Provider;
|
|
129
|
+
candidate = factory({ home, env, log, persist: false,
|
|
130
|
+
account: { ...chosen, selection_source: "manual", ...(switched || discovered.binding?.history_isolation ? { history_isolation: true } : {}) },
|
|
131
|
+
onCatalog() { if (candidate === m365 && !closed) setImmediate(() => { if (candidate === m365 && !closed) void syncClaudeClients(); }); } });
|
|
132
|
+
await candidate.refresh();
|
|
133
|
+
if (closed) throw unavailable("m365_runtime_closed");
|
|
134
|
+
if (candidate.models("claude").length) {
|
|
135
|
+
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
136
|
+
opened = await start({ provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log,
|
|
137
|
+
onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
|
|
138
|
+
}
|
|
139
|
+
candidate.commitSelection(discovered.binding);
|
|
140
|
+
const previous = m365, previousGateway = gateway;
|
|
141
|
+
m365 = candidate;gateway = opened || null;sources.set("m365", m365);reason = null;
|
|
142
|
+
candidate = null;opened = null;
|
|
143
|
+
try { await previousGateway?.close();previous?.close(); }
|
|
144
|
+
catch { log("warn", "Previous Microsoft 365 connection cleanup failed; the selected account is active"); }
|
|
145
|
+
claudeReason = gateway ? null : "m365_no_claude_models";
|
|
146
|
+
await syncClaudeClients();
|
|
147
|
+
changingAccount = false;
|
|
148
|
+
return snapshot();
|
|
149
|
+
} finally { await opened?.close();candidate?.close();changingAccount = false; }
|
|
150
|
+
}
|
|
104
151
|
async function switchSource(provider, preference) {
|
|
105
152
|
if (!providerRegistry.get(provider)?.codex) throw new Error("Choose a listed Codex source");
|
|
106
153
|
if (provider === "m365") {
|
|
@@ -134,7 +181,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
134
181
|
if (remove) {
|
|
135
182
|
if (result.remaining) throw Object.assign(new Error("User-modified Claude settings were preserved; M365 profile cleanup is incomplete"), { code: "m365_cleanup_preserved" });
|
|
136
183
|
const paths = m365Paths(options);
|
|
137
|
-
for (const file of [paths.account, paths.catalog, paths.gateway, paths.ownership]) {
|
|
184
|
+
for (const file of [paths.account, paths.catalog, paths.gateway, paths.ownership, paths.conversations]) {
|
|
138
185
|
try { if (!fs.lstatSync(file).isFile()) throw Error();fs.unlinkSync(file); }
|
|
139
186
|
catch (error) { if (error.code !== "ENOENT") throw new Error("M365 cleanup preserved an unexpected file"); }
|
|
140
187
|
}
|
|
@@ -144,6 +191,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
144
191
|
return {
|
|
145
192
|
github, current, snapshot, start: startM365, refresh: () => startM365(true),
|
|
146
193
|
handleClaude(req, res) {
|
|
194
|
+
if (changingAccount) { res.writeHead(409, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify({ error: { code: "m365_account_busy", message: m365AccountMessage("m365_account_busy") } }));return; }
|
|
147
195
|
if (!enabled || !gateway?.handle) {
|
|
148
196
|
res.writeHead(503, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
149
197
|
res.end(JSON.stringify({ type: "error", error: { type: "api_error", code: claudeReason || reason || "m365_claude_unavailable", message: "Claude is unavailable; check the model service settings." } }));return;
|
|
@@ -161,6 +209,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
161
209
|
{ id: "m365", name: "Microsoft 365", generation: m365 ? dashboardGeneration(m365) : 0, enabled, state: ms.state, reason: ms.reason,
|
|
162
210
|
auth: { state: ms.token_cached ? "authorized" : !enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
|
|
163
211
|
account: ms.account?.login || "", token_cached: ms.token_cached === true,
|
|
212
|
+
tenant: ms.account?.tenant || "", selection_source: ms.account?.selection_source || null,
|
|
164
213
|
expires_in_ms: ms.token_expires_in_ms ?? null, checked_at: ms.token_checked_at || null },
|
|
165
214
|
models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
|
|
166
215
|
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "m365", state: selection.codex === "m365" ? ms.state : "standby" },
|
|
@@ -195,7 +244,8 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
195
244
|
// Internal bounded correlation only; IDs are never exposed or persisted.
|
|
196
245
|
const key = typeof raw === "string" && raw.length <= 512 ? raw : null;
|
|
197
246
|
const previous = key && sessions.get(key)?.namespace || priorNamespace, order = ++requestOrder;
|
|
198
|
-
return { historyNamespace: namespace, historyTransferNamespace: previous && previous !== namespace
|
|
247
|
+
return { historyNamespace: namespace, historyTransferNamespace: previous && previous !== namespace
|
|
248
|
+
&& !(previous.startsWith("m365:") && namespace.startsWith("m365:")) ? previous : undefined,
|
|
199
249
|
onHistoryStored() {
|
|
200
250
|
if (!key) return;
|
|
201
251
|
const record = sessions.get(key);
|
|
@@ -208,6 +258,11 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
208
258
|
async action(input) {
|
|
209
259
|
return serialize(async () => {
|
|
210
260
|
if (closed) throw unavailable("m365_runtime_closed");
|
|
261
|
+
if (input.action === "accounts") {
|
|
262
|
+
const result = await discoverAccounts();
|
|
263
|
+
return { accounts: publicM365Accounts(result.accounts, result), state: snapshot() };
|
|
264
|
+
}
|
|
265
|
+
if (input.action === "account") return selectAccount(input.account_id);
|
|
211
266
|
if (input.action === "models") { await startM365();return { state: snapshot(), models: m365?.models(input.family === "claude" ? "claude" : "gpt") || [] }; }
|
|
212
267
|
if (input.action === "auto-review") {
|
|
213
268
|
if (input.provider && input.provider !== selection.codex) throw new Error("Save the source before changing review settings");
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
const fail = code => Object.assign(new Error(code), { code });
|
|
7
|
+
const clean = (value, limit) => typeof value === "string" && value.length > 0 && value.length <= limit && !/[\u0000-\u0020\u007f]/.test(value);
|
|
8
|
+
export const accountChoiceId = account => createHash("sha256").update(`${account.tenant}\0${account.id}`).digest("hex");
|
|
9
|
+
|
|
10
|
+
export function normalizeBrokerAccounts(values) {
|
|
11
|
+
if (!Array.isArray(values) || values.length > 128) throw fail("m365_accounts_invalid");
|
|
12
|
+
const accounts = new Map();
|
|
13
|
+
for (const value of values) {
|
|
14
|
+
if (!clean(value?.homeAccountId, 512) || !clean(value.realm, 128) || !clean(value.username, 320) || !clean(value.accountId, 512)) continue;
|
|
15
|
+
// Personal Microsoft accounts cannot authorize this organization-only service.
|
|
16
|
+
if (value.realm.toLowerCase() === "9188040d-6c67-4c5b-b112-36a304b66dad") continue;
|
|
17
|
+
const account = { id: value.homeAccountId, tenant: value.realm, login: value.username };
|
|
18
|
+
const key = accountChoiceId(account), prior = accounts.get(key);
|
|
19
|
+
if (prior && (prior.login.toLowerCase() !== account.login.toLowerCase()
|
|
20
|
+
|| prior.native.environment !== value.environment || prior.native.localAccountId !== value.localAccountId)) throw fail("m365_account_conflict");
|
|
21
|
+
if (!prior) accounts.set(key, { ...account, native: value });
|
|
22
|
+
}
|
|
23
|
+
return [...accounts.values()];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function windowsAccountHint({ platform = process.platform, env = process.env, signal, execFileImpl = promisify(execFile) } = {}) {
|
|
27
|
+
if (platform !== "win32") return null;
|
|
28
|
+
try {
|
|
29
|
+
const { stdout } = await execFileImpl(path.win32.join(env.SystemRoot || env.WINDIR || "C:\\Windows", "System32", "whoami.exe"), ["/upn"],
|
|
30
|
+
{ env, signal, timeout: 2500, maxBuffer: 8192, windowsHide: true, encoding: "utf8" });
|
|
31
|
+
const upn = stdout.trim();
|
|
32
|
+
return clean(upn, 320) && /^[^@\s]+@[^@\s]+$/.test(upn) ? upn : null;
|
|
33
|
+
} catch { return null; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function chooseM365Account(accounts, { binding, windowsLogin } = {}) {
|
|
37
|
+
if (binding) {
|
|
38
|
+
const matches = accounts.filter(value => value.id === binding.id && value.tenant === binding.tenant);
|
|
39
|
+
if (matches.length !== 1) throw fail("m365_account_unavailable");
|
|
40
|
+
return { ...matches[0], selection_source: ["manual", "windows", "single"].includes(binding.selection_source) ? binding.selection_source : "legacy" };
|
|
41
|
+
}
|
|
42
|
+
if (!accounts.length) throw fail("m365_account_unavailable");
|
|
43
|
+
const current = windowsLogin && accounts.filter(value => value.login.toLowerCase() === windowsLogin.toLowerCase());
|
|
44
|
+
if (current?.length === 1) return { ...current[0], selection_source: "windows" };
|
|
45
|
+
if (accounts.length === 1) return { ...accounts[0], selection_source: "single" };
|
|
46
|
+
throw fail("m365_account_ambiguous");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function publicM365Accounts(accounts, { binding, windowsLogin } = {}) {
|
|
50
|
+
const matches = windowsLogin ? accounts.filter(value => value.login.toLowerCase() === windowsLogin.toLowerCase()) : [];
|
|
51
|
+
return accounts.map(account => ({ id: accountChoiceId(account), login: account.login, tenant: account.tenant,
|
|
52
|
+
selected: Boolean(binding && binding.id === account.id && binding.tenant === account.tenant),
|
|
53
|
+
current_windows: matches.length === 1 && matches[0] === account }));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function m365AccountMessage(code) {
|
|
57
|
+
return ({ m365_account_ambiguous: "Choose a company account in Model sources or run ccdx m365 account.",
|
|
58
|
+
m365_account_unavailable: "Company account unavailable. Connect it in Windows or macOS, then check again.",
|
|
59
|
+
m365_account_conflict: "Account records conflict. Check your company sign-in, then check again.",
|
|
60
|
+
m365_interaction_required: "Complete your company sign-in, then check again.",
|
|
61
|
+
m365_llm_permission_unavailable: "This account does not have model access.",
|
|
62
|
+
m365_account_busy: "Finish active Microsoft 365 requests before changing accounts.",
|
|
63
|
+
m365_account_changed: "This conversation belongs to another company account. Start a new conversation.",
|
|
64
|
+
m365_catalog_http_403: "Model access was denied. Check company permissions and network policy.",
|
|
65
|
+
m365_catalog_http_401: "Company authorization was rejected. Check your sign-in and company policy." })[code] || "Microsoft 365 is unavailable. Check company sign-in, network and permissions.";
|
|
66
|
+
}
|
|
@@ -6,6 +6,7 @@ import { promisify } from "node:util";
|
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import path from "node:path";
|
|
9
|
+
import { normalizeBrokerAccounts, chooseM365Account, windowsAccountHint } from "./m365-accounts.mjs";
|
|
9
10
|
|
|
10
11
|
export const M365_CLIENT_ID = "aebc6443-996d-45c2-90f0-388ff96faa56";
|
|
11
12
|
export const M365_RESOURCE = "42c8f7bd-c7a8-4ba9-bc1c-91edfb716247";
|
|
@@ -19,9 +20,9 @@ export function brokerFailure(error) {
|
|
|
19
20
|
return { code, aadsts: [...new Set(String(error?.errorContext || "").match(/AADSTS\d+/g) || [])].slice(0, 3) };
|
|
20
21
|
}
|
|
21
22
|
|
|
22
|
-
export async function acquireSilentM365Token({ account = null } = {}, {
|
|
23
|
+
export async function acquireSilentM365Token({ account = null, action = "token" } = {}, {
|
|
23
24
|
platform = process.platform, loadBroker = () => createRequire(import.meta.url)("@azure/msal-node-runtime").msalNodeRuntime,
|
|
24
|
-
execFileImpl = promisify(execFile),
|
|
25
|
+
execFileImpl = promisify(execFile), env = process.env,
|
|
25
26
|
} = {}) {
|
|
26
27
|
if (!["darwin", "win32"].includes(platform)) throw fail("m365_platform_unsupported");
|
|
27
28
|
if (platform === "darwin") {
|
|
@@ -39,18 +40,19 @@ export async function acquireSilentM365Token({ account = null } = {}, {
|
|
|
39
40
|
catch (error) { reject(error); }
|
|
40
41
|
});
|
|
41
42
|
const discovered = await invoke("DiscoverAccountsAsync", M365_CLIENT_ID, randomUUID());
|
|
42
|
-
const accounts = (discovered.accounts || [])
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
if (
|
|
46
|
-
const selected =
|
|
43
|
+
const accounts = normalizeBrokerAccounts(discovered.accounts || []);
|
|
44
|
+
const windowsLogin = (!account || action === "accounts") && accounts.length > 1
|
|
45
|
+
? await windowsAccountHint({ platform, env, execFileImpl }) : null;
|
|
46
|
+
if (action === "accounts") return { accounts: accounts.map(({ native, ...value }) => value), windowsLogin };
|
|
47
|
+
const selected = chooseM365Account(accounts, { binding: account, windowsLogin }), parameters = new broker.AuthParameters();
|
|
47
48
|
parameters.CreateAuthParameters(M365_CLIENT_ID, AUTHORITY);
|
|
48
49
|
parameters.SetRedirectUri(platform === "darwin" ? "msauth.com.msauth.unsignedapp://auth" : `ms-appx-web://Microsoft.AAD.BrokerPlugin/${M365_CLIENT_ID}`);
|
|
49
50
|
parameters.SetRequestedScopes(`${M365_RESOURCE}/.default`);
|
|
50
|
-
const result = await invoke("AcquireTokenSilentlyAsync", parameters, randomUUID(), selected);
|
|
51
|
+
const result = await invoke("AcquireTokenSilentlyAsync", parameters, randomUUID(), selected.native);
|
|
51
52
|
if (!result.accessToken || !String(result.grantedScopes || "").split(" ").includes(`${M365_RESOURCE}/LLM.Read`)) throw fail("m365_llm_permission_unavailable");
|
|
53
|
+
if (result.account && (result.account.homeAccountId !== selected.id || result.account.realm !== selected.tenant)) throw fail("m365_account_changed");
|
|
52
54
|
return { token: result.accessToken, expiresAt: Number(result.expiresOn) * 1000,
|
|
53
|
-
account: { id: selected.
|
|
55
|
+
account: { id: selected.id, tenant: selected.tenant, login: selected.login, selection_source: selected.selection_source } };
|
|
54
56
|
}
|
|
55
57
|
|
|
56
58
|
async function main() {
|
|
@@ -63,7 +65,7 @@ async function main() {
|
|
|
63
65
|
if (Buffer.byteLength(input) > 4096) throw fail("m365_auth_request_invalid");
|
|
64
66
|
}
|
|
65
67
|
const request = JSON.parse(input);
|
|
66
|
-
if (request.action
|
|
68
|
+
if (!["token", "accounts"].includes(request.action)) throw fail("m365_auth_request_invalid");
|
|
67
69
|
const result = await acquireSilentM365Token(request);
|
|
68
70
|
process.stdout.write(JSON.stringify(result), () => process.exit(0));
|
|
69
71
|
} catch (error) { process.stdout.write(JSON.stringify({ error: brokerFailure(error) }), () => process.exit(1)); }
|