codex-copilot-dx 1.2.1 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/bin/cli.mjs +1 -1
- package/docs/ARCHITECTURE.md +10 -0
- package/docs/REFERENCE.md +30 -7
- 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 +61 -5
- package/src/dashboard/index.html +64 -8
- package/src/dashboard/language.js +47 -0
- package/src/dashboard/status.js +11 -2
- package/src/dashboard/theme.js +39 -16
- package/src/dashboard/ui.css +58 -0
- package/src/dashboard/ui.js +27 -1
- package/src/dashboard-api.mjs +18 -3
- package/src/m365-settings.mjs +23 -1
- package/src/optional-routes.mjs +1 -1
- 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 +11 -7
- package/src/startup-ui.mjs +5 -2
- package/src/terminal-colors.mjs +20 -0
- package/src/terminal-console.mjs +6 -2
- package/src/user-settings.mjs +22 -1
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
"company_account": ["Company account", "公司账号"],
|
|
4
|
+
"check_accounts": ["Check accounts", "检查账号"],
|
|
5
|
+
"choose_company_account": ["Choose a company account", "选择公司账号"],
|
|
6
|
+
"use_this_account": ["Use this account", "使用此账号"],
|
|
7
|
+
"company_account_scope": ["Applies to Microsoft 365 in Codex and Claude. Start a new conversation after changing accounts.", "影响 Codex 和 Claude 的 M365 服务。\n更换账号后请新建对话。"],
|
|
8
|
+
"company_account_current": ["{login} · Tenant {tenant} · {source}", "{login}\n租户:{tenant} · {source}"],
|
|
9
|
+
"account_source_windows": ["Windows sign-in", "Windows 登录账号"],
|
|
10
|
+
"account_source_single": ["Only company account", "唯一公司账号"],
|
|
11
|
+
"account_source_manual": ["Your choice", "手动选择"],
|
|
12
|
+
"account_source_legacy": ["Saved account", "已保存账号"],
|
|
13
|
+
"company_account_none": ["No company account connected.", "尚未连接公司账号。"],
|
|
14
|
+
"company_account_choose": ["Choose an account. Browsing does not change your connection.", "请选择账号。查看列表不会切换。"],
|
|
15
|
+
"company_account_empty": ["No company account found. Connect your work account in Windows or macOS, then check again.", "未找到公司账号。\n请先连接工作账号,再检查。"],
|
|
16
|
+
"company_account_confirm": ["Change the Microsoft 365 account for Codex and Claude? Existing conversations will not move to the new account. Start a new conversation.", "更换 Codex 和 Claude 的 M365 账号?旧对话不会转移,请新建对话。"],
|
|
17
|
+
"company_account_checked": ["Account connected. Model list checked; inference access is not tested.", "账号已连接,模型列表已检查。\n尚未测试实际请求。"],
|
|
18
|
+
"m365_account_ambiguous": ["Choose a company account below.", "请在下方选择公司账号。"],
|
|
19
|
+
"m365_account_unavailable": ["Company account unavailable. Check your work sign-in, then check again.", "公司账号不可用。\n请检查工作账号登录。"],
|
|
20
|
+
"m365_account_conflict": ["Account records conflict. Check your work sign-in.", "账号记录冲突,请检查工作登录。"],
|
|
21
|
+
"m365_interaction_required": ["Complete your company sign-in, then check again.", "请先完成公司登录,再检查。"],
|
|
22
|
+
"m365_llm_permission_unavailable": ["This account does not have model access.", "此账号没有模型访问权限。"],
|
|
23
|
+
"m365_account_busy": ["Finish Microsoft 365 requests before changing accounts.", "请在 M365 请求结束后更换。"],
|
|
24
|
+
"m365_account_selection_stale": ["Account list changed. Check again and select an account.", "账号列表已变化,请重新检查。"],
|
|
25
|
+
"company_account_check_failed": ["Could not read accounts. Check company sign-in and the native authentication component.", "未能读取账号。\n请检查公司登录和认证组件。"],
|
|
26
|
+
"company_account_not_saved": ["Account not changed. Previous connection kept. {reason}", "账号未更换,保留原连接。\n{reason}"],
|
|
27
|
+
"source_catalog_unavailable": ["Model list unavailable: {code}", "模型列表不可用:{code}"],
|
|
28
|
+
"terminal_color_preview": ["Terminal color preview", "终端配色预览"],
|
|
29
|
+
"source_retry_time": ["Can retry after {time}.", "可在 {time} 后重试。"],
|
|
30
|
+
"appearance_web_appearance": ["WEB APPEARANCE", "网页外观"],
|
|
31
|
+
"appearance_color_theme": ["Color theme", "颜色主题"],
|
|
32
|
+
"appearance_browser_scope": ["This browser only.", "只影响当前浏览器。"],
|
|
33
|
+
"appearance_classic_green": ["Classic green (default)", "经典绿(默认)"],
|
|
34
|
+
"appearance_klein_blue": ["Klein blue", "克莱因蓝"],
|
|
35
|
+
"appearance_terminal_scope": ["Independent of the webpage theme.", "与网页主题分别设置。"],
|
|
36
|
+
"appearance_terminal_effect": ["Table updates now. Startup logo changes next launch.", "表格即时换色,启动 Logo 下次生效。"],
|
|
37
|
+
"appearance_sample": ["Sample data", "示例数据"],
|
|
38
|
+
"theme_saved_browser": ["Saved in this browser. Changes apply now.", "保存在此浏览器,立即生效。"],
|
|
39
|
+
"theme_tab_only": ["This tab only. Browser storage is unavailable.", "本次有效,浏览器未能保存。"],
|
|
40
|
+
"terminal_theme_applied": ["Table updated. Startup logo changes next launch.", "表格已换色,启动 Logo 下次生效。"],
|
|
41
|
+
"terminal_theme_unavailable": ["Saved. Colored output is unavailable in this terminal mode.", "已保存,当前终端模式不显示配色。"],
|
|
42
|
+
"source_check_details": ["Check details", "检查详情"],
|
|
43
|
+
"source_check_failed": ["{source}: model list update failed.", "{source}:模型列表更新失败。"],
|
|
44
|
+
"source_check_previous": ["Showing the list from {time}.", "当前显示 {time} 的列表。"],
|
|
45
|
+
"source_check_none": ["No previous model list is available.", "暂无可用的旧模型列表。"],
|
|
46
|
+
"source_check_time": ["Last check", "本次检查"],
|
|
47
|
+
"source_check_reason": ["Reason", "失败原因"],
|
|
48
|
+
"source_check_action": ["Use Refresh to check this source again.", "点击刷新,重新检查此来源。"],
|
|
49
|
+
"source_failure_summary": ["{source} / {detail}", "{source} / {detail}"],
|
|
3
50
|
"codex_body_admission_active_active_queued_queued_queue_limit_lim": ["Codex body admission: active {active} / queued {queued} / queue limit {limit}", "Codex请求体:进行中{active}\n排队{queued} / 队列上限{limit}"],
|
|
4
51
|
"terminal_animation_unavailable_in_this_output_mode": ["Terminal animation unavailable in this output mode", "当前输出模式不播放终端动效"],
|
|
5
52
|
"prediction_integration_setup": ["Suggestion setup", "建议设置"],
|
package/src/dashboard/status.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
let contextCompactions = {};
|
|
5
5
|
let failureSignature;
|
|
6
6
|
let contextSignature;
|
|
7
|
+
const sourceNames = new Map([["github", "GitHub Copilot"], ["m365", "Microsoft 365"]]);
|
|
7
8
|
|
|
8
9
|
function renderProviders(data) {
|
|
9
10
|
const providers = data.providers || [];
|
|
@@ -15,6 +16,7 @@
|
|
|
15
16
|
auth.replaceChildren();clients.replaceChildren();requests.replaceChildren();
|
|
16
17
|
const routes = [];
|
|
17
18
|
for (const provider of providers) {
|
|
19
|
+
sourceNames.set(provider.id, provider.name);
|
|
18
20
|
const identity = provider.auth || {};
|
|
19
21
|
const authRow = tableRow([provider.name, identity.account || "—", states[identity.state] || "unknown",
|
|
20
22
|
states[provider.state] || "unknown", identity.checked_at || "—", duration(identity.expires_in_ms)], { labels: [2, 3] });
|
|
@@ -83,15 +85,22 @@
|
|
|
83
85
|
details.dataset.key = `${failure.at}/${failure.request_id || failure.response_id}/${failure.code}`;
|
|
84
86
|
details.open = expanded.has(details.dataset.key);
|
|
85
87
|
const title = document.createElement("summary");
|
|
86
|
-
|
|
88
|
+
const summary = {
|
|
87
89
|
detail: phrase("time_model_code", {
|
|
88
90
|
time: failure.at ? String(failure.at) : phrase("unknown_time"),
|
|
89
91
|
model: failure.model ? String(failure.model).slice(0, 80) : phrase("unknown_model"),
|
|
90
92
|
code: failure.code ? String(failure.code).slice(0, 80) : phrase("unknown_error"),
|
|
91
93
|
}),
|
|
92
94
|
retry: phrase(failure.retried ? "retry_attempted" : "no_retry"),
|
|
93
|
-
}
|
|
95
|
+
};
|
|
96
|
+
localize(title, "detail_retry", summary);
|
|
94
97
|
const timeline = failure.timeline;
|
|
98
|
+
const provider = failure.provider || timeline?.provider;
|
|
99
|
+
if (provider) {
|
|
100
|
+
const source = sourceNames.get(provider) || provider;
|
|
101
|
+
const original = phrase("detail_retry", summary);
|
|
102
|
+
localize(title, "source_failure_summary", { source, detail: original });
|
|
103
|
+
}
|
|
95
104
|
const timings = timeline?.timings_ms || {};
|
|
96
105
|
const timingText = ["admission", "body", "history", "images", "serialization", "upstream_start", "upstream_headers", "first_output", "last_activity", "terminal", "finished"]
|
|
97
106
|
.filter((key) => finite(timings[key])).map((key) => `${key}=${Number(timings[key]).toFixed(1)}`).join(" / ");
|
package/src/dashboard/theme.js
CHANGED
|
@@ -1,35 +1,58 @@
|
|
|
1
1
|
(() => {
|
|
2
|
-
const key = "ccdx.dashboard.theme";
|
|
3
|
-
|
|
2
|
+
const key = "ccdx.dashboard.theme", paletteKey = "ccdx.dashboard.palette";
|
|
3
|
+
const valid = value => value === "green" || value === "klein";
|
|
4
|
+
let theme = "dark", palette = "green", saved = true;
|
|
4
5
|
try {
|
|
5
6
|
if (localStorage.getItem(key) === "light") theme = "light";
|
|
6
|
-
|
|
7
|
+
const value = localStorage.getItem(paletteKey);if (valid(value)) palette = value;
|
|
8
|
+
} catch { saved = false; }
|
|
9
|
+
const label = (node, message) => {
|
|
10
|
+
if (!node) return;
|
|
11
|
+
if (globalThis.ccdxLanguage) globalThis.ccdxLanguage.set(node, message);
|
|
12
|
+
else node.textContent = message;
|
|
13
|
+
};
|
|
14
|
+
function sync() {
|
|
15
|
+
const select = document.getElementById("web-color-theme");if (select) select.value = palette;
|
|
16
|
+
label(document.getElementById("web-color-note"), saved ? "theme_saved_browser" : "theme_tab_only");
|
|
17
|
+
}
|
|
7
18
|
const applyTheme = () => {
|
|
8
19
|
document.documentElement.dataset.theme = theme;
|
|
9
|
-
|
|
20
|
+
document.documentElement.dataset.palette = palette;
|
|
21
|
+
const color = palette === "klein" ? theme === "dark" ? "#789aff" : "#002fa7" : theme === "dark" ? "#a6f5a8" : "#176b3a";
|
|
10
22
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><g fill="none" stroke="${color}" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="${color}"/></svg>`;
|
|
11
23
|
document.getElementById("favicon").href = `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
|
12
24
|
};
|
|
13
25
|
applyTheme();
|
|
14
|
-
|
|
26
|
+
function persist() {
|
|
27
|
+
try { localStorage.setItem(key, theme);localStorage.setItem(paletteKey, palette);saved = true; }
|
|
28
|
+
catch { saved = false; }
|
|
29
|
+
sync();
|
|
30
|
+
}
|
|
15
31
|
document.addEventListener("DOMContentLoaded", () => {
|
|
16
32
|
const button = document.getElementById("theme-toggle");
|
|
17
33
|
const updateLabel = () => {
|
|
18
|
-
const
|
|
34
|
+
const value = `Switch to ${theme === "dark" ? "light" : "dark"} mode`;
|
|
19
35
|
if (globalThis.ccdxLanguage) {
|
|
20
|
-
globalThis.ccdxLanguage.set(button,
|
|
21
|
-
globalThis.ccdxLanguage.set(button,
|
|
22
|
-
} else {
|
|
23
|
-
button.setAttribute("aria-label", label);
|
|
24
|
-
button.title = label;
|
|
25
|
-
}
|
|
36
|
+
globalThis.ccdxLanguage.set(button, value, {}, "aria-label");
|
|
37
|
+
globalThis.ccdxLanguage.set(button, value, {}, "title");
|
|
38
|
+
} else { button.setAttribute("aria-label", value);button.title = value; }
|
|
26
39
|
};
|
|
27
|
-
updateLabel();
|
|
40
|
+
updateLabel();sync();
|
|
28
41
|
button.addEventListener("click", () => {
|
|
29
|
-
theme = theme === "dark" ? "light" : "dark";
|
|
30
|
-
|
|
31
|
-
try { localStorage.setItem(key, theme); } catch { /* Keep the current selection. */ }
|
|
42
|
+
theme = theme === "dark" ? "light" : "dark";applyTheme();
|
|
43
|
+
persist();
|
|
32
44
|
updateLabel();
|
|
33
45
|
});
|
|
46
|
+
document.getElementById("web-color-theme")?.addEventListener("change", event => {
|
|
47
|
+
if (!valid(event.target.value)) return;
|
|
48
|
+
palette = event.target.value;applyTheme();
|
|
49
|
+
persist();
|
|
50
|
+
});
|
|
51
|
+
globalThis.addEventListener?.("storage", event => {
|
|
52
|
+
if (event.key !== paletteKey && event.key !== key) return;
|
|
53
|
+
if (event.key === paletteKey) palette = valid(event.newValue) ? event.newValue : "green";
|
|
54
|
+
else theme = event.newValue === "light" ? "light" : "dark";
|
|
55
|
+
applyTheme();updateLabel();sync();
|
|
56
|
+
});
|
|
34
57
|
});
|
|
35
58
|
})();
|
package/src/dashboard/ui.css
CHANGED
|
@@ -202,3 +202,61 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
202
202
|
.section-actions > label { flex: 1 1 180px; }
|
|
203
203
|
.section-actions select { max-width: 100%; }
|
|
204
204
|
}
|
|
205
|
+
|
|
206
|
+
/* Independent color palettes; green remains the unchanged default. */
|
|
207
|
+
:root[data-palette="klein"][data-theme="light"] {
|
|
208
|
+
color-scheme: light;
|
|
209
|
+
--page:#F3F6FF; --surface:#ffffff; --text:#19354F; --strong:#102E4C;
|
|
210
|
+
--muted:#4b607a; --badge:#4b607a; --subtle:#4f6681; --quiet:#5d718b; --footer:#5d718b;
|
|
211
|
+
--border:#C5CFEA; --top-border:#B8C6E6; --accent:#002FA7; --accent-soft:#002FA7; --heading:#002FA7;
|
|
212
|
+
--button-border:#819AD4; --button-bg:#EDF2FF; --button-fg:#002FA7; --button-hover:#DAE4FF;
|
|
213
|
+
--selected-bg:#E3EAFF; --option-hover:#EBF0FF; --table-text:#24405E; --preview:#586f8b;
|
|
214
|
+
--ansi-white:#0752A6; --ansi-159:#002FA7; --ansi-123:#1678FF; --ansi-87:#2493FF;
|
|
215
|
+
--ansi-51:#47B6FF; --ansi-45:#438FFF; --ansi-39:#547AFF; --ansi-33:#5D6CDB;
|
|
216
|
+
--bad:#a33625; --failed:#a33625; --incomplete:#835600;
|
|
217
|
+
}
|
|
218
|
+
:root[data-palette="klein"]:not([data-theme="light"]) {
|
|
219
|
+
color-scheme:dark;
|
|
220
|
+
--page:#081625; --surface:#0F2236; --text:#dde7f4; --strong:#eff6ff;
|
|
221
|
+
--muted:#9caec6; --badge:#adbed4; --subtle:#91a8c5; --quiet:#829bb9; --footer:#829bb9;
|
|
222
|
+
--border:#244663; --top-border:#244663; --accent:#789AFF; --accent-soft:#89A7FF; --heading:#93ADFF;
|
|
223
|
+
--button-border:#526CA9; --button-bg:#1B2B4C; --button-fg:#A5BBFF; --button-hover:#273D68;
|
|
224
|
+
--selected-bg:#1C315C; --option-hover:#14334F; --table-text:#d1dfef; --preview:#8da7c9;
|
|
225
|
+
--ansi-white:#edf5ff; --ansi-159:#acd6ff; --ansi-123:#91c7ff; --ansi-87:#7bb9f4;
|
|
226
|
+
--ansi-51:#68a9e5; --ansi-45:#6095d1; --ansi-39:#678ac4; --ansi-33:#707eb1;
|
|
227
|
+
--bad:#ff947e; --failed:#ff9f91; --incomplete:#e3c77c;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
.appearance-row { display:grid; grid-template-columns:minmax(0,1fr) 200px; align-items:center; gap:18px; margin-top:20px; }
|
|
231
|
+
.appearance-label { min-width:0; }
|
|
232
|
+
.appearance-label label { display:block; font-size:13px; color:var(--text); line-height:1.65; }
|
|
233
|
+
.appearance-label p { margin:4px 0 0; font-size:12px; color:var(--subtle); line-height:1.7; }
|
|
234
|
+
.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
|
+
.appearance-note { color:var(--subtle); margin:17px 0 0; font-size:12px; line-height:1.7; }
|
|
236
|
+
.appearance-animation { margin-top:22px; border-top:1px solid var(--border); padding-top:18px; }
|
|
237
|
+
.appearance-animation > summary { color:var(--heading); font-size:12px; font-weight:700; }
|
|
238
|
+
.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
|
+
.terminal-sample[data-terminal-palette="klein"] { --sample-logo:#4C9FFF; --sample-table:#4C9FFF; --sample-motion:#4C9FFF; }
|
|
240
|
+
.terminal-caption { display:flex; justify-content:space-between; flex-wrap:wrap; gap:8px; color:var(--sample-muted); font-size:11px; line-height:1.6; margin-bottom:16px; }
|
|
241
|
+
.terminal-brand { display:flex; align-items:center; flex-wrap:wrap; gap:14px; margin-bottom:15px; }
|
|
242
|
+
.terminal-brand strong { color:var(--sample-text); display:block; font-size:12px; font-weight:500; line-height:1.7; }
|
|
243
|
+
.terminal-brand div>span { display:block; color:var(--sample-muted); font-size:11px; line-height:1.7; }
|
|
244
|
+
.terminal-sample pre { font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace; padding:0; margin:0; background:transparent; border:0; border-radius:0; letter-spacing:0; }
|
|
245
|
+
.terminal-sample .terminal-logo { color:var(--sample-logo); font-size:12px; line-height:1.15; white-space:pre; }
|
|
246
|
+
.terminal-sample .terminal-table { color:var(--sample-table); font-size:11px; line-height:1.45; white-space:pre; }
|
|
247
|
+
.terminal-sample .terminal-notices { margin-top:10px; font-size:11px; line-height:1.6; white-space:pre-wrap; color:var(--sample-muted); }
|
|
248
|
+
.terminal-sample .terminal-motion { color:var(--sample-text); font-size:11px; line-height:1.6; white-space:pre-wrap; }
|
|
249
|
+
#terminal-sample-frame { color:var(--sample-motion); }
|
|
250
|
+
.terminal-compact { display:none; }
|
|
251
|
+
@media(max-width:700px) { .appearance-row { grid-template-columns:minmax(0,1fr) 180px; gap:12px; } }
|
|
252
|
+
@media(max-width:480px) { .appearance-row { grid-template-columns:minmax(0,1fr) auto; gap:12px; } .appearance-row:has(select) { grid-template-columns:minmax(0,1fr); } .appearance-select { width:100%; } .terminal-wide { display:none; } .terminal-compact { display:block; } .terminal-sample { padding:12px 9px; } .terminal-sample .terminal-table { font-size:11px; } }
|
|
253
|
+
@media(pointer:coarse) { .appearance-select { min-height:44px; font-size:16px; } }
|
|
254
|
+
.model-check-details { margin:14px 0; color:var(--text); }
|
|
255
|
+
.model-check-details > summary { color:var(--heading); font-size:12px; }
|
|
256
|
+
#models-note p { margin:4px 0; }
|
|
257
|
+
|
|
258
|
+
:root:not([data-theme="light"]) #animation-settings { --ansi-white:#f5fff5;--ansi-159:#9af5e9;--ansi-123:#75e4d9;--ansi-87:#5ad0d4;--ansi-51:#42b9d8;--ansi-45:#3ca2d0;--ansi-39:#4389c2;--ansi-33:#4775b2; }
|
|
259
|
+
:root:not([data-theme="light"]) #animation-settings[data-terminal-palette="klein"] { --ansi-white:#789aff;--ansi-159:#789aff;--ansi-123:#789aff;--ansi-87:#789aff;--ansi-51:#789aff;--ansi-45:#789aff;--ansi-39:#789aff;--ansi-33:#789aff; }
|
|
260
|
+
|
|
261
|
+
:root[data-theme="light"] #animation-settings { --ansi-white:#234231;--ansi-159:#116b64;--ansi-123:#0d7771;--ansi-87:#116b75;--ansi-51:#14697e;--ansi-45:#1a6183;--ansi-39:#265f8d;--ansi-33:#365a8d; }
|
|
262
|
+
:root[data-theme="light"] #animation-settings[data-terminal-palette="klein"] { --ansi-white:#002fa7;--ansi-159:#002fa7;--ansi-123:#002fa7;--ansi-87:#002fa7;--ansi-51:#002fa7;--ansi-45:#002fa7;--ansi-39:#002fa7;--ansi-33:#002fa7; }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -340,7 +340,9 @@ async function readDashboard(url, { signal, timeout = 15000, source } = {}) {
|
|
|
340
340
|
const response = await fetch(url, { cache: "no-store", headers: { "X-CCDX-Dashboard": "1", Accept: "application/json" },
|
|
341
341
|
signal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]) });
|
|
342
342
|
const data = await response.json();
|
|
343
|
-
if (!response.ok || (source && !(Array.isArray(source) ? source : [source]).includes(data.source)))
|
|
343
|
+
if (!response.ok || (source && !(Array.isArray(source) ? source : [source]).includes(data.source))) {
|
|
344
|
+
throw Object.assign(new Error(data.error || `HTTP ${response.status}`), { diagnostic: data.diagnostic });
|
|
345
|
+
}
|
|
344
346
|
return data;
|
|
345
347
|
}
|
|
346
348
|
|
|
@@ -410,11 +412,35 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
|
|
|
410
412
|
state: state => {
|
|
411
413
|
element("refresh-models").disabled = Boolean(state.pending);
|
|
412
414
|
text("models-state", state.pending ? "checking_live" : state.error ? "live_lookup_failed" : state.value?.source === "catalog" ? "catalog_snapshot" : "live_snapshot");
|
|
415
|
+
element("model-check-details").hidden = !state.error;
|
|
413
416
|
if (state.error) {
|
|
414
417
|
const message = String(state.error.message || state.error).slice(0, 240);
|
|
415
418
|
const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
|
|
416
419
|
if (httpError) text("models-note", "live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] });
|
|
417
420
|
else text("models-note", message);
|
|
421
|
+
const sourceReason = /^Model catalog unavailable \/ (m365_[a-z0-9_]+)$/.exec(message);
|
|
422
|
+
const reason = httpError ? phrase("live_model_lookup_failed_http_status_run_ccdx_models_for_details", { status: httpError[1] })
|
|
423
|
+
: sourceReason ? phrase("source_catalog_unavailable", { code: sourceReason[1] }) : phrase(message);
|
|
424
|
+
const source = providerEntries.find(entry => entry.id === selectedProvider)?.name || selectedProvider;
|
|
425
|
+
const previous = modelSnapshots.get(selectedProvider);
|
|
426
|
+
element("models-note").replaceChildren();
|
|
427
|
+
const summary = document.createElement("span"), kept = document.createElement("span");
|
|
428
|
+
localize(summary, "source_check_failed", { source });
|
|
429
|
+
localize(kept, previous?.checked_at ? "source_check_previous" : "source_check_none", { time: previous?.checked_at ? new Date(previous.checked_at).toLocaleTimeString() : "" });
|
|
430
|
+
element("models-note").append(summary, document.createElement("br"), kept);
|
|
431
|
+
const fields = element("model-check-fields");fields.replaceChildren();
|
|
432
|
+
const diagnostic = state.error.diagnostic || {};
|
|
433
|
+
for (const [key, value] of [["source", source], ["source_check_time", diagnostic.checked_at], ["source_check_reason", reason], ["http_status", diagnostic.http_status]]) {
|
|
434
|
+
if (value === null || value === undefined || value === "") continue;
|
|
435
|
+
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);
|
|
436
|
+
if (value?.key) localize(detail, value.key, value.values);else detail.textContent = String(value).slice(0, 300);
|
|
437
|
+
fields.append(term, detail);
|
|
438
|
+
}
|
|
439
|
+
if (Number.isFinite(diagnostic.retry_after_ms) && diagnostic.retry_after_ms > 0) {
|
|
440
|
+
const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, "retry");
|
|
441
|
+
const checked = Date.parse(diagnostic.checked_at);
|
|
442
|
+
if (Number.isFinite(checked)) { localize(detail, "source_retry_time", { time: new Date(checked + diagnostic.retry_after_ms).toLocaleTimeString() });fields.append(term, detail); }
|
|
443
|
+
}
|
|
418
444
|
}
|
|
419
445
|
if (state.error && !modelSnapshots.has(selectedProvider)) emptyTable("live-models-body", 6, "no_catalog_available");
|
|
420
446
|
for (const node of timestamps.get("models")) refreshTime(node, state);
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -142,6 +142,7 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
142
142
|
authStatusFn = () => authStatus({ home }),
|
|
143
143
|
providerCatalogFn,
|
|
144
144
|
providerStateFn,
|
|
145
|
+
providerAccountsFn,
|
|
145
146
|
serviceControl,
|
|
146
147
|
applyAnimation,
|
|
147
148
|
} = {}) {
|
|
@@ -162,6 +163,15 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
162
163
|
return;
|
|
163
164
|
}
|
|
164
165
|
|
|
166
|
+
if (pathname === "/_ccdx/ui/m365/accounts" && req.method === "GET") {
|
|
167
|
+
if (!providerAccountsFn) { sendJson(res, 503, { error: "Account selection requires the updated running service" });return; }
|
|
168
|
+
try {
|
|
169
|
+
const result = await providerAccountsFn();
|
|
170
|
+
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 })) });
|
|
171
|
+
} 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" }); }
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
|
|
165
175
|
if (pathname === "/_ccdx/ui/settings") {
|
|
166
176
|
if (!serviceControl) { sendJson(res, 503, { error: "Settings require the running service; restart the updated CCDX" });return; }
|
|
167
177
|
if (req.method === "GET") {
|
|
@@ -177,7 +187,8 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
177
187
|
abort.clearTimeout();const data = await serviceControl.action(input);
|
|
178
188
|
if (!res.destroyed && !res.writableEnded) sendJson(res, 200, data);
|
|
179
189
|
} catch (error) {
|
|
180
|
-
sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300)
|
|
190
|
+
sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300),
|
|
191
|
+
...(/^m365_[a-z_]+$/.test(error.code || "") ? { code: error.code } : {}) });
|
|
181
192
|
} finally { abort.cleanup(); }
|
|
182
193
|
return;
|
|
183
194
|
}
|
|
@@ -249,8 +260,8 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
249
260
|
|
|
250
261
|
if (pathname === MODELS_PATH && req.method === "GET") {
|
|
251
262
|
const abort = createRequestAbort(req, res);
|
|
263
|
+
const provider = new URL(req.url, "http://localhost").searchParams.get("provider") || "";
|
|
252
264
|
try {
|
|
253
|
-
const provider = new URL(req.url, "http://localhost").searchParams.get("provider") || "";
|
|
254
265
|
if (provider && (!isProviderId(provider) || !dashboardProviders(providerStateFn, authStatusFn).some(entry => entry.id === provider))) {
|
|
255
266
|
sendJson(res, 400, { error: "Select a registered provider" });return;
|
|
256
267
|
}
|
|
@@ -280,7 +291,11 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
280
291
|
})),
|
|
281
292
|
});
|
|
282
293
|
} catch (error) {
|
|
283
|
-
|
|
294
|
+
const message = /^m365_[a-z0-9_]+$/.test(error.code || "") ? `Model catalog unavailable / ${error.code}` : liveModelError(error);
|
|
295
|
+
if (!res.destroyed && !res.writableEnded) sendJson(res, error.statusCode || 502, { error: message,
|
|
296
|
+
diagnostic: { provider: provider || null, checked_at: new Date().toISOString(), message,
|
|
297
|
+
http_status: Number(/\bHTTP (\d{3})\b/.exec(message)?.[1]) || finite(error.statusCode),
|
|
298
|
+
retry_after_ms: finite(error.retryAfterMs) } });
|
|
284
299
|
} finally { abort.cleanup(); }
|
|
285
300
|
return;
|
|
286
301
|
}
|
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
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"]);
|
|
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"]);
|
|
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
|
+
}
|