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.
Files changed (50) hide show
  1. package/README.md +23 -2
  2. package/bin/cli.mjs +38 -11
  3. package/docs/ARCHITECTURE.md +62 -8
  4. package/docs/REFERENCE.md +161 -4
  5. package/package.json +4 -1
  6. package/src/adapter.mjs +83 -22
  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 +6 -0
  14. package/src/codex-model-catalog.mjs +7 -2
  15. package/src/copilot-responses-policy.mjs +2 -64
  16. package/src/dashboard/index.html +11 -1
  17. package/src/dashboard/language.js +26 -0
  18. package/src/dashboard/status.js +16 -2
  19. package/src/dashboard/ui.css +2 -2
  20. package/src/dashboard/ui.js +16 -7
  21. package/src/dashboard/usage.js +3 -1
  22. package/src/dashboard-api.mjs +10 -7
  23. package/src/doctor-repair.mjs +2 -0
  24. package/src/doctor.mjs +18 -2
  25. package/src/m365-settings.mjs +89 -0
  26. package/src/native-prediction-windows.mjs +2 -7
  27. package/src/profile-model-runtime.mjs +4 -2
  28. package/src/provider-management.mjs +28 -0
  29. package/src/provider-runtime.mjs +180 -0
  30. package/src/provider-settings.mjs +32 -0
  31. package/src/providers/github.mjs +62 -0
  32. package/src/providers/m365-auth-helper.mjs +72 -0
  33. package/src/providers/m365-auth.mjs +105 -0
  34. package/src/providers/m365-messages-policy.mjs +20 -0
  35. package/src/providers/m365-network.mjs +73 -0
  36. package/src/providers/m365.mjs +238 -0
  37. package/src/response-failures.mjs +4 -2
  38. package/src/response-history.mjs +20 -3
  39. package/src/responses-handler.mjs +40 -95
  40. package/src/responses-image-tools.mjs +61 -0
  41. package/src/responses-proxy.mjs +5 -5
  42. package/src/responses-request.mjs +25 -0
  43. package/src/stream-performance.mjs +7 -4
  44. package/src/usage-analysis.mjs +3 -2
  45. package/src/usage-store.mjs +41 -12
  46. package/src/usage.mjs +8 -2
  47. package/src/windows-http-network.mjs +122 -0
  48. package/src/windows-prediction-network.cs +13 -6
  49. package/src/windows-prediction-network.mjs +4 -108
  50. package/src/windows-process.mjs +8 -0
@@ -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.1", "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"),
@@ -152,9 +154,9 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
152
154
  }
153
155
 
154
156
  export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers,
155
- error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model }) {
157
+ error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider }) {
156
158
  const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
157
- message: error_body === "empty" ? "Upstream returned no error details." : "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 });
158
160
  return { ...details, request_id: requestId, http_status: statusCode, route,
159
161
  origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
160
162
  ...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}), ...(parameter ? { parameter } : {}),
@@ -1,10 +1,25 @@
1
1
  import { httpError } from "./http-errors.mjs";
2
2
  import { clearResponsesToolOutputPartsCache } from "./responses-content.mjs";
3
3
  import { loadRuntimeConfig, parsePositiveInteger, RUNTIME_DEFAULTS } from "./runtime-config.mjs";
4
+ import { currentRequestContext } from "./request-context.mjs";
4
5
 
5
6
  const DEFAULT_MAX_BYTES = RUNTIME_DEFAULTS.responseHistoryMaxBytes;
6
7
  const DEFAULT_MAX_ENTRIES = RUNTIME_DEFAULTS.responseHistoryMaxEntries;
7
8
 
9
+ function historyKey(id, namespace = currentRequestContext()?.historyNamespace) {
10
+ if (typeof id === "string" && id.includes("\0")) throw httpError("Invalid previous_response_id", 400);
11
+ return namespace && id ? `\0${namespace}\0${id}` : id;
12
+ }
13
+
14
+ function readableHistoryKey(id) {
15
+ const current = historyKey(id), transfer = currentRequestContext()?.historyTransferNamespace;
16
+ if (!transfer) return current;
17
+ const previous = historyKey(id, transfer);
18
+ if (previous === current) return current;
19
+ if (histories.has(current) && histories.has(previous)) throw httpError("previous_response_id is ambiguous across providers; replay the full plaintext conversation", 400);
20
+ return histories.has(current) ? current : previous;
21
+ }
22
+
8
23
  function cloneJson(value) {
9
24
  return value === undefined ? undefined : structuredClone(value);
10
25
  }
@@ -278,13 +293,13 @@ export function responseHistoryStats() {
278
293
  }
279
294
 
280
295
  export function responseHistoryRootId(responseId) {
281
- return histories.get(responseId)?.rootId || null;
296
+ return histories.get(readableHistoryKey(responseId))?.rootId || null;
282
297
  }
283
298
 
284
299
  function responseHistoryChain(responseId) {
285
300
  const chain = [];
286
301
  const seen = new Set();
287
- let currentId = responseId;
302
+ let currentId = readableHistoryKey(responseId);
288
303
  while (currentId) {
289
304
  if (seen.has(currentId)) throw httpError(`Cycle detected in local response history: ${currentId}`, 500);
290
305
  seen.add(currentId);
@@ -294,7 +309,7 @@ function responseHistoryChain(responseId) {
294
309
  const wasEvicted = evictedIds.has(currentId);
295
310
  if (wasEvicted) evictedLookupMisses += 1;
296
311
  const reason = wasEvicted ? " was evicted after reaching the local history limit" : " is not available";
297
- throw httpError(`previous_response_id${reason}: ${currentId}`, 400);
312
+ throw httpError(`previous_response_id${reason}: ${String(currentId).split("\0").at(-1)}`, 400);
298
313
  }
299
314
  chain.push(entry);
300
315
  currentId = entry.parentId;
@@ -381,6 +396,8 @@ export function rememberResponseHistoryNode({
381
396
  takeOwnership = false,
382
397
  }) {
383
398
  if (!id || !Array.isArray(inputItems)) return false;
399
+ id = historyKey(id);
400
+ parentId = parentId ? historyKey(parentId) : null;
384
401
  const existing = histories.get(id);
385
402
  const parentEntry = parentId ? histories.get(parentId) : null;
386
403
  if (parentId && !parentEntry) {