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
@@ -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();
@@ -0,0 +1,105 @@
1
+ import { spawn } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import { m365AccountKey, readM365Account } from "../m365-settings.mjs";
4
+
5
+ const helperPath = fileURLToPath(new URL("./m365-auth-helper.mjs", import.meta.url));
6
+ const abortError = signal => signal?.reason || Object.assign(new Error("M365 authorization cancelled"), { name: "AbortError" });
7
+ export const m365Error = (code, message = code) => Object.assign(new Error(message), { code, statusCode: 503 });
8
+
9
+ export function m365HelperEnvironment(env = process.env) {
10
+ const keys = new Set(["PATH", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "SYSTEMROOT", "WINDIR", "APPDATA", "LOCALAPPDATA",
11
+ "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "NODE_EXTRA_CA_CERTS"]);
12
+ return Object.fromEntries(Object.entries(env).filter(([key]) => keys.has(key.toUpperCase())));
13
+ }
14
+
15
+ export function requestM365Token({ account, signal, env = process.env, spawnImpl = spawn, timeoutMs = 28000 } = {}) {
16
+ if (signal?.aborted) return Promise.reject(abortError(signal));
17
+ return new Promise((resolve, reject) => {
18
+ let child, timer, finished = false, bytes = 0;
19
+ const chunks = [];
20
+ const finish = (error, result) => {
21
+ if (finished) return;
22
+ finished = true;
23
+ clearTimeout(timer);
24
+ signal?.removeEventListener("abort", cancelled);
25
+ if (error) { child?.kill("SIGKILL");reject(error); } else resolve(result);
26
+ };
27
+ const cancelled = () => finish(abortError(signal));
28
+ try { child = spawnImpl(process.execPath, [helperPath], { env: m365HelperEnvironment(env), windowsHide: true, stdio: ["pipe", "pipe", "pipe"] }); }
29
+ catch { finish(m365Error("m365_helper_start_failed"));return; }
30
+ timer = setTimeout(() => finish(m365Error("m365_auth_timeout")), timeoutMs);
31
+ signal?.addEventListener("abort", cancelled, { once: true });
32
+ if (signal?.aborted) { cancelled();return; }
33
+ child.once("error", () => finish(m365Error("m365_helper_start_failed")));
34
+ child.stdin.on("error", () => {});
35
+ child.stderr.on("data", () => {});
36
+ child.stdout.on("data", chunk => {
37
+ bytes += chunk.length;
38
+ if (bytes > 128 * 1024) { finish(m365Error("m365_auth_response_invalid"));return; }
39
+ chunks.push(chunk);
40
+ });
41
+ child.once("close", code => {
42
+ if (finished) return;
43
+ let result;
44
+ try { result = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { finish(m365Error("m365_auth_response_invalid"));return; }
45
+ if (code !== 0 || result.error) {
46
+ finish(m365Error(/^m365_[a-z_]+$/.test(result.error?.code || "") ? result.error.code : "m365_auth_failed"));return;
47
+ }
48
+ try {
49
+ m365AccountKey(result.account);
50
+ if (typeof result.token !== "string" || !result.token || /\s/.test(result.token)
51
+ || !Number.isFinite(result.expiresAt) || result.expiresAt <= Date.now()) throw Error();
52
+ if (account && m365AccountKey(account) !== m365AccountKey(result.account)) throw Error();
53
+ } catch { finish(m365Error("m365_auth_response_invalid"));return; }
54
+ finish(null, result);
55
+ });
56
+ child.stdin.end(JSON.stringify({ action: "token", account: account || null }));
57
+ });
58
+ }
59
+
60
+ export function createM365Auth({ home, env = process.env, acquire = requestM365Token, now = Date.now } = {}) {
61
+ let cached = null, flight = null, generation = 0, lastError = null, retryAt = 0;
62
+ const snapshot = () => ({ token_cached: Boolean(cached && cached.expiresAt > now()),
63
+ token_expires_in_ms: cached ? Math.max(0, cached.expiresAt - now()) : null,
64
+ token_refresh_in_flight: Boolean(flight), reason: lastError,
65
+ account: cached ? { login: cached.account.login } : null });
66
+ function getToken({ signal } = {}) {
67
+ if (signal?.aborted) return Promise.reject(abortError(signal));
68
+ if (cached && cached.expiresAt - now() > 120000) return Promise.resolve(cached);
69
+ if (flight?.controller.signal.aborted) flight = null;
70
+ if (!flight && retryAt > now()) return Promise.reject(m365Error(lastError || "m365_auth_backoff"));
71
+ if (!flight) {
72
+ const controller = new AbortController(), current = generation;
73
+ const entry = { controller, waiters: 0, settled: false, promise: null };
74
+ entry.promise = Promise.resolve().then(() => acquire({ account: cached?.account || readM365Account({ home }), env, signal: controller.signal }))
75
+ .then(result => {
76
+ if (current !== generation || controller.signal.aborted) throw abortError(controller.signal);
77
+ m365AccountKey(result.account);
78
+ cached = result;lastError = null;retryAt = 0;return result;
79
+ }).catch(error => {
80
+ if (current === generation && !controller.signal.aborted) {
81
+ lastError = /^m365_[a-z_]+$/.test(error?.code || "") ? error.code : "m365_auth_failed";
82
+ retryAt = now() + 60000;
83
+ }
84
+ throw error;
85
+ }).finally(() => { entry.settled = true;if (flight === entry) flight = null; });
86
+ flight = entry;
87
+ }
88
+ const entry = flight;
89
+ entry.waiters += 1;
90
+ return new Promise((resolve, reject) => {
91
+ let done = false;
92
+ const finish = (fn, value) => {
93
+ if (done) return;
94
+ done = true;signal?.removeEventListener("abort", cancelled);entry.waiters -= 1;
95
+ if (!entry.waiters && !entry.settled) entry.controller.abort();
96
+ fn(value);
97
+ };
98
+ const cancelled = () => finish(reject, abortError(signal));
99
+ signal?.addEventListener("abort", cancelled, { once: true });
100
+ if (signal?.aborted) cancelled();
101
+ entry.promise.then(value => finish(resolve, value), error => finish(reject, error));
102
+ });
103
+ }
104
+ return { getToken, snapshot, reset() { generation += 1;flight?.controller.abort();flight = null;cached = null;lastError = null;retryAt = 0; } };
105
+ }
@@ -0,0 +1,20 @@
1
+ // Loki explicitly rejects 1h prompt-cache retention. Cap only the standard
2
+ // cache_control locations to its supported 5m TTL; never walk tool input/data.
3
+ // Text, image bytes, thinking, tools, permissions and cache breakpoints survive.
4
+ export function limitM365CacheTtl(body) {
5
+ let changed = 0;
6
+ const block = value => {
7
+ if (value?.cache_control?.type !== "ephemeral" || value.cache_control.ttl !== "1h") return value;
8
+ changed++;return { ...value, cache_control: { ...value.cache_control, ttl: "5m" } };
9
+ };
10
+ const blocks = value => {
11
+ if (!Array.isArray(value)) return value;
12
+ const before = changed, next = value.map(block);return changed === before ? value : next;
13
+ };
14
+ const next = block(body);
15
+ const system = blocks(body.system), tools = blocks(body.tools);
16
+ const messages = Array.isArray(body.messages) ? body.messages.map(message => {
17
+ const content = blocks(message?.content);return content === message?.content ? message : { ...message, content };
18
+ }) : body.messages;
19
+ return { body: changed ? { ...next, system, tools, messages } : body, changed };
20
+ }
@@ -0,0 +1,73 @@
1
+ import https from "node:https";
2
+ import { Readable } from "node:stream";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { resolveNetworkRoute, networkProxyFor, bypassNetworkProxy, networkRouteSnapshot } from "../network-route.mjs";
6
+ import { createProxyAgent } from "../proxy-tunnel.mjs";
7
+ import { loadRuntimeConfig } from "../runtime-config.mjs";
8
+ import { m365HelperEnvironment } from "./m365-auth.mjs";
9
+
10
+ const HOST = "df.loki.delve.office.com";
11
+ const targetUrl = new URL(`https://${HOST}/api/v1/llmapi/models`);
12
+ const fail = code => Object.assign(new Error(`Microsoft 365 network is unavailable (${code})`), { code: `m365_${code}`, statusCode: 503 });
13
+
14
+ export function requestFetch(requestImpl, agent) {
15
+ return (raw, init = {}) => new Promise((resolve, reject) => {
16
+ let url;try { url = new URL(raw); } catch { reject(fail("target_invalid"));return; }
17
+ if (url.protocol !== "https:" || url.hostname !== HOST || url.port || url.username || url.password || url.hash
18
+ || !url.pathname.startsWith("/api/v1/llmapi/") || !["GET", "POST", "HEAD"].includes(init.method || "GET")) { reject(fail("target_invalid"));return; }
19
+ if (init.signal?.aborted) { reject(init.signal.reason);return; }
20
+ const headers = Object.fromEntries(new Headers(init.headers));
21
+ headers["accept-encoding"] = "identity";
22
+ let request, incoming;
23
+ const abort = () => { request?.destroy(init.signal.reason || fail("request_cancelled"));incoming?.destroy(); };
24
+ const cleanup = () => init.signal?.removeEventListener("abort", abort);
25
+ try {
26
+ request = requestImpl({ hostname: HOST, protocol: "https:", port: 443, path: url.pathname + url.search,
27
+ method: init.method || "GET", headers, agent, rejectUnauthorized: true }, response => {
28
+ incoming = response;response.once("end", cleanup);response.once("close", cleanup);response.on("error", reject);
29
+ const responseHeaders = new Headers();
30
+ for (const [key, value] of Object.entries(response.headers)) {
31
+ if (value === undefined) continue;
32
+ for (const item of Array.isArray(value) ? value : [value]) responseHeaders.append(key, String(item));
33
+ }
34
+ try {
35
+ const noBody = [204, 205, 304].includes(response.statusCode) || init.method === "HEAD";
36
+ if (noBody) response.resume();
37
+ resolve(new Response(noBody ? null : Readable.toWeb(response), { status: response.statusCode, headers: responseHeaders }));
38
+ } catch (error) { response.destroy();cleanup();reject(error); }
39
+ });
40
+ request.on("error", error => { cleanup();reject(error); });
41
+ init.signal?.addEventListener("abort", abort, { once: true });
42
+ if (init.signal?.aborted) { abort();return; }
43
+ request.end(init.body);
44
+ } catch (error) { cleanup();request?.destroy();reject(error); }
45
+ });
46
+ }
47
+
48
+ export async function createM365Network({ env = process.env, platform = process.platform, signal,
49
+ execFileImpl = promisify(execFile), startWindowsNetwork, requestImpl = https.request } = {}) {
50
+ const explicit = resolveNetworkRoute({ env, checkApi: false });
51
+ const environmentRoute = networkProxyFor(targetUrl, explicit), bypass = bypassNetworkProxy(HOST, 443, explicit);
52
+ const runtime = loadRuntimeConfig(env);
53
+ if (platform === "win32" && !environmentRoute && !bypass) {
54
+ const start = startWindowsNetwork || (await import("../windows-http-network.mjs")).startWindowsHttpNetwork;
55
+ const worker = await start({ target: "m365", settings: { autoDetect: false, pac: "" }, env: m365HelperEnvironment(env), signal,
56
+ timeoutMs: Math.max(runtime.upstreamTimeoutMs, runtime.streamIdleTimeoutMs) });
57
+ return { fetch: requestFetch(worker.requestImpl), snapshot: () => ({ source: "system", type: "winhttp", healthy: worker.healthy() }),
58
+ healthy: worker.healthy, close: worker.close };
59
+ }
60
+ let plan = explicit;
61
+ if (platform === "darwin" && !environmentRoute && !bypass) {
62
+ let systemProxy;
63
+ try { ({ stdout: systemProxy } = await execFileImpl("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2500, maxBuffer: 65536, signal })); }
64
+ catch { throw fail("proxy_discovery_failed"); }
65
+ try { plan = resolveNetworkRoute({ env, systemProxy, checkApi: false }); }
66
+ catch { throw fail("proxy_settings_unsupported"); }
67
+ }
68
+ const agent = createProxyAgent(plan, { timeoutMs: 30000 });
69
+ agent.maxSockets = 8;agent.maxFreeSockets = 2;
70
+ let closed = false;
71
+ return { fetch: requestFetch(requestImpl, agent), snapshot: () => ({ ...networkRouteSnapshot(plan), healthy: !closed }),
72
+ healthy: () => !closed, close() { closed = true;agent.destroy(); } };
73
+ }
@@ -0,0 +1,238 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { createM365Auth, m365Error } from "./m365-auth.mjs";
3
+ import { m365Paths, m365AccountKey, readM365Account, readM365Json, writeM365Json } from "../m365-settings.mjs";
4
+ import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
5
+ import { prepareResponsesPayload, summarizeReqBody } from "../image-optimization.mjs";
6
+ import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
7
+ import { createRoutePlan } from "../route-plan.mjs";
8
+ import { CODEX_AUTO_REVIEW_MODEL } from "../models.mjs";
9
+ import { currentRequestContext } from "../request-context.mjs";
10
+ import { markRequestObservation, markUpstreamHeaders, markUpstreamStarted } from "../stream-performance.mjs";
11
+ import { requestOptionsEvidence } from "../response-failures.mjs";
12
+ import { status } from "../status.mjs";
13
+ import { redactDiagnosticText } from "../diagnostic-text.mjs";
14
+ import { removeNativeImageTools } from "../responses-image-tools.mjs";
15
+ import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
16
+
17
+ export const M365_API_BASE = "https://df.loki.delve.office.com/api/v1/llmapi";
18
+ const SOFT_TTL_MS = 2 * 60 * 60 * 1000;
19
+ const HARD_TTL_MS = 7 * 24 * 60 * 60 * 1000;
20
+ const protocolError = (code, message, statusCode = 400) => Object.assign(new Error(message), {
21
+ code, statusCode, jsonBody: { error: { code, message, type: statusCode === 400 ? "invalid_request_error" : "upstream_error" } },
22
+ });
23
+
24
+ export function m365Headers(token, { headers = {}, conversationId, stream = false } = {}) {
25
+ const out = { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: stream ? "text/event-stream" : "application/json",
26
+ "X-ClientType": "GitHub", "X-ClientVersion": "0.10.0", "X-Llm-Api-Version": "2026-09-28", "X-ClientScenario": "Code",
27
+ "X-ClientFeature": "LlmApiProxy", "X-ClientCorrelationId": randomUUID(), "X-ClientCallId": randomUUID() };
28
+ if (conversationId) out["X-ConversationId"] = conversationId;
29
+ for (const name of ["anthropic-version", "anthropic-beta"]) {
30
+ const value = headers[name];
31
+ if (typeof value === "string" && value.length < 8192 && !/[\r\n]/.test(value)) out[name] = value;
32
+ }
33
+ return out;
34
+ }
35
+
36
+ export function m365ConversationId(body, headers = {}, profile = "m365") {
37
+ let session = headers["x-conversation-id"] || headers["session_id"] || headers["session-id"] || headers["x-claude-code-session-id"];
38
+ if (!session && typeof body?.metadata?.user_id === "string") {
39
+ try { session = JSON.parse(body.metadata.user_id)?.session_id; } catch {
40
+ session = /(?:^|_)session_([\w-]{8,128})$/.exec(body.metadata.user_id)?.[1];
41
+ }
42
+ }
43
+ if (typeof session !== "string" || !session || session.length > 512 || /[\u0000-\u001f\u007f]/.test(session)) return randomUUID();
44
+ const value = createHash("sha256").update(`${profile}\0${session}`).digest("hex");
45
+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20, 32)}`;
46
+ }
47
+
48
+ export function m365Catalog(payload) {
49
+ if (!payload || !Array.isArray(payload.data) || payload.data.length > 1000) throw m365Error("m365_catalog_invalid");
50
+ const seen = new Set();
51
+ for (const model of payload.data) {
52
+ if (!model || typeof model.id !== "string" || !/^[A-Za-z0-9][\w.-]{0,127}$/.test(model.id)
53
+ || seen.has(model.id) || !Array.isArray(model.supported_endpoints)) throw m365Error("m365_catalog_invalid");
54
+ seen.add(model.id);
55
+ }
56
+ return { data: payload.data };
57
+ }
58
+
59
+ export function m365Models(catalog, family) {
60
+ return (catalog?.data || []).filter(model => typeof model?.publisher === "string" && model.model_picker_enabled !== false
61
+ && (!model.policy?.state || model.policy.state === "enabled")).filter(model => family === "claude"
62
+ ? model.id.startsWith("claude-") && model.publisher?.toLowerCase() === "anthropic" && model.supported_endpoints.includes("/v1/messages")
63
+ : model.id.startsWith("gpt-") && model.publisher?.toLowerCase() === "openai"
64
+ && model.supported_endpoints.some(endpoint => endpoint === "/responses" || endpoint === "/v1/responses"));
65
+ }
66
+
67
+ export function createM365Provider({ home, env = process.env, auth = createM365Auth({ home, env }), fetchImpl,
68
+ createNetwork, now = Date.now, log = (kind, message) => console.log(status(kind, message)), onCatalog = () => {} } = {}) {
69
+ const paths = m365Paths({ home });
70
+ let catalog = null, account = null, catalogAt = 0, state = "idle", reason = null, flight = null, controller = null, generation = 0;
71
+ let network = null, networkFlight = null, cacheTtlAdjustments = 0;
72
+ const registry = { models: null, source: "unavailable", cacheState: "none", cacheSavedAtMs: null,
73
+ refreshInFlight: false, generation: 0, lastError: null, lastErrorAtMs: null };
74
+ const profile = () => account ? `m365:${m365AccountKey(account)}` : "m365:unavailable";
75
+ async function transport(signal) {
76
+ if (network?.healthy()) return network.fetch;
77
+ if (!networkFlight) {
78
+ const pending = (async () => {
79
+ network?.close();network = null;
80
+ const start = createNetwork || (await import("./m365-network.mjs")).createM365Network;
81
+ const opened = await start({ env, signal });
82
+ if (state === "disabled") { opened.close();throw m365Error("m365_disabled"); }
83
+ network = opened;return opened.fetch;
84
+ })().finally(() => { if (networkFlight === pending) networkFlight = null; });
85
+ networkFlight = pending;
86
+ }
87
+ return networkFlight;
88
+ }
89
+ function applyCatalog(value, source, savedAt) {
90
+ catalog = m365Catalog(value);catalogAt = savedAt;
91
+ registry.models = { data: m365Models(catalog, "gpt").map(model => ({ ...model,
92
+ vendor: "OpenAI", model_picker_enabled: true, policy: { state: "enabled" } })) };
93
+ registry.source = source;registry.cacheSavedAtMs = savedAt;registry.cacheState = now() - savedAt < SOFT_TTL_MS ? "fresh" : "stale";
94
+ }
95
+ try {
96
+ account = readM365Account({ home });
97
+ const saved = readM365Json(paths.catalog);
98
+ if (account && saved?.account_key === m365AccountKey(account) && Number.isFinite(saved.saved_at)
99
+ && now() - saved.saved_at < HARD_TTL_MS) applyCatalog(saved.models, "cache", saved.saved_at);
100
+ } catch { reason = "m365_cache_unavailable"; }
101
+
102
+ async function request(endpoint, body, options = {}) {
103
+ if (state === "disabled") throw m365Error("m365_disabled");
104
+ if (!["/models", "/responses", "/v1/responses", "/v1/messages", "/v1/messages/count_tokens"].includes(endpoint)) throw m365Error("m365_endpoint_invalid");
105
+ const credential = await auth.getToken({ signal: options.signal });
106
+ if (account && m365AccountKey(credential.account) !== m365AccountKey(account)) throw m365Error("m365_account_changed");
107
+ const requestHeaders = m365Headers(credential.token, { ...options,
108
+ conversationId: body ? m365ConversationId(body, options.headers, m365AccountKey(credential.account)) : undefined,
109
+ stream: body?.stream === true });
110
+ const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
111
+ if (serialized !== undefined) requestHeaders["Content-Length"] = String(Buffer.byteLength(serialized));
112
+ options.onUpstreamStart?.();
113
+ if (body) markUpstreamStarted(body.stream === true);
114
+ try {
115
+ const send = fetchImpl || await transport(options.signal);
116
+ const response = await send(`${M365_API_BASE}${endpoint}`, { method: body ? "POST" : "GET", headers: requestHeaders,
117
+ ...(serialized !== undefined ? { body: serialized } : {}), signal: options.signal, redirect: "manual" });
118
+ if (response.ok) return response;
119
+ const raw = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, label: "M365 error", signal: options.signal });
120
+ const safe = raw.split(credential.token).join("[redacted]");
121
+ const headers = new Headers(response.headers);headers.delete("content-length");headers.delete("content-encoding");
122
+ return new Response(safe, { status: response.status, headers });
123
+ } catch (error) {
124
+ if (options.signal?.aborted) throw options.signal.reason || error;
125
+ throw Object.assign(new Error(redactDiagnosticText(String(error.message).split(credential.token).join("[redacted]"))), {
126
+ code: /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : "m365_network_error", statusCode: 502 });
127
+ }
128
+ }
129
+
130
+ function refresh() {
131
+ if (state === "disabled") return Promise.reject(m365Error("m365_disabled"));
132
+ if (flight) return flight;
133
+ const current = ++generation;
134
+ state = "checking";registry.refreshInFlight = true;registry.generation = current;
135
+ controller = new AbortController();
136
+ const signal = controller.signal, timer = setTimeout(() => controller.abort(), 30000);
137
+ const pending = (async () => {
138
+ const credential = await auth.getToken({ signal });
139
+ const response = await request("/models", null, { signal });
140
+ const raw = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES, label: "M365 model catalog", signal });
141
+ if (!response.ok) throw m365Error(`m365_catalog_http_${response.status}`);
142
+ let value;try { value = m365Catalog(JSON.parse(raw)); } catch { throw m365Error("m365_catalog_invalid"); }
143
+ if (current !== generation || signal.aborted) throw m365Error("m365_refresh_cancelled");
144
+ account = credential.account;
145
+ writeM365Json(paths.account, account);
146
+ writeM365Json(paths.catalog, { account_key: m365AccountKey(account), saved_at: now(), models: value });
147
+ applyCatalog(value, "live", now());state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
148
+ try { await onCatalog(value); } catch { log("warn", "M365 models are ready; optional client configuration could not be updated"); }
149
+ return value;
150
+ })().catch(error => {
151
+ if (current === generation) {
152
+ state = "unavailable";reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : "m365_unavailable";
153
+ registry.lastError = reason;registry.lastErrorAtMs = now();
154
+ }
155
+ throw error;
156
+ }).finally(() => { clearTimeout(timer);if (flight === pending) { flight = null;controller = null;registry.refreshInFlight = false; } });
157
+ flight = pending;
158
+ return pending;
159
+ }
160
+
161
+ function selectedModel(id, family) {
162
+ const models = m365Models(catalog, family);
163
+ const model = models.find(entry => entry.id === id || (family === "claude" && entry.id.replace(/(\d+)\.(\d+)$/, "$1-$2") === id));
164
+ if (!model) throw protocolError("m365_model_unavailable", `Model ${String(id).slice(0, 128)} is not available from Microsoft 365. Select a model from its current catalog.`);
165
+ return model;
166
+ }
167
+
168
+ const client = {
169
+ async listModels({ signal } = {}) {
170
+ signal?.throwIfAborted();
171
+ if (!catalog) await refresh();
172
+ else if (now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
173
+ signal?.throwIfAborted();
174
+ if (!registry.models) throw m365Error(reason || "m365_catalog_unavailable");
175
+ return { status: 200, body: JSON.stringify(registry.models) };
176
+ },
177
+ getCachedModelEndpoints: id => catalog?.data.find(model => model.id === id)?.supported_endpoints || null,
178
+ cacheModelEndpoints() {},
179
+ async responses(body, options = {}) {
180
+ const model = selectedModel(body.model, "gpt");
181
+ const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
182
+ currentInputStart: options.currentInputStart || 0, signal: options.signal,
183
+ profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
184
+ skipInitialOptimization: options.payloadPrepared || options.payloadOptions?.skipInitialOptimization });
185
+ const final = enforceResponsesPayloadByteBudget(body, prepared, { assertActive: options.assertActive });
186
+ const summary = final.stage === prepared.stage ? prepared.summary : summarizeReqBody(body);
187
+ markRequestObservation({ payload_bytes: final.bodyBytes, images: summary.images });
188
+ const context = currentRequestContext();if (context) context.requestOptions = requestOptionsEvidence(body);
189
+ log("info", `responses provider=m365 payload bytes=${final.bodyBytes} input_items=${summary.items} images=${summary.images}`);
190
+ return request(model.supported_endpoints.includes("/responses") ? "/responses" : "/v1/responses", body,
191
+ { ...options, headers: context?.clientHeaders, bodyText: final.bodyText });
192
+ },
193
+ responsesCompact(body, options) { return client.responses(body, options); },
194
+ chatCompletions() { throw protocolError("m365_protocol_unsupported", "Microsoft 365 Codex routing requires native Responses"); },
195
+ async messages(body, options = {}) {
196
+ const model = selectedModel(body.model, "claude");
197
+ const adjusted = limitM365CacheTtl(body);
198
+ if (adjusted.changed && !cacheTtlAdjustments) log("info", "Microsoft 365 supports 5m prompt caching; 1h cache retention is capped to 5m. Content and breakpoints are unchanged.");
199
+ cacheTtlAdjustments += adjusted.changed;
200
+ return request(options.countTokens ? "/v1/messages/count_tokens" : "/v1/messages", model.id === adjusted.body.model ? adjusted.body : { ...adjusted.body, model: model.id }, options);
201
+ },
202
+ runtimeStatus: () => ({ ...auth.snapshot(), account_bound: Boolean(account), upstream_host: new URL(M365_API_BASE).hostname,
203
+ model_endpoint_cache_entries: catalog?.data.length || 0, model_list_flights: flight ? 1 : 0 }),
204
+ };
205
+ return {
206
+ id: "m365", client, registry, auth, refresh, profileId: profile,
207
+ models: family => m365Models(catalog, family),
208
+ selectModel(body, { requestedModel, upstreamModel }) {
209
+ selectedModel(upstreamModel, "gpt");
210
+ if (requestedModel !== CODEX_AUTO_REVIEW_MODEL && body.service_tier === "priority") {
211
+ throw protocolError("m365_priority_unverified", "Microsoft 365 does not advertise a verified fast tier. Select Standard or switch back to GitHub Copilot.");
212
+ }
213
+ return { upstreamModel, forceResponses: true };
214
+ },
215
+ route(_body, { upstreamModel, surface }) {
216
+ return createRoutePlan({ disposition: "relay", origin: "m365", profile: profile(), protocol: "openai-responses", model: upstreamModel, surface });
217
+ },
218
+ // Loki rejects the native image_generation declaration; the independent
219
+ // CCDX image functions/MCP remain available through their existing names.
220
+ applyRequestPolicies: body => removeNativeImageTools(body),
221
+ compatibility: {
222
+ hasRetry: () => false, selectRetry: async () => null,
223
+ async openResponse(context, upstream, options) {
224
+ const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal,
225
+ currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart });
226
+ markUpstreamHeaders(resp.status);
227
+ const errorText = resp.ok ? undefined : await readBoundedResponseText(resp, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, label: "M365 response error", signal: options.signal });
228
+ return { resp, reqContext: context, errorText, usedRetryPolicies: new Set() };
229
+ },
230
+ },
231
+ snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login } : null,
232
+ network: network?.snapshot() || null,
233
+ cache_ttl_adjustments: cacheTtlAdjustments,
234
+ models: { total: catalog?.data.length || 0, claude: m365Models(catalog, "claude").length, gpt: m365Models(catalog, "gpt").length,
235
+ source: registry.source, refreshed_at: catalogAt ? new Date(catalogAt).toISOString() : null }, refresh_in_flight: Boolean(flight) }),
236
+ close() { state = "disabled";generation += 1;controller?.abort();auth.reset();network?.close();network = null; },
237
+ };
238
+ }
@@ -30,6 +30,7 @@ export function responseFailureDetails(event, eventType = event?.type, {
30
30
  retried = false,
31
31
  retryPolicy = null,
32
32
  retrySkipped = null,
33
+ provider = currentRequestContext()?.provider,
33
34
  } = {}) {
34
35
  const response = event?.response && typeof event.response === "object" ? event.response : event;
35
36
  const error = response?.error && typeof response.error === "object"
@@ -40,6 +41,7 @@ export function responseFailureDetails(event, eventType = event?.type, {
40
41
  return {
41
42
  at: new Date().toISOString(),
42
43
  request_id: currentRequestContext()?.requestId || null,
44
+ ...(["github", "m365"].includes(provider) ? { provider } : {}),
43
45
  event_type: safeIdentifier(eventType || "response.failed"),
44
46
  model: safeIdentifier(response?.model || model),
45
47
  code: safeIdentifier(error?.code || "unknown_error"),
@@ -83,26 +85,85 @@ export function createResponseFailureDiagnostics({
83
85
  const recent = [];
84
86
  let total = 0;
85
87
  let retried = 0;
88
+ const copy = entry => ({ ...entry,
89
+ ...(entry.request_options ? { request_options: { ...entry.request_options } } : {}),
90
+ ...(entry.attempt_timings ? { attempt_timings: entry.attempt_timings.map(attempt => ({ ...attempt })) } : {}),
91
+ });
86
92
  return {
87
93
  record(details) {
88
94
  total += 1;
89
95
  if (details.retried) retried += 1;
90
- recent.push({ ...details, at: now() });
96
+ recent.push(copy({ ...details, at: now() }));
91
97
  if (recent.length > maxEntries) recent.splice(0, recent.length - maxEntries);
92
98
  },
93
99
  snapshot() {
94
100
  return {
95
101
  total,
96
102
  retried,
97
- recent: recent.map((entry) => ({ ...entry })),
103
+ recent: recent.map(copy),
98
104
  };
99
105
  },
100
106
  };
101
107
  }
102
108
 
103
- export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers }) {
109
+ export function upstreamErrorEvidence(text, { includeMessage = false } = {}) {
110
+ const errorBody = !String(text || "").trim() ? "empty" : "unstructured";
111
+ let error;
112
+ try { const parsed = JSON.parse(text); error = parsed?.error; } catch {}
113
+ if (!error || typeof error !== "object" || Array.isArray(error)) return { error_body: errorBody,
114
+ ...(includeMessage && errorBody !== "empty" ? { diagnostic_message: safeFailureMessage(typeof error === "string" ? error : text) } : {}) };
115
+ const technical = value => typeof value === "string" && /^[a-z\d_.:-]{1,80}$/i.test(value)
116
+ && redactDiagnosticText(value) === value ? value : undefined;
117
+ const param = typeof error.param === "string" && error.param.length <= 160
118
+ && /^(?:model|input|tools|tool_choice|reasoning|text|temperature|top_p|max_output_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
119
+ ? error.param : undefined;
120
+ return { error_body: "structured", code: technical(error.code), error_type: technical(error.type),
121
+ parameter: param, ...(includeMessage && typeof error.message === "string" ? { diagnostic_message: safeFailureMessage(error.message) } : {}) };
122
+ }
123
+
124
+ export function requestOptionsEvidence(body) {
125
+ const result = {};
126
+ if (!body || typeof body !== "object") return result;
127
+ if (["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"].includes(body.reasoning?.effort)) result.reasoning_effort = body.reasoning.effort;
128
+ if (["auto", "default", "flex", "priority", "scale"].includes(body.service_tier)) result.service_tier = body.service_tier;
129
+ if (["text", "json_object", "json_schema"].includes(body.text?.format?.type)) result.output_format = body.text.format.type;
130
+ if (Number.isSafeInteger(body.max_output_tokens) && body.max_output_tokens >= 0) result.max_output_tokens = body.max_output_tokens;
131
+ if (Array.isArray(body.tools)) result.tools = body.tools.length;
132
+ if (Array.isArray(body.input)) result.input_items = body.input.length;
133
+ return result;
134
+ }
135
+
136
+ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
137
+ const all = createResponseFailureDiagnostics({ maxEntries, now });
138
+ const actionable = createResponseFailureDiagnostics({ maxEntries, now });
139
+ const protocol = createResponseFailureDiagnostics({ maxEntries: 8, now });
140
+ const counts = { inference: 0, protocol: 0, route: 0, other: 0 };
141
+ return {
142
+ record(details) {
143
+ all.record(details);
144
+ const category = ["responses", "responses_compact"].includes(details.route) ? "inference"
145
+ : details.route === "image_mcp" && details.http_status === 405 ? "protocol"
146
+ : details.route === "not_found" ? "route" : "other";
147
+ counts[category]++;
148
+ if (category === "inference" || category === "other") actionable.record(details);
149
+ if (category === "protocol") protocol.record(details);
150
+ },
151
+ snapshot() { return { ...all.snapshot(), by_category: { ...counts },
152
+ actionable_recent: actionable.snapshot().recent, protocol_recent: protocol.snapshot().recent }; },
153
+ };
154
+ }
155
+
156
+ export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers,
157
+ error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider }) {
104
158
  const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
105
- message: "HTTP request failed; original response was preserved." } }, "http.error", { headers });
159
+ message: error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved." } }, "http.error", { headers, provider });
106
160
  return { ...details, request_id: requestId, http_status: statusCode, route,
107
- origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true };
161
+ origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
162
+ ...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}), ...(parameter ? { parameter } : {}),
163
+ ...(diagnostic_message ? { diagnostic_message } : {}),
164
+ ...(method ? { method } : {}), ...(target ? { target } : {}),
165
+ ...(request_options ? { request_options } : {}),
166
+ ...(attempt_timings ? { attempt_timings } : {}),
167
+ ...(requested_model ? { requested_model, request_kind: requested_model === "codex-auto-review" ? "auto_review" : "unknown" } : {}),
168
+ ...(Number.isSafeInteger(upstream_attempts) ? { upstream_attempts } : {}) };
108
169
  }