codex-copilot-dx 0.9.41 → 0.10.1
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 +23 -2
- package/bin/cli.mjs +38 -11
- package/docs/ARCHITECTURE.md +62 -8
- package/docs/REFERENCE.md +161 -4
- package/package.json +4 -1
- package/src/adapter.mjs +83 -22
- package/src/auto-review-model.mjs +4 -3
- package/src/claude-client-config.mjs +217 -0
- package/src/claude-gateway.mjs +163 -0
- package/src/cli-m365.mjs +133 -0
- package/src/cli-models.mjs +1 -1
- package/src/cli-options.mjs +20 -6
- package/src/cli-status.mjs +6 -0
- package/src/codex-model-catalog.mjs +7 -2
- package/src/copilot-responses-policy.mjs +2 -64
- package/src/dashboard/index.html +11 -1
- package/src/dashboard/language.js +26 -0
- package/src/dashboard/status.js +16 -2
- package/src/dashboard/ui.css +2 -2
- package/src/dashboard/ui.js +16 -7
- package/src/dashboard/usage.js +3 -1
- package/src/dashboard-api.mjs +10 -7
- package/src/doctor-repair.mjs +2 -0
- package/src/doctor.mjs +18 -2
- package/src/m365-settings.mjs +89 -0
- package/src/native-prediction-windows.mjs +2 -7
- package/src/profile-model-runtime.mjs +4 -2
- package/src/provider-management.mjs +28 -0
- package/src/provider-runtime.mjs +180 -0
- package/src/provider-settings.mjs +32 -0
- package/src/providers/github.mjs +62 -0
- package/src/providers/m365-auth-helper.mjs +72 -0
- package/src/providers/m365-auth.mjs +105 -0
- package/src/providers/m365-messages-policy.mjs +20 -0
- package/src/providers/m365-network.mjs +73 -0
- package/src/providers/m365.mjs +238 -0
- package/src/response-failures.mjs +4 -2
- package/src/response-history.mjs +20 -3
- package/src/responses-handler.mjs +40 -95
- package/src/responses-image-tools.mjs +61 -0
- package/src/responses-proxy.mjs +5 -5
- package/src/responses-request.mjs +25 -0
- package/src/stream-performance.mjs +7 -4
- package/src/usage-analysis.mjs +3 -2
- package/src/usage-store.mjs +41 -12
- package/src/usage.mjs +8 -2
- package/src/windows-http-network.mjs +122 -0
- package/src/windows-prediction-network.cs +13 -6
- package/src/windows-prediction-network.mjs +4 -108
- package/src/windows-process.mjs +8 -0
package/src/dashboard-api.mjs
CHANGED
|
@@ -114,6 +114,7 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
114
114
|
liveModelsFn = options => fetchLiveCopilotModels({ home, ...options }),
|
|
115
115
|
usageSummaryFn,
|
|
116
116
|
authStatusFn = () => authStatus({ home }),
|
|
117
|
+
providerCatalogFn,
|
|
117
118
|
} = {}) {
|
|
118
119
|
if (!isLoopbackAddress(req.socket?.remoteAddress)
|
|
119
120
|
|| req.headers?.host === undefined
|
|
@@ -193,21 +194,21 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
193
194
|
if (pathname === MODELS_PATH && req.method === "GET") {
|
|
194
195
|
const abort = createRequestAbort(req, res);
|
|
195
196
|
try {
|
|
196
|
-
const catalog = await liveModelsFn({ signal: abort.signal });
|
|
197
|
+
const catalog = providerCatalogFn?.() || await liveModelsFn({ signal: abort.signal });
|
|
197
198
|
if (!Array.isArray(catalog?.models) || !Number.isFinite(catalog?.advertised)) {
|
|
198
199
|
throw new Error("Invalid live model catalog");
|
|
199
200
|
}
|
|
200
201
|
const models = catalog.models;
|
|
201
202
|
sendJson(res, 200, {
|
|
202
|
-
source: "live",
|
|
203
|
-
checked_at: new Date().toISOString(),
|
|
203
|
+
source: catalog.source === "catalog" ? "catalog" : "live",
|
|
204
|
+
checked_at: catalog.source === "catalog" ? catalog.checkedAt : new Date().toISOString(),
|
|
204
205
|
upstream_host: safeText(catalog?.upstreamHost || "GitHub Copilot", 120),
|
|
205
206
|
advertised: finite(catalog?.advertised),
|
|
206
207
|
selectable: models.length,
|
|
207
208
|
models: models.slice(0, 500).map((model) => ({
|
|
208
209
|
id: safeText(model.id, 100),
|
|
209
210
|
vendor: safeText(model.vendor, 80),
|
|
210
|
-
endpoints: Array.isArray(model.endpoints) ? model.endpoints.filter((value) =>
|
|
211
|
+
endpoints: Array.isArray(model.endpoints) ? model.endpoints.filter((value) => ["responses", "chat", "messages"].includes(value)) : [],
|
|
211
212
|
preview: model.preview === true,
|
|
212
213
|
})),
|
|
213
214
|
});
|
|
@@ -219,6 +220,8 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
219
220
|
|
|
220
221
|
if (pathname === USAGE_PATH && req.method === "GET") {
|
|
221
222
|
const query = new URL(req.url, "http://localhost").searchParams;
|
|
223
|
+
const provider = query.get("provider") || "";
|
|
224
|
+
if (provider && !["github", "m365"].includes(provider)) { sendJson(res, 400, { error: "Select GitHub or Microsoft 365" });return; }
|
|
222
225
|
let analytics = null;
|
|
223
226
|
if (query.get("analytics") === "1") {
|
|
224
227
|
try {
|
|
@@ -232,9 +235,9 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
232
235
|
}
|
|
233
236
|
try {
|
|
234
237
|
const analysis = analytics && !usageSummaryFn
|
|
235
|
-
? await analyzeUsageLogs(undefined, { timeZone: query.get("time_zone") || "UTC" }) : null;
|
|
236
|
-
const summary = analysis?.summary || await (usageSummaryFn || (options => summarizeUsageLogs(undefined, options)))(analytics ? { onRecord: analytics.record } :
|
|
237
|
-
sendJson(res, 200, { source: "local_usage_log", ...usageTable(summary), ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
|
|
238
|
+
? await analyzeUsageLogs(undefined, { timeZone: query.get("time_zone") || "UTC", provider }) : null;
|
|
239
|
+
const summary = analysis?.summary || await (usageSummaryFn || (options => summarizeUsageLogs(undefined, options)))({ provider, ...(analytics ? { onRecord: analytics.record } : {}) });
|
|
240
|
+
sendJson(res, 200, { source: "local_usage_log", provider: provider || "all", providers: summary.providers, ...usageTable(summary), ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
|
|
238
241
|
} catch {
|
|
239
242
|
sendJson(res, 500, { error: "Could not read local usage summary" });
|
|
240
243
|
}
|
package/src/doctor-repair.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { readSavedGithubToken } from "./auth-credentials.mjs";
|
|
|
4
4
|
import { importDiscoveredGithubToken } from "./auth.mjs";
|
|
5
5
|
import { readPredictionSettings } from "./native-prediction-profile.mjs";
|
|
6
6
|
import { requestPredictionFix } from "./native-prediction-fix.mjs";
|
|
7
|
+
import { readProviderSettings } from "./provider-settings.mjs";
|
|
7
8
|
|
|
8
9
|
// Explicit invocation only. One repair and one affected recheck per operation.
|
|
9
10
|
export async function repairDoctor({ home, env = process.env, host, port, platform = process.platform, fetchImpl = fetch,
|
|
@@ -31,6 +32,7 @@ export async function repairDoctor({ home, env = process.env, host, port, platfo
|
|
|
31
32
|
: "Codex configuration preserved; review invalid or custom settings manually" };
|
|
32
33
|
});
|
|
33
34
|
await run("github-auth", async () => {
|
|
35
|
+
if (readProviderSettings({ home, env }).codex === "m365") return { kind: "info", result: "preserved_existing", message: "GitHub credentials preserved; Codex currently uses Microsoft 365" };
|
|
34
36
|
if (savedToken(home)) return { kind: "info", result: "preserved_existing", message: "Saved GitHub credential retained; use doctor --online to verify access" };
|
|
35
37
|
const imported = await importToken({ home, env, fetchImpl, log: () => {} });
|
|
36
38
|
const verified = imported?.ok && Boolean(savedToken(home));
|
package/src/doctor.mjs
CHANGED
|
@@ -22,6 +22,7 @@ import { inspectPredictionEnvironment } from "./native-prediction-environment.mj
|
|
|
22
22
|
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
23
23
|
import { readImageProviderConfig } from "./image-provider-config.mjs";
|
|
24
24
|
import { inspectAdapterCompatibility } from "./doctor-compat.mjs";
|
|
25
|
+
import { readProviderSettings } from "./provider-settings.mjs";
|
|
25
26
|
export { selectCompatibilityModels, inspectAdapterCompatibility } from "./doctor-compat.mjs";
|
|
26
27
|
|
|
27
28
|
export { inspectCodexConfig };
|
|
@@ -196,14 +197,20 @@ export async function collectDoctorChecks({
|
|
|
196
197
|
readPredictionSettingsFn = readPredictionSettings,
|
|
197
198
|
inspectPredictionEnvironmentFn = inspectPredictionEnvironment,
|
|
198
199
|
readImageProviderConfigFn = readImageProviderConfig,
|
|
200
|
+
providerControlFn,
|
|
199
201
|
} = {}) {
|
|
200
202
|
if (configOnly) return inspectCodexConfig({ home, env, host, port });
|
|
201
203
|
checkedDoctorProfile(profile);
|
|
204
|
+
let source = "github", sourceError = null;
|
|
205
|
+
try { source = readProviderSettings({ home, env }).codex; } catch (error) { sourceError = error.message; }
|
|
202
206
|
const checks = [
|
|
203
|
-
...inspectAuthProfiles({ home }).map(check => ({ ...check, id: "github-auth"
|
|
207
|
+
...inspectAuthProfiles({ home }).map(check => ({ ...check, id: "github-auth",
|
|
208
|
+
...(source === "m365" ? { kind: "info", message: `Inactive GitHub provider: ${check.message}` } : {}) })),
|
|
204
209
|
...inspectCodexConfig({ home, env, host, port }).map(check => ({ ...check, id: "codex-config" })),
|
|
205
210
|
{ kind: "info", message: `Runtime: Node ${process.version}, ${platform}/${process.arch}` },
|
|
206
211
|
];
|
|
212
|
+
if (sourceError) checks.push({ kind: "err", id: "provider", message: sourceError });
|
|
213
|
+
else if (source === "m365") checks.push({ kind: "info", id: "provider", message: "Codex provider: Microsoft 365; GitHub credentials are retained independently" });
|
|
207
214
|
if (platform === "win32") {
|
|
208
215
|
const command = inspectWindowsCommandFn({ platform });
|
|
209
216
|
checks.push({ kind: command.status === "ready" ? "ok" : ["checkout", "not_applicable"].includes(command.status) ? "info" : "warn", id: "windows-command",
|
|
@@ -237,7 +244,16 @@ export async function collectDoctorChecks({
|
|
|
237
244
|
}
|
|
238
245
|
|
|
239
246
|
if (online) {
|
|
240
|
-
|
|
247
|
+
if (source === "m365") {
|
|
248
|
+
try {
|
|
249
|
+
const control = providerControlFn || (await import("./cli-m365.mjs")).providerControl;
|
|
250
|
+
const result = await control({ host, port, fetchImpl, action: { action: "models", family: "gpt" }, timeoutMs: onlineTimeoutMs });
|
|
251
|
+
const ready = result.state?.m365?.state === "ready" && result.models?.length > 0;
|
|
252
|
+
checks.push({ kind: ready ? "ok" : "warn", id: "provider", message: ready
|
|
253
|
+
? `Microsoft 365 is ready; ${result.models.length} GPT models available`
|
|
254
|
+
: "Microsoft 365 is not ready; inspect ccdx m365 status. No GitHub fallback was selected" });
|
|
255
|
+
} catch { checks.push({ kind: "warn", id: "provider", message: "Microsoft 365 could not be checked through the running adapter; start ccdx and inspect ccdx m365 status" }); }
|
|
256
|
+
} else if (!sourceError) checks.push(...await inspectAuthProfilesOnline({
|
|
241
257
|
home,
|
|
242
258
|
profile,
|
|
243
259
|
fetchImpl,
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
6
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
7
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
8
|
+
|
|
9
|
+
export const M365_GATEWAY_PORT = 2027;
|
|
10
|
+
|
|
11
|
+
export function m365Paths({ home = os.homedir() } = {}) {
|
|
12
|
+
const directory = path.join(home, ".local", "share", "codex-copilot-dx", "profiles", "m365");
|
|
13
|
+
return { directory, settings: path.join(directory, "settings.json"), account: path.join(directory, "account.json"),
|
|
14
|
+
catalog: path.join(directory, "models.json"), gateway: path.join(directory, "gateway.json"),
|
|
15
|
+
ownership: path.join(directory, "client-config.json") };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function readM365Json(file, fallback = null) {
|
|
19
|
+
try {
|
|
20
|
+
if (!fs.lstatSync(file).isFile()) throw Error("Expected a regular file");
|
|
21
|
+
const value = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 4 * 1024 * 1024 }));
|
|
22
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("Expected an object");
|
|
23
|
+
return value;
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (error.code === "ENOENT") return fallback;
|
|
26
|
+
throw Object.assign(new Error("M365 local configuration could not be read; existing files were preserved"), { code: "m365_config_invalid" });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function writeM365Json(file, value) {
|
|
31
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
32
|
+
try { if (!fs.lstatSync(file).isFile()) throw Error("M365 configuration target is not a regular file"); }
|
|
33
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
34
|
+
const changed = atomicWriteFileIfChangedSync(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, preserveMode: false });
|
|
35
|
+
if (process.platform !== "win32") fs.chmodSync(file, 0o600);
|
|
36
|
+
return changed;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function validateSettings(value) {
|
|
40
|
+
if (value.enabled !== undefined && typeof value.enabled !== "boolean") {
|
|
41
|
+
throw Object.assign(new Error("M365 settings are invalid; existing settings were preserved"), { code: "m365_config_invalid" });
|
|
42
|
+
}
|
|
43
|
+
return { ...value, enabled: value.enabled !== false };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function readM365Settings(options = {}) {
|
|
47
|
+
return validateSettings(readM365Json(m365Paths(options).settings, {}));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function updateM365Settings(update, options = {}) {
|
|
51
|
+
const file = m365Paths(options).settings;
|
|
52
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
53
|
+
return withFileLockSync(`${file}.lock`, () => {
|
|
54
|
+
const current = readM365Settings(options), next = validateSettings({ ...current, ...update });
|
|
55
|
+
writeM365Json(file, next);
|
|
56
|
+
return next;
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function m365AccountKey(account) {
|
|
61
|
+
if (!account || typeof account.id !== "string" || !account.id || account.id.length > 512
|
|
62
|
+
|| typeof account.tenant !== "string" || !account.tenant || account.tenant.length > 128
|
|
63
|
+
|| typeof account.login !== "string" || !account.login || account.login.length > 320
|
|
64
|
+
|| /[\u0000-\u0020\u007f]/.test(account.id + account.tenant + account.login)) {
|
|
65
|
+
throw Object.assign(new Error("M365 account identity is unavailable"), { code: "m365_account_invalid" });
|
|
66
|
+
}
|
|
67
|
+
return createHash("sha256").update(`${account.tenant}\0${account.id}`).digest("hex");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function readM365Account(options = {}) {
|
|
71
|
+
const account = readM365Json(m365Paths(options).account);
|
|
72
|
+
if (account) m365AccountKey(account);
|
|
73
|
+
return account;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function ensureM365GatewayKey(options = {}) {
|
|
77
|
+
const file = m365Paths(options).gateway;
|
|
78
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
79
|
+
return withFileLockSync(`${file}.lock`, () => {
|
|
80
|
+
const saved = readM365Json(file);
|
|
81
|
+
if (saved) {
|
|
82
|
+
if (!/^ccdx_m365_[a-f0-9]{64}$/.test(saved.key || "")) throw Object.assign(new Error("M365 gateway key is invalid; it was preserved"), { code: "m365_gateway_key_invalid" });
|
|
83
|
+
return saved.key;
|
|
84
|
+
}
|
|
85
|
+
const key = `ccdx_m365_${randomBytes(32).toString("hex")}`;
|
|
86
|
+
writeM365Json(file, { key });
|
|
87
|
+
return key;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
@@ -1,17 +1,12 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { windowsPowerShellEnvironment } from "./windows-process.mjs";
|
|
5
|
+
export { windowsPowerShellEnvironment } from "./windows-process.mjs";
|
|
4
6
|
|
|
5
7
|
const WINDOWS_PUBLISHER = "CN=50BDFD77-8903-4850-9FFE-6E8522F64D5B";
|
|
6
8
|
const WINDOWS_PACKAGE_FAMILY = "OpenAI.Codex_2p2nqsd0c76g0";
|
|
7
9
|
|
|
8
|
-
export function windowsPowerShellEnvironment(env = process.env) {
|
|
9
|
-
// PowerShell 7 can export a Core-only PSModulePath. Prefer the bundled
|
|
10
|
-
// Windows PowerShell modules for this child, retaining user module paths.
|
|
11
|
-
const modules = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "Modules");
|
|
12
|
-
return { ...env, PSModulePath: [modules, env.PSModulePath].filter(Boolean).join(";") };
|
|
13
|
-
}
|
|
14
|
-
|
|
15
10
|
function powershell(script, { env = process.env, exec = execFileSync, ...options } = {}) {
|
|
16
11
|
const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
17
12
|
try {
|
|
@@ -73,6 +73,8 @@ export function createProfileModelRuntime({
|
|
|
73
73
|
: DEFAULT_TIMEOUT_MS;
|
|
74
74
|
let refreshFlight = null;
|
|
75
75
|
let refreshGeneration = 0;
|
|
76
|
+
const credentialFingerprint = () => String((typeof codexCredentialFingerprint === "function"
|
|
77
|
+
? codexCredentialFingerprint() : codexCredentialFingerprint) || "").trim();
|
|
76
78
|
|
|
77
79
|
function emit(kind, message) {
|
|
78
80
|
if (typeof log === "function") log(kind, message);
|
|
@@ -90,7 +92,7 @@ export function createProfileModelRuntime({
|
|
|
90
92
|
const cached = loadModelCacheEntry({
|
|
91
93
|
home,
|
|
92
94
|
profile: "codex",
|
|
93
|
-
credentialFingerprint:
|
|
95
|
+
credentialFingerprint: credentialFingerprint(),
|
|
94
96
|
});
|
|
95
97
|
if (!cached) return false;
|
|
96
98
|
try {
|
|
@@ -133,7 +135,7 @@ export function createProfileModelRuntime({
|
|
|
133
135
|
const saved = saveModelCache(models, {
|
|
134
136
|
home,
|
|
135
137
|
profile: "codex",
|
|
136
|
-
credentialFingerprint:
|
|
138
|
+
credentialFingerprint: credentialFingerprint(),
|
|
137
139
|
isCurrent: () => refreshGeneration === generation,
|
|
138
140
|
});
|
|
139
141
|
if (saved) {
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
|
|
2
|
+
import { createRequestAbort, readJsonBody, sendJsonError } from "./http-transport.mjs";
|
|
3
|
+
import { httpError } from "./http-errors.mjs";
|
|
4
|
+
|
|
5
|
+
export const PROVIDER_MANAGEMENT_PATH = "/_ccdx/providers";
|
|
6
|
+
export async function handleProviderManagement(req, res, runtime) {
|
|
7
|
+
if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers?.host === undefined || !isLoopbackHostHeader(req.headers.host)
|
|
8
|
+
|| Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Provider management requires a native loopback client", 403));return; }
|
|
9
|
+
if (!runtime) { sendJsonError(res, httpError("This service does not support provider management; restart the updated CCDX service", 503));return; }
|
|
10
|
+
if (req.method === "GET") {
|
|
11
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(runtime.snapshot()));return;
|
|
12
|
+
}
|
|
13
|
+
if (req.method !== "POST") { sendJsonError(res, httpError("Provider changes require POST", 405));return; }
|
|
14
|
+
if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { sendJsonError(res, httpError("Expected application/json", 415));return; }
|
|
15
|
+
const abort = createRequestAbort(req, res);abort.setTimeout(2000, "request_body_timeout");
|
|
16
|
+
try {
|
|
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"]);
|
|
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);
|
|
21
|
+
if (input.effort !== undefined && input.effort !== null && (typeof input.effort !== "string" || input.effort.length > 16)) throw httpError("Invalid reasoning effort", 400);
|
|
22
|
+
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
|
+
abort.clearTimeout();
|
|
24
|
+
const result = await runtime.action(input);
|
|
25
|
+
if (!res.destroyed && !res.writableEnded) { res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(result)); }
|
|
26
|
+
} catch (error) { sendJsonError(res, error, error.statusCode || 503); }
|
|
27
|
+
finally { abort.cleanup(); }
|
|
28
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { createGithubProvider } from "./providers/github.mjs";
|
|
3
|
+
import { readProviderSettings, writeProviderSettings } from "./provider-settings.mjs";
|
|
4
|
+
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey, M365_GATEWAY_PORT } from "./m365-settings.mjs";
|
|
5
|
+
|
|
6
|
+
const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
|
|
7
|
+
{ code: reason, statusCode: 503 });
|
|
8
|
+
|
|
9
|
+
// Composition owns source selection. Providers never modify Codex, prediction,
|
|
10
|
+
// image configuration or each other's credentials.
|
|
11
|
+
export function createProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", home, env = process.env, platform = process.platform,
|
|
12
|
+
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients } = {}) {
|
|
13
|
+
const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
|
|
14
|
+
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
15
|
+
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
16
|
+
let selection = readProviderSettings(options), m365 = null, gateway = null, pending = null, closed = false, serial = null;
|
|
17
|
+
let reason = null, claudeReason = null, clients = { code: "not_configured", app: "not_configured" }, lastClients = {};
|
|
18
|
+
const sessions = new Map();let priorNamespace = null, requestOrder = 0, activeM365Requests = 0;
|
|
19
|
+
let enabled;
|
|
20
|
+
try { enabled = readM365Settings(options).enabled && env.CCDX_M365 !== "0"; }
|
|
21
|
+
catch { enabled = false;reason = "m365_config_invalid"; }
|
|
22
|
+
|
|
23
|
+
async function startM365(forceRefresh = false) {
|
|
24
|
+
if (closed || !enabled || !["darwin", "win32"].includes(platform)) return null;
|
|
25
|
+
if (pending) return pending;
|
|
26
|
+
if (!forceRefresh && m365?.snapshot().state === "ready") return m365;
|
|
27
|
+
const operation = (async () => {
|
|
28
|
+
if (!m365) {
|
|
29
|
+
const factory = createM365 || (await import("./providers/m365.mjs")).createM365Provider;
|
|
30
|
+
if (closed || !enabled) return null;
|
|
31
|
+
m365 = factory({ home, env, log });
|
|
32
|
+
}
|
|
33
|
+
await m365.refresh();if (closed || !enabled) return null;
|
|
34
|
+
const claudeModels = m365.models("claude");
|
|
35
|
+
claudeReason = !claudeModels.length ? "m365_no_claude_models" : corePort === M365_GATEWAY_PORT ? "m365_gateway_core_port_conflict" : null;
|
|
36
|
+
if (claudeReason === "m365_gateway_core_port_conflict") log("warn", `Claude gateway skipped: port ${M365_GATEWAY_PORT} belongs to the configured core service; M365 GPT routing remains available`);
|
|
37
|
+
if (claudeModels.length && !claudeReason) try {
|
|
38
|
+
const apiKey = ensureM365GatewayKey(options);
|
|
39
|
+
if (!gateway) {
|
|
40
|
+
const start = startGateway || (await import("./claude-gateway.mjs")).startClaudeGateway;
|
|
41
|
+
const opened = await start({ provider: m365, apiKey, env, log,
|
|
42
|
+
onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
|
|
43
|
+
if (closed || !enabled) { await opened.close();return null; }
|
|
44
|
+
gateway = opened;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const integration = configureClients ? null : await import("./claude-client-config.mjs");
|
|
48
|
+
const configure = configureClients || integration.configureClaudeClients;
|
|
49
|
+
const desktopManaged = integration ? await integration.inspectClaudeDesktopPolicy(options) : false;
|
|
50
|
+
if (closed || !enabled) return null;
|
|
51
|
+
clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${gateway.port}`, apiKey, models: claudeModels });
|
|
52
|
+
} catch { clients = { code: "configuration_unavailable", app: "configuration_unavailable" };claudeReason = "m365_claude_config_unavailable"; }
|
|
53
|
+
} catch (error) {
|
|
54
|
+
claudeReason = error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_claude_setup_unavailable";
|
|
55
|
+
log("warn", `Claude setup unavailable: ${claudeReason}; M365 GPT routing is independent`);
|
|
56
|
+
}
|
|
57
|
+
reason = null;log("ok", `Microsoft 365 ready: ${claudeModels.length} Claude, ${m365.models("gpt").length} GPT models${gateway ? `; Claude gateway at http://127.0.0.1:${gateway.port}` : ""}`);
|
|
58
|
+
return m365;
|
|
59
|
+
})().catch(error => {
|
|
60
|
+
reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_unavailable";
|
|
61
|
+
log("info", `Microsoft 365 unavailable: ${reason}`);return null;
|
|
62
|
+
}).finally(() => { if (pending === operation) pending = null; });
|
|
63
|
+
pending = operation;return operation;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const snapshot = () => ({ codex_provider: selection.codex,
|
|
67
|
+
github: { state: "configured", profile: "codex" },
|
|
68
|
+
m365: { ...(m365?.snapshot() || {}), enabled, state: !enabled ? "disabled" : pending ? "checking"
|
|
69
|
+
: !["darwin", "win32"].includes(platform) ? "unsupported" : m365?.snapshot().state || (reason ? "unavailable" : "idle"),
|
|
70
|
+
reason: reason || m365?.snapshot().reason || null,
|
|
71
|
+
preference: selection.m365 || null,
|
|
72
|
+
active_requests: activeM365Requests,
|
|
73
|
+
claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway?.port || null, clients: { ...clients },
|
|
74
|
+
observed_clients: { ...lastClients }, requests: gateway?.snapshot?.() || null } } });
|
|
75
|
+
|
|
76
|
+
function current() {
|
|
77
|
+
if (selection.codex === "github") return github;
|
|
78
|
+
if (!m365 || !enabled || m365.snapshot().state === "disabled") throw unavailable(reason || "m365_not_ready");
|
|
79
|
+
return m365;
|
|
80
|
+
}
|
|
81
|
+
const serialize = task => {
|
|
82
|
+
const next = (serial || Promise.resolve()).then(task);
|
|
83
|
+
serial = next.catch(() => {});return next;
|
|
84
|
+
};
|
|
85
|
+
async function switchSource(provider, preference) {
|
|
86
|
+
if (!["github", "m365"].includes(provider)) throw new Error("Provider must be github or m365");
|
|
87
|
+
if (provider === "m365") {
|
|
88
|
+
if (!enabled) throw unavailable("m365_disabled");
|
|
89
|
+
const ready = await startM365();if (!ready) throw unavailable(reason || "m365_not_ready");
|
|
90
|
+
const ids = new Set(m365.models("gpt").map(model => model.id));
|
|
91
|
+
if (!preference || !ids.has(preference.model) || !ids.has(preference.auto_review_model)) {
|
|
92
|
+
throw Object.assign(new Error("Choose available M365 GPT and auto-review models before switching"), { code: "m365_model_selection_required", statusCode: 400 });
|
|
93
|
+
}
|
|
94
|
+
if (!m365.models("gpt").find(model => model.id === preference.auto_review_model)?.capabilities?.supports?.reasoning_effort?.includes("low")) {
|
|
95
|
+
throw Object.assign(new Error("Choose an M365 Auto-review model that advertises low reasoning"), { code: "m365_review_effort_unavailable", statusCode: 400 });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (closed) throw unavailable("m365_runtime_closed");
|
|
99
|
+
let previous;try { previous = current().profileId(); } catch {}
|
|
100
|
+
const next = writeProviderSettings(provider, preference, options);
|
|
101
|
+
if (selection.codex !== provider) priorNamespace = previous || null;
|
|
102
|
+
selection = next;return snapshot();
|
|
103
|
+
}
|
|
104
|
+
async function disable(remove) {
|
|
105
|
+
if (remove && (activeM365Requests > 0 || gateway?.snapshot?.().active > 0)) {
|
|
106
|
+
throw Object.assign(new Error("Microsoft 365 requests are active; finish them before removing its profile"), { code: "m365_profile_busy", statusCode: 409 });
|
|
107
|
+
}
|
|
108
|
+
await switchSource("github");
|
|
109
|
+
updateM365Settings({ enabled: false }, options);enabled = false;
|
|
110
|
+
m365?.close();await gateway?.close();gateway = null;
|
|
111
|
+
await pending;m365 = null;
|
|
112
|
+
const restore = restoreClients || (await import("./claude-client-config.mjs")).restoreClaudeClients;
|
|
113
|
+
const result = restore(options);clients = { code: result.preserved ? "preserved" : "restored", app: result.preserved ? "preserved" : "restored" };
|
|
114
|
+
if (remove) {
|
|
115
|
+
if (result.remaining) throw Object.assign(new Error("User-modified Claude settings were preserved; M365 profile cleanup is incomplete"), { code: "m365_cleanup_preserved" });
|
|
116
|
+
const paths = m365Paths(options);
|
|
117
|
+
for (const file of [paths.account, paths.catalog, paths.gateway, paths.ownership]) {
|
|
118
|
+
try { if (!fs.lstatSync(file).isFile()) throw Error();fs.unlinkSync(file); }
|
|
119
|
+
catch (error) { if (error.code !== "ENOENT") throw new Error("M365 cleanup preserved an unexpected file"); }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return snapshot();
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
github, current, snapshot, start: startM365, refresh: () => startM365(true),
|
|
126
|
+
selection: () => selection,
|
|
127
|
+
dashboardCatalog() {
|
|
128
|
+
if (selection.codex !== "m365") return null;
|
|
129
|
+
const models = [...(m365?.models("gpt") || []), ...(m365?.models("claude") || [])];
|
|
130
|
+
return { source: "catalog", checkedAt: m365?.snapshot().models.refreshed_at || null,
|
|
131
|
+
upstreamHost: "Microsoft 365", advertised: models.length,
|
|
132
|
+
models: models.map(model => ({ id: model.id, vendor: model.publisher,
|
|
133
|
+
endpoints: model.supported_endpoints.includes("/v1/messages") ? ["messages"] : ["responses"], preview: false })) };
|
|
134
|
+
},
|
|
135
|
+
track(target) {
|
|
136
|
+
if (target.id !== "m365") return undefined;
|
|
137
|
+
activeM365Requests++;let finished = false;
|
|
138
|
+
return () => { if (!finished) { finished = true;activeM365Requests--; } };
|
|
139
|
+
},
|
|
140
|
+
historyContext(headers, target) {
|
|
141
|
+
const namespace = target.profileId(), raw = headers.session_id || headers["session-id"];
|
|
142
|
+
// Internal bounded correlation only; IDs are never exposed or persisted.
|
|
143
|
+
const key = typeof raw === "string" && raw.length <= 512 ? raw : null;
|
|
144
|
+
const previous = key && sessions.get(key)?.namespace || priorNamespace, order = ++requestOrder;
|
|
145
|
+
return { historyNamespace: namespace, historyTransferNamespace: previous && previous !== namespace ? previous : undefined,
|
|
146
|
+
onHistoryStored() {
|
|
147
|
+
if (!key) return;
|
|
148
|
+
const record = sessions.get(key);
|
|
149
|
+
if (record?.order > order) return;
|
|
150
|
+
if (record) { record.namespace = namespace;record.order = order; }
|
|
151
|
+
sessions.delete(key);sessions.set(key, record || { namespace, order });
|
|
152
|
+
while (sessions.size > 1024) sessions.delete(sessions.keys().next().value);
|
|
153
|
+
} };
|
|
154
|
+
},
|
|
155
|
+
async action(input) {
|
|
156
|
+
return serialize(async () => {
|
|
157
|
+
if (closed) throw unavailable("m365_runtime_closed");
|
|
158
|
+
if (input.action === "models") { await startM365();return { state: snapshot(), models: m365?.models(input.family === "claude" ? "claude" : "gpt") || [] }; }
|
|
159
|
+
if (input.action === "auto-review") {
|
|
160
|
+
if (selection.codex !== "m365" || !m365) throw unavailable("m365_not_selected");
|
|
161
|
+
const model = m365.models("gpt").find(model => model.id === input.model);
|
|
162
|
+
if (!model || input.effort !== null && !model.capabilities?.supports?.reasoning_effort?.includes(input.effort)) {
|
|
163
|
+
throw Object.assign(new Error("The selected M365 review model or effort is not available"), { statusCode: 400, code: "m365_review_effort_unavailable" });
|
|
164
|
+
}
|
|
165
|
+
const preference = { ...selection.m365, auto_review_model: input.model, auto_review_effort: input.effort };
|
|
166
|
+
const changed = JSON.stringify(preference) !== JSON.stringify(selection.m365);
|
|
167
|
+
selection = writeProviderSettings("m365", preference, options);return { changed, ...snapshot() };
|
|
168
|
+
}
|
|
169
|
+
if (input.action === "switch") return switchSource(input.provider, { model: input.model, auto_review_model: input.auto_review_model });
|
|
170
|
+
if (input.action === "off" || input.action === "remove") return disable(input.action === "remove");
|
|
171
|
+
if (input.action === "on") {
|
|
172
|
+
updateM365Settings({ enabled: true }, options);enabled = env.CCDX_M365 !== "0";
|
|
173
|
+
await startM365(true);return snapshot();
|
|
174
|
+
}
|
|
175
|
+
throw new Error("Unknown M365 action");
|
|
176
|
+
});
|
|
177
|
+
},
|
|
178
|
+
async close() { closed = true;enabled = false;m365?.close();await gateway?.close();gateway = null;await pending; },
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { userSettingsPath } from "./user-settings.mjs";
|
|
4
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
5
|
+
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
6
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
7
|
+
|
|
8
|
+
export function providerSettingsPath(options = {}) {
|
|
9
|
+
return path.join(path.dirname(userSettingsPath(options)), "providers.json");
|
|
10
|
+
}
|
|
11
|
+
const invalid = () => Object.assign(new Error("Provider selection is invalid; review providers.json before starting ccdx. The existing file was preserved"), { code: "ccdx_provider_selection_invalid" });
|
|
12
|
+
function checked(value) {
|
|
13
|
+
if (!value || value.version !== 1 || !["github", "m365"].includes(value.codex)) throw invalid();
|
|
14
|
+
if (value.m365 !== undefined && (!value.m365 || typeof value.m365 !== "object"
|
|
15
|
+
|| ["model", "auto_review_model"].some(key => typeof value.m365[key] !== "string" || !/^gpt-[\w.-]{1,120}$/.test(value.m365[key])))) throw invalid();
|
|
16
|
+
if (value.codex === "m365" && !value.m365) throw invalid();
|
|
17
|
+
if (value.m365?.auto_review_effort !== undefined && value.m365.auto_review_effort !== null
|
|
18
|
+
&& !["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(value.m365.auto_review_effort)) throw invalid();
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
export function readProviderSettings(options = {}) {
|
|
22
|
+
try { return checked(JSON.parse(readBoundedFileSync(providerSettingsPath(options), { encoding: "utf8", maxBytes: 8192 }))); }
|
|
23
|
+
catch (error) { if (error.code === "ENOENT") return { version: 1, codex: "github" };throw invalid(); }
|
|
24
|
+
}
|
|
25
|
+
export function writeProviderSettings(provider, preference, options = {}) {
|
|
26
|
+
const file = providerSettingsPath(options);fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
27
|
+
return withFileLockSync(`${file}.lock`, () => {
|
|
28
|
+
const current = readProviderSettings(options);
|
|
29
|
+
const next = checked({ ...current, codex: provider, ...(provider === "m365" ? { m365: preference } : {}) });
|
|
30
|
+
atomicWriteFileIfChangedSync(file, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });return next;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { defaultCopilotClient } from "../copilot.mjs";
|
|
2
|
+
import { applyCopilotResponsesRequestPolicies, stripUnsupportedGpt6ServiceTier } from "../copilot-responses-policy.mjs";
|
|
3
|
+
import { hasCopilotResponseRetryPolicy, openCopilotResponse, selectCopilotResponseRetryWithHistory } from "../copilot-responses-compat.mjs";
|
|
4
|
+
import { CODEX_AUTO_REVIEW_MODEL, modelIsResponsesOnly, modelSupportsChatCompletions, resolveCopilotPriorityTierModel } from "../models.mjs";
|
|
5
|
+
import { responsesBodyUsesCustomTools } from "../responses-bridge.mjs";
|
|
6
|
+
import { createRoutePlan } from "../route-plan.mjs";
|
|
7
|
+
|
|
8
|
+
const RESPONSES_ONLY_FALLBACK = new Set([
|
|
9
|
+
"gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.5", "gpt-5.4",
|
|
10
|
+
"gpt-5.4-mini", "gpt-5.3-codex", "gpt-5.2-codex",
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
function isResponsesOnly(model, endpoints) {
|
|
14
|
+
if (endpoints) {
|
|
15
|
+
const entry = { supported_endpoints: endpoints };
|
|
16
|
+
if (modelSupportsChatCompletions(entry)) return false;
|
|
17
|
+
if (modelIsResponsesOnly(entry)) return true;
|
|
18
|
+
}
|
|
19
|
+
return RESPONSES_ONLY_FALLBACK.has(model);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createGithubProvider({ client = defaultCopilotClient, profileId = "codex" } = {}) {
|
|
23
|
+
const profile = typeof profileId === "function" ? profileId : () => profileId;
|
|
24
|
+
return Object.freeze({
|
|
25
|
+
id: "github",
|
|
26
|
+
client,
|
|
27
|
+
profileId: profile,
|
|
28
|
+
selectModel(body, { requestedModel, upstreamModel }, models) {
|
|
29
|
+
const priorityTierModel = requestedModel === upstreamModel
|
|
30
|
+
? resolveCopilotPriorityTierModel(upstreamModel, body.service_tier, models) : null;
|
|
31
|
+
if (priorityTierModel) {
|
|
32
|
+
upstreamModel = priorityTierModel;
|
|
33
|
+
delete body.service_tier;
|
|
34
|
+
}
|
|
35
|
+
stripUnsupportedGpt6ServiceTier(body, requestedModel, upstreamModel, priorityTierModel);
|
|
36
|
+
return { upstreamModel, forceResponses: Boolean(priorityTierModel) };
|
|
37
|
+
},
|
|
38
|
+
route(body, { requestedModel, upstreamModel, forceResponses, surface, getCachedModelEndpoints = client.getCachedModelEndpoints }) {
|
|
39
|
+
let protocol = "openai-responses";
|
|
40
|
+
if (surface === "responses") {
|
|
41
|
+
const customTools = responsesBodyUsesCustomTools(body);
|
|
42
|
+
const endpoints = getCachedModelEndpoints(upstreamModel);
|
|
43
|
+
const native = forceResponses || requestedModel === CODEX_AUTO_REVIEW_MODEL
|
|
44
|
+
|| isResponsesOnly(upstreamModel, endpoints)
|
|
45
|
+
|| (customTools && Array.isArray(endpoints) && (endpoints.includes("/responses") || endpoints.includes("/v1/responses")));
|
|
46
|
+
if (customTools && !native) {
|
|
47
|
+
const message = `Model ${upstreamModel} has custom tool items that cannot be represented by Chat Completions, and cached endpoint metadata does not confirm Responses support`;
|
|
48
|
+
throw Object.assign(new Error(message), { statusCode: 400, code: "ccdx_custom_tools_require_responses",
|
|
49
|
+
jsonBody: { error: { message, type: "invalid_request_error", code: "ccdx_custom_tools_require_responses", model: upstreamModel } } });
|
|
50
|
+
}
|
|
51
|
+
protocol = native ? "openai-responses" : "openai-chat-completions";
|
|
52
|
+
}
|
|
53
|
+
// Preserve the established GitHub replay identity across the extraction.
|
|
54
|
+
return createRoutePlan({ disposition: "relay", origin: "ccdx", profile: profile(), protocol, model: upstreamModel, surface });
|
|
55
|
+
},
|
|
56
|
+
applyRequestPolicies: applyCopilotResponsesRequestPolicies,
|
|
57
|
+
compatibility: Object.freeze({ openResponse: openCopilotResponse,
|
|
58
|
+
hasRetry: hasCopilotResponseRetryPolicy, selectRetry: selectCopilotResponseRetryWithHistory }),
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export const defaultGithubProvider = createGithubProvider();
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// The native broker runs only in this short-lived child. Its stdout is a private
|
|
2
|
+
// parent pipe; no token or broker diagnostics are written to the user's terminal.
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
|
|
10
|
+
export const M365_CLIENT_ID = "aebc6443-996d-45c2-90f0-388ff96faa56";
|
|
11
|
+
export const M365_RESOURCE = "42c8f7bd-c7a8-4ba9-bc1c-91edfb716247";
|
|
12
|
+
const AUTHORITY = "https://login.microsoftonline.com/organizations";
|
|
13
|
+
const fail = code => Object.assign(new Error(code), { code });
|
|
14
|
+
|
|
15
|
+
export function brokerFailure(error) {
|
|
16
|
+
const states = { 2: "interaction_required", 3: "network_unavailable", 4: "network_unavailable",
|
|
17
|
+
5: "service_unavailable", 9: "broker_configuration", 11: "authority_untrusted", 13: "account_unavailable", 16: "account_unavailable" };
|
|
18
|
+
const code = /^m365_[a-z_]+$/.test(error?.code || "") ? error.code : `m365_${states[error?.errorStatus] || "broker_error"}`;
|
|
19
|
+
return { code, aadsts: [...new Set(String(error?.errorContext || "").match(/AADSTS\d+/g) || [])].slice(0, 3) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function acquireSilentM365Token({ account = null } = {}, {
|
|
23
|
+
platform = process.platform, loadBroker = () => createRequire(import.meta.url)("@azure/msal-node-runtime").msalNodeRuntime,
|
|
24
|
+
execFileImpl = promisify(execFile),
|
|
25
|
+
} = {}) {
|
|
26
|
+
if (!["darwin", "win32"].includes(platform)) throw fail("m365_platform_unsupported");
|
|
27
|
+
if (platform === "darwin") {
|
|
28
|
+
let output;
|
|
29
|
+
try { output = await execFileImpl("/usr/bin/profiles", ["status", "-type", "enrollment"],
|
|
30
|
+
{ timeout: 4000, maxBuffer: 8192, env: { ...process.env, LANG: "C", LC_ALL: "C" } }); }
|
|
31
|
+
catch { throw fail("m365_device_status_unavailable"); }
|
|
32
|
+
if (!/^MDM enrollment:\s*Yes\b/m.test(output.stdout || "")) throw fail("m365_device_not_managed");
|
|
33
|
+
}
|
|
34
|
+
let broker;
|
|
35
|
+
try { broker = loadBroker(); } catch { throw fail("m365_broker_missing"); }
|
|
36
|
+
if (!broker || broker.StartupError) throw fail("m365_broker_unavailable");
|
|
37
|
+
const invoke = (method, ...args) => new Promise((resolve, reject) => {
|
|
38
|
+
try { broker[method](...args, result => { try { result.CheckError();resolve(result); } catch (error) { reject(error); } }); }
|
|
39
|
+
catch (error) { reject(error); }
|
|
40
|
+
});
|
|
41
|
+
const discovered = await invoke("DiscoverAccountsAsync", M365_CLIENT_ID, randomUUID());
|
|
42
|
+
const accounts = (discovered.accounts || []).filter(value => value.accountId && value.username && value.realm);
|
|
43
|
+
const matching = account ? accounts.filter(value => value.homeAccountId === account.id && value.realm === account.tenant) : accounts;
|
|
44
|
+
if (!matching.length) throw fail("m365_account_unavailable");
|
|
45
|
+
if (matching.length !== 1) throw fail("m365_account_ambiguous");
|
|
46
|
+
const selected = matching[0], parameters = new broker.AuthParameters();
|
|
47
|
+
parameters.CreateAuthParameters(M365_CLIENT_ID, AUTHORITY);
|
|
48
|
+
parameters.SetRedirectUri(platform === "darwin" ? "msauth.com.msauth.unsignedapp://auth" : `ms-appx-web://Microsoft.AAD.BrokerPlugin/${M365_CLIENT_ID}`);
|
|
49
|
+
parameters.SetRequestedScopes(`${M365_RESOURCE}/.default`);
|
|
50
|
+
const result = await invoke("AcquireTokenSilentlyAsync", parameters, randomUUID(), selected);
|
|
51
|
+
if (!result.accessToken || !String(result.grantedScopes || "").split(" ").includes(`${M365_RESOURCE}/LLM.Read`)) throw fail("m365_llm_permission_unavailable");
|
|
52
|
+
return { token: result.accessToken, expiresAt: Number(result.expiresOn) * 1000,
|
|
53
|
+
account: { id: selected.homeAccountId, tenant: selected.realm, login: selected.username } };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function main() {
|
|
57
|
+
const timer = setTimeout(() => { process.stdout.write(JSON.stringify({ error: { code: "m365_auth_timeout" } }));process.exit(1); }, 25000);
|
|
58
|
+
try {
|
|
59
|
+
if (process.stdin.isTTY || process.stdout.isTTY) throw fail("m365_private_pipe_required");
|
|
60
|
+
let input = "";
|
|
61
|
+
for await (const chunk of process.stdin) {
|
|
62
|
+
input += chunk.toString("utf8");
|
|
63
|
+
if (Buffer.byteLength(input) > 4096) throw fail("m365_auth_request_invalid");
|
|
64
|
+
}
|
|
65
|
+
const request = JSON.parse(input);
|
|
66
|
+
if (request.action !== "token") throw fail("m365_auth_request_invalid");
|
|
67
|
+
const result = await acquireSilentM365Token(request);
|
|
68
|
+
process.stdout.write(JSON.stringify(result), () => process.exit(0));
|
|
69
|
+
} catch (error) { process.stdout.write(JSON.stringify({ error: brokerFailure(error) }), () => process.exit(1)); }
|
|
70
|
+
finally { clearTimeout(timer); }
|
|
71
|
+
}
|
|
72
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();
|