codex-copilot-dx 0.9.40 → 0.10.0

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.
Files changed (56) hide show
  1. package/README.md +25 -4
  2. package/bin/cli.mjs +37 -11
  3. package/docs/ARCHITECTURE.md +84 -13
  4. package/docs/REFERENCE.md +207 -16
  5. package/package.json +4 -1
  6. package/src/adapter.mjs +98 -152
  7. package/src/auto-review-model.mjs +4 -3
  8. package/src/claude-client-config.mjs +217 -0
  9. package/src/claude-gateway.mjs +163 -0
  10. package/src/cli-m365.mjs +133 -0
  11. package/src/cli-models.mjs +1 -1
  12. package/src/cli-options.mjs +20 -6
  13. package/src/cli-status.mjs +23 -7
  14. package/src/codex-model-catalog.mjs +7 -2
  15. package/src/copilot-client.mjs +4 -0
  16. package/src/copilot-responses-compat.mjs +1 -1
  17. package/src/copilot-responses-policy.mjs +11 -64
  18. package/src/dashboard/index.html +14 -4
  19. package/src/dashboard/language.js +40 -2
  20. package/src/dashboard/status.js +26 -4
  21. package/src/dashboard/ui.css +2 -2
  22. package/src/dashboard/ui.js +16 -7
  23. package/src/dashboard/usage.js +3 -1
  24. package/src/dashboard-api.mjs +10 -7
  25. package/src/doctor-repair.mjs +2 -0
  26. package/src/doctor.mjs +18 -2
  27. package/src/http-transport.mjs +6 -3
  28. package/src/m365-settings.mjs +89 -0
  29. package/src/management-routes.mjs +118 -0
  30. package/src/native-prediction-windows.mjs +2 -7
  31. package/src/optional-routes.mjs +33 -0
  32. package/src/profile-model-runtime.mjs +4 -2
  33. package/src/provider-management.mjs +28 -0
  34. package/src/provider-runtime.mjs +179 -0
  35. package/src/provider-settings.mjs +32 -0
  36. package/src/providers/github.mjs +62 -0
  37. package/src/providers/m365-auth-helper.mjs +72 -0
  38. package/src/providers/m365-auth.mjs +105 -0
  39. package/src/providers/m365-messages-policy.mjs +20 -0
  40. package/src/providers/m365-network.mjs +73 -0
  41. package/src/providers/m365.mjs +238 -0
  42. package/src/response-failures.mjs +66 -5
  43. package/src/response-history.mjs +20 -3
  44. package/src/responses-bridge.mjs +1 -1
  45. package/src/responses-handler.mjs +40 -103
  46. package/src/responses-image-tools.mjs +61 -0
  47. package/src/responses-proxy.mjs +5 -5
  48. package/src/responses-request.mjs +25 -0
  49. package/src/stream-performance.mjs +42 -10
  50. package/src/usage-analysis.mjs +3 -2
  51. package/src/usage-store.mjs +41 -12
  52. package/src/usage.mjs +8 -2
  53. package/src/windows-http-network.mjs +122 -0
  54. package/src/windows-prediction-network.cs +13 -6
  55. package/src/windows-prediction-network.mjs +4 -108
  56. package/src/windows-process.mjs +8 -0
@@ -8,6 +8,7 @@ import { redactDiagnosticText } from "./diagnostic-text.mjs";
8
8
  import { httpError } from "./http-errors.mjs";
9
9
  import { admissionAbortError, contentEncodings, requestContentLength } from "./request-admission.mjs";
10
10
  import { currentRequestContext } from "./request-context.mjs";
11
+ import { upstreamErrorEvidence } from "./response-failures.mjs";
11
12
 
12
13
  export { httpError } from "./http-errors.mjs";
13
14
  export { createRequestAdmission } from "./request-admission.mjs";
@@ -275,9 +276,11 @@ export function sendJsonError(res, err, fallbackStatus = 400) {
275
276
  }
276
277
 
277
278
  export function sendUpstreamError(res, response, text) {
278
- let code;
279
- try { code = JSON.parse(text)?.error?.code; } catch {}
280
- currentRequestContext()?.onHttpError?.({ code, origin: "upstream_http", headers: response.headers });
279
+ const context = currentRequestContext();
280
+ if (context?.onHttpError) context.onHttpError({
281
+ ...upstreamErrorEvidence(text, { includeMessage: context.includeHttpErrorDetails === true }),
282
+ origin: "upstream_http", headers: response.headers,
283
+ });
281
284
  if (!res.headersSent) {
282
285
  res.writeHead(response.status || 502, safeUpstreamResponseHeaders(response.headers, {
283
286
  defaultContentType: "application/json",
@@ -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
+ }
@@ -0,0 +1,118 @@
1
+ import { ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH, PREDICTION_FIX_CAPABILITY, adapterHealthPayload } from "./running-adapter.mjs";
2
+ import { ADAPTER_CACHE_PATH, cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
3
+ import { createRequestAbort, readJsonBody, sendJsonError } from "./http-transport.mjs";
4
+ import { httpError } from "./http-errors.mjs";
5
+ import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
6
+
7
+ export function isManagementRoute(method, pathname) {
8
+ return (method === "GET" && [ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH].includes(pathname))
9
+ || pathname === ADAPTER_PREDICTION_FIX_PATH || pathname === ADAPTER_CACHE_PATH;
10
+ }
11
+
12
+ // Management retains its own access checks; it receives snapshots and explicit
13
+ // actions, never an inference client or a second integration lifecycle.
14
+ export function createManagementHandler({ statusSnapshot, nativePredictionPac, fixPrediction, requestBodyTimeoutMs } = {}) {
15
+ const options = { nativePredictionPac, fixPrediction };
16
+ return async (req, res, pathname) => {
17
+ if (req.method === "GET" && pathname === ADAPTER_STATUS_PATH) {
18
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || !isLoopbackHostHeader(req.headers?.host)) {
19
+ res.writeHead(403, { "Content-Type": "application/json" });
20
+ res.end(JSON.stringify({ error: "Runtime status is available only from loopback" }));
21
+ return;
22
+ }
23
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
24
+ res.end(JSON.stringify(statusSnapshot()));
25
+ return;
26
+ }
27
+
28
+ if (req.method === "GET" && pathname === ADAPTER_HEALTH_PATH) {
29
+ res.writeHead(200, { "Content-Type": "application/json" });
30
+ const predictionPac = isLoopbackAddress(req.socket?.remoteAddress) && isLoopbackHostHeader(req.headers?.host)
31
+ ? options.nativePredictionPac?.() : null;
32
+ const health = adapterHealthPayload();
33
+ res.end(JSON.stringify({ ...health,
34
+ capabilities: [...health.capabilities, ...(typeof options.fixPrediction === "function" ? [PREDICTION_FIX_CAPABILITY] : [])],
35
+ ...(predictionPac ? { native_prediction_pac: predictionPac } : {}) }));
36
+ return;
37
+ }
38
+
39
+ if (pathname === ADAPTER_PREDICTION_FIX_PATH) {
40
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers?.host === undefined
41
+ || !isLoopbackHostHeader(req.headers.host) || Object.hasOwn(req.headers, "origin")) {
42
+ sendJsonError(res, httpError("Prediction repair is available only to native loopback clients", 403));return;
43
+ }
44
+ if (req.method !== "POST") {
45
+ res.setHeader?.("Allow", "POST");sendJsonError(res, httpError("Prediction repair requires POST", 405));return;
46
+ }
47
+ if (String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase() !== "application/json") {
48
+ sendJsonError(res, httpError("Prediction repair requires application/json", 415));return;
49
+ }
50
+ if (typeof options.fixPrediction !== "function") {
51
+ sendJsonError(res, httpError("This adapter does not support prediction repair; upgrade and restart CCDX once", 503));return;
52
+ }
53
+ const abort = createRequestAbort(req, res);abort.setTimeout(2000);
54
+ try {
55
+ const body = await readJsonBody(req, { maxBodyBytes: 1024, maxDecodedBodyBytes: 1024, signal: abort.signal });
56
+ if (!body || Object.keys(body).length !== 1 || body.action !== "fix") throw httpError("Expected prediction repair action: fix", 400);
57
+ abort.clearTimeout();
58
+ const result = await options.fixPrediction();
59
+ if (!res.destroyed && !res.writableEnded) {
60
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(result));
61
+ }
62
+ } catch (error) { sendJsonError(res, error, 503); }
63
+ finally { abort.cleanup(); }
64
+ return;
65
+ }
66
+
67
+ if (pathname === ADAPTER_CACHE_PATH) {
68
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || !isLoopbackHostHeader(req.headers?.host)) {
69
+ res.writeHead(403, { "Content-Type": "application/json" });
70
+ res.end(JSON.stringify({ error: "Cache control is available only from loopback" }));
71
+ return;
72
+ }
73
+ if (req.method === "GET") {
74
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
75
+ res.end(JSON.stringify(cacheRuntimeSnapshot()));
76
+ return;
77
+ }
78
+ if (req.method !== "POST") {
79
+ res.writeHead(405, { "Content-Type": "application/json", Allow: "GET, POST" });
80
+ res.end(JSON.stringify({ error: "Only GET and POST are supported" }));
81
+ return;
82
+ }
83
+ if (Object.hasOwn(req.headers || {}, "origin")) {
84
+ res.writeHead(403, { "Content-Type": "application/json" });
85
+ res.end(JSON.stringify({ error: "Browser origins are not allowed for cache control" }));
86
+ return;
87
+ }
88
+ const mediaType = String(req.headers?.["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
89
+ if (mediaType !== "application/json") {
90
+ res.writeHead(415, { "Content-Type": "application/json" });
91
+ res.end(JSON.stringify({ error: "Cache control requires application/json" }));
92
+ return;
93
+ }
94
+ const abort = createRequestAbort(req, res);
95
+ abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
96
+ try {
97
+ const body = await readJsonBody(req, {
98
+ maxBodyBytes: 8 * 1024,
99
+ maxDecodedBodyBytes: 8 * 1024,
100
+ signal: abort.signal,
101
+ });
102
+ let result;
103
+ if (body?.action === "set_limit") result = setHistoryCacheLimit(body.max_bytes);
104
+ else if (body?.action === "clean") result = cleanRuntimeCaches({ history: body.history === true });
105
+ else throw httpError("Unknown cache action", 400);
106
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
107
+ res.end(JSON.stringify(result));
108
+ } catch (error) {
109
+ if (["ccdx_cache_busy", "ccdx_cache_limit_below_usage"].includes(error?.code)) error.statusCode = 409;
110
+ sendJsonError(res, error, 400);
111
+ } finally {
112
+ abort.cleanup();
113
+ }
114
+ return;
115
+ }
116
+
117
+ };
118
+ }
@@ -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 {
@@ -0,0 +1,33 @@
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js"]);
2
+ export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth"]);
3
+
4
+ export function isOptionalRoute(method, pathname) {
5
+ return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
6
+ || ((method === "GET" || method === "HEAD") && DASHBOARD_PATHS.has(pathname));
7
+ }
8
+
9
+ // Optional handlers load only on their own routes. Failure is contained by the
10
+ // shared HTTP dispatcher and cannot initialize or change core inference.
11
+ export function createOptionalRoutes(options = {}) {
12
+ let imageMcpHandler = options.imageMcpHandler || null;
13
+ return {
14
+ imageStats() { return imageMcpHandler?.stats?.(); },
15
+ async handle(req, res, pathname) {
16
+ if (DASHBOARD_API_PATHS.has(pathname)) {
17
+ const { handleDashboardApi } = await import("./dashboard-api.mjs");
18
+ return handleDashboardApi(req, res, pathname, options.dashboardOptions);
19
+ }
20
+ if ((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname)) {
21
+ const { serveDashboard } = await import("./dashboard.mjs");
22
+ return serveDashboard(req, res, pathname);
23
+ }
24
+ if (pathname === "/mcp/image") {
25
+ if (imageMcpHandler) return imageMcpHandler(req, res);
26
+ return import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
27
+ imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
28
+ return imageMcpHandler(req, res);
29
+ });
30
+ }
31
+ },
32
+ };
33
+ }
@@ -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: String(codexCredentialFingerprint || "").trim(),
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: String(codexCredentialFingerprint || "").trim(),
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,179 @@
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 } 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
+ 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 ? null : "m365_no_claude_models";
36
+ if (claudeModels.length) try {
37
+ const apiKey = ensureM365GatewayKey(options);
38
+ if (!gateway) {
39
+ const start = startGateway || (await import("./claude-gateway.mjs")).startClaudeGateway;
40
+ const opened = await start({ provider: m365, apiKey, env, log,
41
+ onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
42
+ if (closed || !enabled) { await opened.close();return null; }
43
+ gateway = opened;
44
+ }
45
+ try {
46
+ const integration = configureClients ? null : await import("./claude-client-config.mjs");
47
+ const configure = configureClients || integration.configureClaudeClients;
48
+ const desktopManaged = integration ? await integration.inspectClaudeDesktopPolicy(options) : false;
49
+ if (closed || !enabled) return null;
50
+ clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${gateway.port}`, apiKey, models: claudeModels });
51
+ } catch { clients = { code: "configuration_unavailable", app: "configuration_unavailable" };claudeReason = "m365_claude_config_unavailable"; }
52
+ } catch (error) {
53
+ claudeReason = error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_claude_setup_unavailable";
54
+ log("warn", `Claude setup unavailable: ${claudeReason}; M365 GPT routing is independent`);
55
+ }
56
+ 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}` : ""}`);
57
+ return m365;
58
+ })().catch(error => {
59
+ reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_unavailable";
60
+ log("info", `Microsoft 365 unavailable: ${reason}`);return null;
61
+ }).finally(() => { if (pending === operation) pending = null; });
62
+ pending = operation;return operation;
63
+ }
64
+
65
+ const snapshot = () => ({ codex_provider: selection.codex,
66
+ github: { state: "configured", profile: "codex" },
67
+ m365: { ...(m365?.snapshot() || {}), enabled, state: !enabled ? "disabled" : pending ? "checking"
68
+ : !["darwin", "win32"].includes(platform) ? "unsupported" : m365?.snapshot().state || (reason ? "unavailable" : "idle"),
69
+ reason: reason || m365?.snapshot().reason || null,
70
+ preference: selection.m365 || null,
71
+ active_requests: activeM365Requests,
72
+ claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway?.port || null, clients: { ...clients },
73
+ observed_clients: { ...lastClients }, requests: gateway?.snapshot?.() || null } } });
74
+
75
+ function current() {
76
+ if (selection.codex === "github") return github;
77
+ if (!m365 || !enabled || m365.snapshot().state === "disabled") throw unavailable(reason || "m365_not_ready");
78
+ return m365;
79
+ }
80
+ const serialize = task => {
81
+ const next = (serial || Promise.resolve()).then(task);
82
+ serial = next.catch(() => {});return next;
83
+ };
84
+ async function switchSource(provider, preference) {
85
+ if (!["github", "m365"].includes(provider)) throw new Error("Provider must be github or m365");
86
+ if (provider === "m365") {
87
+ if (!enabled) throw unavailable("m365_disabled");
88
+ const ready = await startM365();if (!ready) throw unavailable(reason || "m365_not_ready");
89
+ const ids = new Set(m365.models("gpt").map(model => model.id));
90
+ if (!preference || !ids.has(preference.model) || !ids.has(preference.auto_review_model)) {
91
+ throw Object.assign(new Error("Choose available M365 GPT and auto-review models before switching"), { code: "m365_model_selection_required", statusCode: 400 });
92
+ }
93
+ if (!m365.models("gpt").find(model => model.id === preference.auto_review_model)?.capabilities?.supports?.reasoning_effort?.includes("low")) {
94
+ throw Object.assign(new Error("Choose an M365 Auto-review model that advertises low reasoning"), { code: "m365_review_effort_unavailable", statusCode: 400 });
95
+ }
96
+ }
97
+ if (closed) throw unavailable("m365_runtime_closed");
98
+ let previous;try { previous = current().profileId(); } catch {}
99
+ const next = writeProviderSettings(provider, preference, options);
100
+ if (selection.codex !== provider) priorNamespace = previous || null;
101
+ selection = next;return snapshot();
102
+ }
103
+ async function disable(remove) {
104
+ if (remove && (activeM365Requests > 0 || gateway?.snapshot?.().active > 0)) {
105
+ throw Object.assign(new Error("Microsoft 365 requests are active; finish them before removing its profile"), { code: "m365_profile_busy", statusCode: 409 });
106
+ }
107
+ await switchSource("github");
108
+ updateM365Settings({ enabled: false }, options);enabled = false;
109
+ m365?.close();await gateway?.close();gateway = null;
110
+ await pending;m365 = null;
111
+ const restore = restoreClients || (await import("./claude-client-config.mjs")).restoreClaudeClients;
112
+ const result = restore(options);clients = { code: result.preserved ? "preserved" : "restored", app: result.preserved ? "preserved" : "restored" };
113
+ if (remove) {
114
+ if (result.remaining) throw Object.assign(new Error("User-modified Claude settings were preserved; M365 profile cleanup is incomplete"), { code: "m365_cleanup_preserved" });
115
+ const paths = m365Paths(options);
116
+ for (const file of [paths.account, paths.catalog, paths.gateway, paths.ownership]) {
117
+ try { if (!fs.lstatSync(file).isFile()) throw Error();fs.unlinkSync(file); }
118
+ catch (error) { if (error.code !== "ENOENT") throw new Error("M365 cleanup preserved an unexpected file"); }
119
+ }
120
+ }
121
+ return snapshot();
122
+ }
123
+ return {
124
+ github, current, snapshot, start: startM365, refresh: () => startM365(true),
125
+ selection: () => selection,
126
+ dashboardCatalog() {
127
+ if (selection.codex !== "m365") return null;
128
+ const models = [...(m365?.models("gpt") || []), ...(m365?.models("claude") || [])];
129
+ return { source: "catalog", checkedAt: m365?.snapshot().models.refreshed_at || null,
130
+ upstreamHost: "Microsoft 365", advertised: models.length,
131
+ models: models.map(model => ({ id: model.id, vendor: model.publisher,
132
+ endpoints: model.supported_endpoints.includes("/v1/messages") ? ["messages"] : ["responses"], preview: false })) };
133
+ },
134
+ track(target) {
135
+ if (target.id !== "m365") return undefined;
136
+ activeM365Requests++;let finished = false;
137
+ return () => { if (!finished) { finished = true;activeM365Requests--; } };
138
+ },
139
+ historyContext(headers, target) {
140
+ const namespace = target.profileId(), raw = headers.session_id || headers["session-id"];
141
+ // Internal bounded correlation only; IDs are never exposed or persisted.
142
+ const key = typeof raw === "string" && raw.length <= 512 ? raw : null;
143
+ const previous = key && sessions.get(key)?.namespace || priorNamespace, order = ++requestOrder;
144
+ return { historyNamespace: namespace, historyTransferNamespace: previous && previous !== namespace ? previous : undefined,
145
+ onHistoryStored() {
146
+ if (!key) return;
147
+ const record = sessions.get(key);
148
+ if (record?.order > order) return;
149
+ if (record) { record.namespace = namespace;record.order = order; }
150
+ sessions.delete(key);sessions.set(key, record || { namespace, order });
151
+ while (sessions.size > 1024) sessions.delete(sessions.keys().next().value);
152
+ } };
153
+ },
154
+ async action(input) {
155
+ return serialize(async () => {
156
+ if (closed) throw unavailable("m365_runtime_closed");
157
+ if (input.action === "models") { await startM365();return { state: snapshot(), models: m365?.models(input.family === "claude" ? "claude" : "gpt") || [] }; }
158
+ if (input.action === "auto-review") {
159
+ if (selection.codex !== "m365" || !m365) throw unavailable("m365_not_selected");
160
+ const model = m365.models("gpt").find(model => model.id === input.model);
161
+ if (!model || input.effort !== null && !model.capabilities?.supports?.reasoning_effort?.includes(input.effort)) {
162
+ throw Object.assign(new Error("The selected M365 review model or effort is not available"), { statusCode: 400, code: "m365_review_effort_unavailable" });
163
+ }
164
+ const preference = { ...selection.m365, auto_review_model: input.model, auto_review_effort: input.effort };
165
+ const changed = JSON.stringify(preference) !== JSON.stringify(selection.m365);
166
+ selection = writeProviderSettings("m365", preference, options);return { changed, ...snapshot() };
167
+ }
168
+ if (input.action === "switch") return switchSource(input.provider, { model: input.model, auto_review_model: input.auto_review_model });
169
+ if (input.action === "off" || input.action === "remove") return disable(input.action === "remove");
170
+ if (input.action === "on") {
171
+ updateM365Settings({ enabled: true }, options);enabled = env.CCDX_M365 !== "0";
172
+ await startM365(true);return snapshot();
173
+ }
174
+ throw new Error("Unknown M365 action");
175
+ });
176
+ },
177
+ async close() { closed = true;enabled = false;m365?.close();await gateway?.close();gateway = null;await pending; },
178
+ };
179
+ }
@@ -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();