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,217 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { execFile } from "node:child_process";
6
+ import { promisify } from "node:util";
7
+ import { readBoundedFileSync } from "./bounded-file.mjs";
8
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
9
+ import { withFileLockSync } from "./lock.mjs";
10
+ import { m365Paths, readM365Json, writeM365Json } from "./m365-settings.mjs";
11
+
12
+ export const M365_CLAUDE_PROFILE_ID = "00000000-0000-4000-8000-000000202700";
13
+ const M365_CLAUDE_PROFILE_NAME = "CCDX Microsoft 365";
14
+
15
+ export function claudeClientPaths({ home = os.homedir(), platform = process.platform, env = process.env } = {}) {
16
+ const base = platform === "win32" ? env.LOCALAPPDATA || path.join(home, "AppData", "Local")
17
+ : platform === "darwin" ? path.join(home, "Library", "Application Support") : env.XDG_CONFIG_HOME || path.join(home, ".config");
18
+ const normalBase = platform === "win32" ? env.APPDATA || path.join(home, "AppData", "Roaming") : base;
19
+ const library = path.join(base, "Claude-3p", "configLibrary");
20
+ return { code: path.join(env.CLAUDE_CONFIG_DIR || path.join(home, ".claude"), "settings.json"),
21
+ normal: path.join(normalBase, "Claude", "claude_desktop_config.json"),
22
+ threep: path.join(base, "Claude-3p", "claude_desktop_config.json"),
23
+ meta: path.join(library, "_meta.json"), profile: path.join(library, `${M365_CLAUDE_PROFILE_ID}.json`) };
24
+ }
25
+
26
+ function read(file) {
27
+ try {
28
+ if (!fs.lstatSync(file).isFile()) throw Error();
29
+ const bytes = readBoundedFileSync(file, { maxBytes: 1024 * 1024 });
30
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
31
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error();
32
+ return { exists: true, bytes, value };
33
+ } catch (error) {
34
+ if (error.code === "ENOENT") return { exists: false, bytes: null, value: {} };
35
+ throw Object.assign(new Error("Claude configuration is unreadable; existing files were preserved"), { code: "claude_config_unreadable" });
36
+ }
37
+ }
38
+ function valueAt(object, keys) {
39
+ const parent = keys.slice(0, -1).reduce((v, k) => v && Object.hasOwn(v, k) ? v[k] : undefined, object);
40
+ return parent && typeof parent === "object" && Object.hasOwn(parent, keys.at(-1)) ? { exists: true, value: parent[keys.at(-1)] } : { exists: false };
41
+ }
42
+ function setAt(object, keys, value) {
43
+ let parent = object;
44
+ for (const key of keys.slice(0, -1)) {
45
+ if (parent[key] === undefined) parent[key] = {};
46
+ if (!parent[key] || typeof parent[key] !== "object" || Array.isArray(parent[key])) throw new Error("Claude configuration has a conflicting parent field");
47
+ parent = parent[key];
48
+ }
49
+ if (value.exists) parent[keys.at(-1)] = value.value;
50
+ else {
51
+ delete parent[keys.at(-1)];
52
+ if (keys.length === 2 && Object.keys(parent).length === 0) delete object[keys[0]];
53
+ }
54
+ }
55
+
56
+ export async function inspectClaudeDesktopPolicy({ platform = process.platform, home = os.homedir(), env = process.env,
57
+ execFileImpl = promisify(execFile) } = {}) {
58
+ if (platform === "darwin") {
59
+ const files = ["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",
60
+ path.join("/Library/Managed Preferences", os.userInfo().username, "com.anthropic.claudefordesktop.plist"),
61
+ path.join(home, "Library", "Managed Preferences", "com.anthropic.claudefordesktop.plist")];
62
+ return files.some(file => fs.existsSync(file));
63
+ }
64
+ if (platform === "win32") {
65
+ const reg = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
66
+ for (const key of ["HKLM\\SOFTWARE\\Policies\\Claude", "HKCU\\SOFTWARE\\Policies\\Claude"]) {
67
+ try { await execFileImpl(reg, ["query", key], { encoding: "utf8", timeout: 3000, maxBuffer: 32768, windowsHide: true });return true; }
68
+ catch (error) { if (error.code !== 1) return true; }
69
+ }
70
+ }
71
+ return false;
72
+ }
73
+
74
+ function operationValue(snapshot, operation) {
75
+ const field = valueAt(snapshot, operation.keys);
76
+ if (!operation.itemId) return field;
77
+ const item = Array.isArray(field.value) ? field.value.find(value => value?.id === operation.itemId) : undefined;
78
+ return item ? { exists: true, value: item } : { exists: false };
79
+ }
80
+ function setOperation(snapshot, operation, value) {
81
+ if (!operation.itemId) { setAt(snapshot, operation.keys, value);return; }
82
+ const current = valueAt(snapshot, operation.keys);
83
+ if (current.exists && !Array.isArray(current.value)) throw new Error("Claude profile list is invalid");
84
+ const next = (current.value || []).filter(item => item?.id !== operation.itemId);
85
+ if (value.exists) next.push(value.value);
86
+ setAt(snapshot, operation.keys, { exists: true, value: next });
87
+ }
88
+
89
+ function reconcile(operations, { restore = false, ...options } = {}) {
90
+ const paths = claudeClientPaths(options), allowed = new Set(Object.values(paths)), journalPath = m365Paths(options).ownership;
91
+ fs.mkdirSync(path.dirname(journalPath), { recursive: true, mode: 0o700 });
92
+ return withFileLockSync(`${journalPath}.lock`, () => {
93
+ const journal = readM365Json(journalPath, { version: 1, operations: [] });
94
+ const keys = new Map([
95
+ [paths.code, new Set(["env.ANTHROPIC_BASE_URL", "env.ANTHROPIC_AUTH_TOKEN", "env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS", "env.ANTHROPIC_CUSTOM_HEADERS", "env.ANTHROPIC_MODEL"])],
96
+ [paths.normal, new Set(["deploymentMode"])], [paths.threep, new Set(["deploymentMode"])],
97
+ [paths.meta, new Set(["entries", "appliedId"])],
98
+ [paths.profile, new Set(["inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayApiKey", "inferenceGatewayAuthScheme", "inferenceModels", "inferenceCustomHeaders"])],
99
+ ]);
100
+ if (journal.version !== 1 || !Array.isArray(journal.operations) || journal.operations.some(op => !allowed.has(op.file)
101
+ || !Array.isArray(op.keys) || !keys.get(op.file)?.has(op.keys.join("."))
102
+ || op.itemId !== undefined && (op.file !== paths.meta || op.keys.join(".") !== "entries" || op.itemId !== M365_CLAUDE_PROFILE_ID))) {
103
+ throw new Error("Claude configuration ownership is invalid; files were preserved");
104
+ }
105
+ const states = new Map(), pending = [], nextJournal = structuredClone(journal), skipped = [];
106
+ const list = restore ? journal.operations : operations;
107
+ for (const operation of list) {
108
+ if (!allowed.has(operation.file)) throw new Error("Unexpected Claude configuration path");
109
+ if (!states.has(operation.file)) states.set(operation.file, read(operation.file));
110
+ const state = states.get(operation.file);state.next ||= structuredClone(state.value);
111
+ const previous = journal.operations.find(op => op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId);
112
+ const current = operationValue(state.next, operation), desired = restore ? operation.before : { exists: true, value: operation.value };
113
+ if (restore) {
114
+ if (!isDeepStrictEqual(current, { exists: true, value: operation.after })) { skipped.push(operation.file);continue; }
115
+ setOperation(state.next, operation, desired);
116
+ nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
117
+ } else {
118
+ if (isDeepStrictEqual(current, desired)) continue;
119
+ const replaceMode = operation.keys.join(".") === "deploymentMode" && [paths.normal, paths.threep].includes(operation.file)
120
+ && current.value === "1p";
121
+ if (current.exists && !replaceMode && (!previous || !isDeepStrictEqual(current, { exists: true, value: previous.after }))) { skipped.push(operation.file);continue; }
122
+ const entry = { file: operation.file, keys: operation.keys, ...(operation.itemId ? { itemId: operation.itemId } : {}),
123
+ before: previous?.before || current, after: operation.value };
124
+ setOperation(state.next, operation, desired);
125
+ nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
126
+ nextJournal.operations.push(entry);
127
+ }
128
+ }
129
+ // Record ownership before client writes so interruption remains recoverable.
130
+ const oldJournal = journal;
131
+ if (!restore) writeM365Json(journalPath, nextJournal);
132
+ try {
133
+ for (const [file, state] of states) {
134
+ if (isDeepStrictEqual(state.value, state.next)) continue;
135
+ const latest = read(file);
136
+ if (latest.exists !== state.exists || latest.bytes?.equals(state.bytes) === false) throw new Error("Claude configuration changed during setup; retry after the other writer finishes");
137
+ const bytes = Buffer.from(`${JSON.stringify(state.next, null, 2)}\n`);
138
+ atomicWriteFileSync(file, bytes, { mode: 0o600, preserveMode: false });pending.push({ file, state, bytes });
139
+ }
140
+ if (restore) writeM365Json(journalPath, nextJournal);
141
+ } catch (error) {
142
+ for (const entry of pending.reverse()) {
143
+ const latest = read(entry.file);
144
+ if (!latest.bytes?.equals(entry.bytes)) continue;
145
+ if (entry.state.exists) atomicWriteFileSync(entry.file, entry.state.bytes, { mode: 0o600 });
146
+ else fs.unlinkSync(entry.file);
147
+ }
148
+ writeM365Json(journalPath, oldJournal);throw error;
149
+ }
150
+ return { changed: pending.length > 0, preserved: [...new Set(skipped)].length, remaining: nextJournal.operations.length };
151
+ });
152
+ }
153
+
154
+ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, ...options } = {}) {
155
+ const paths = claudeClientPaths(options), ids = models.map(model => model.id), operations = [], result = {};
156
+ const endpoint = new URL(baseUrl);
157
+ if (endpoint.protocol !== "http:" || endpoint.hostname !== "127.0.0.1" || endpoint.pathname !== "/" || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new Error("Claude gateway must use a local root URL");
158
+ const add = (file, keys, value, itemId) => operations.push({ file, keys, value, ...(itemId ? { itemId } : {}) });
159
+ const env = options.env || process.env;
160
+ let code;
161
+ try { code = read(paths.code).value; } catch { result.code = "configuration_unavailable"; }
162
+ const codeEnv = code?.env || {};
163
+ const envConflict = env.ANTHROPIC_BASE_URL && env.ANTHROPIC_BASE_URL !== baseUrl
164
+ || env.ANTHROPIC_AUTH_TOKEN && env.ANTHROPIC_AUTH_TOKEN !== apiKey
165
+ || codeEnv.ANTHROPIC_AUTH_TOKEN && codeEnv.ANTHROPIC_AUTH_TOKEN !== apiKey
166
+ || env.ANTHROPIC_API_KEY && env.ANTHROPIC_API_KEY !== apiKey
167
+ || codeEnv.ANTHROPIC_API_KEY && codeEnv.ANTHROPIC_API_KEY !== apiKey
168
+ || code?.apiKeyHelper
169
+ || ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_USE_ANTHROPIC_AWS", "CLAUDE_CODE_USE_GATEWAY"].some(key => /^(1|true)$/i.test(env[key] || codeEnv[key] || ""));
170
+ if (!code) { /* Keep independent App setup available when Code settings are damaged. */ }
171
+ else if (envConflict || codeEnv.ANTHROPIC_BASE_URL && codeEnv.ANTHROPIC_BASE_URL !== baseUrl) result.code = "preserved";
172
+ else {
173
+ add(paths.code, ["env", "ANTHROPIC_BASE_URL"], baseUrl);
174
+ add(paths.code, ["env", "ANTHROPIC_AUTH_TOKEN"], apiKey);
175
+ add(paths.code, ["env", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"], "1");
176
+ if (env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS === undefined) add(paths.code, ["env", "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"], "1");
177
+ add(paths.code, ["env", "ANTHROPIC_CUSTOM_HEADERS"], "X-CCDX-Client: claude-code");
178
+ if (!codeEnv.ANTHROPIC_MODEL && ids.length) add(paths.code, ["env", "ANTHROPIC_MODEL"], ids[0]);
179
+ result.code = "configured";
180
+ }
181
+ const installed = desktopInstalled ?? (fs.existsSync(path.dirname(paths.normal)) || fs.existsSync(path.dirname(paths.threep))
182
+ || (options.platform || process.platform) === "darwin" && fs.existsSync("/Applications/Claude.app"));
183
+ if (!installed) result.app = "not_installed";
184
+ else if (desktopManaged !== false || env.CLAUDE_USER_DATA_DIR) result.app = "preserved";
185
+ else {
186
+ let meta, profile;
187
+ try { meta = read(paths.meta).value;profile = read(paths.profile).value; } catch { result.app = "configuration_unavailable"; }
188
+ if (!meta) { /* Code setup remains independent. */ }
189
+ else if (meta.hybridPointer || meta.appliedId && meta.appliedId !== M365_CLAUDE_PROFILE_ID
190
+ || profile.inferenceProvider && profile.inferenceProvider !== "gateway"
191
+ || profile.inferenceGatewayBaseUrl && profile.inferenceGatewayBaseUrl !== baseUrl
192
+ || profile.inferenceGatewayApiKey && profile.inferenceGatewayApiKey !== apiKey) result.app = "preserved";
193
+ else {
194
+ add(paths.profile, ["inferenceProvider"], "gateway");
195
+ add(paths.profile, ["inferenceGatewayBaseUrl"], baseUrl);
196
+ add(paths.profile, ["inferenceGatewayApiKey"], apiKey);
197
+ add(paths.profile, ["inferenceGatewayAuthScheme"], "bearer");
198
+ add(paths.profile, ["inferenceModels"], JSON.stringify(ids));
199
+ add(paths.profile, ["inferenceCustomHeaders"], JSON.stringify({ "X-CCDX-Client": "claude-app" }));
200
+ add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: M365_CLAUDE_PROFILE_NAME }, M365_CLAUDE_PROFILE_ID);
201
+ add(paths.meta, ["appliedId"], M365_CLAUDE_PROFILE_ID);
202
+ add(paths.threep, ["deploymentMode"], "3p");
203
+ result.app = "configured";
204
+ }
205
+ }
206
+ const applied = reconcile(operations, options);
207
+ if (applied.preserved) {
208
+ if (result.code === "configured") result.code = "partially_preserved";
209
+ if (result.app === "configured") result.app = "partially_preserved";
210
+ }
211
+ return { ...result, changed: applied.changed };
212
+ }
213
+
214
+ export function restoreClaudeClients(options = {}) {
215
+ if (!fs.existsSync(m365Paths(options).ownership)) return { changed: false, preserved: 0, remaining: 0 };
216
+ return reconcile([], { ...options, restore: true });
217
+ }
@@ -0,0 +1,163 @@
1
+ import http from "node:http";
2
+ import { randomUUID, timingSafeEqual } from "node:crypto";
3
+ import { createRequestAbort, readJsonBody, readBoundedResponseText, writeOrDrain, MAX_UPSTREAM_ERROR_BODY_BYTES } from "./http-transport.mjs";
4
+ import { createRequestAdmission } from "./request-admission.mjs";
5
+ import { loadRuntimeConfig } from "./runtime-config.mjs";
6
+ import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
7
+ import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
8
+ import { runWithRequestContext } from "./request-context.mjs";
9
+ import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
10
+ import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
11
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
12
+ import { decodedBodyLimitPreference } from "./user-settings.mjs";
13
+
14
+ function send(res, code, value) {
15
+ if (res.destroyed || res.writableEnded) return;
16
+ res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
17
+ }
18
+ const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
19
+ function authenticated(headers, key) {
20
+ const candidates = [headers["x-api-key"], typeof headers.authorization === "string" ? /^Bearer (.+)$/i.exec(headers.authorization)?.[1] : null];
21
+ const expected = Buffer.from(key);
22
+ return candidates.some(value => typeof value === "string" && Buffer.byteLength(value) === expected.length && timingSafeEqual(Buffer.from(value), expected));
23
+ }
24
+
25
+ // Observe bounded SSE frames while retaining the original wire bytes for the
26
+ // client. A slow client controls upstream reads; there is no independent tee.
27
+ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024) {
28
+ const decoder = new TextDecoder();let fragments = [], lineBytes = 0, data = [], frameBytes = 0;
29
+ const frame = () => {
30
+ if (data.length) { let value;try { value = JSON.parse(data.join("\n")); } catch { throw new Error("Invalid Claude stream event"); }onEvent(value); }
31
+ data = [];frameBytes = 0;
32
+ };
33
+ const line = value => {
34
+ if (value.endsWith("\r")) value = value.slice(0, -1);
35
+ if (!value) frame();
36
+ else if (value.startsWith("data:")) {
37
+ const part = value.slice(5).replace(/^ /, "");frameBytes += Buffer.byteLength(part);
38
+ if (frameBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");data.push(part);
39
+ }
40
+ };
41
+ function consume(text) {
42
+ let start = 0;
43
+ while (start < text.length) {
44
+ const newline = text.indexOf("\n", start), end = newline < 0 ? text.length : newline, part = text.slice(start, end);
45
+ lineBytes += Buffer.byteLength(part);
46
+ if (lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
47
+ fragments.push(part);
48
+ if (newline < 0) break;
49
+ line(fragments.join(""));fragments = [];lineBytes = 0;start = newline + 1;
50
+ }
51
+ }
52
+ return { write(chunk) { consume(decoder.decode(chunk, { stream: true })); },
53
+ finish() { consume(decoder.decode());if (fragments.length) line(fragments.join(""));frame(); } };
54
+ }
55
+
56
+ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, onRequest = () => {}, env = process.env,
57
+ record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
58
+ if (!provider || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
59
+ const config = loadRuntimeConfig(env), performance = createStreamPerformanceMetrics({ routeNames: ["messages"] });
60
+ const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
61
+ const stats = { total: 0, active: 0, completed: 0, incomplete: 0, failed: 0, cancelled: 0, last_request_at: null, last_model: null };
62
+ async function dispatch(req, res) {
63
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers.host === undefined || !isLoopbackHostHeader(req.headers.host)
64
+ || Object.hasOwn(req.headers, "origin")) { send(res, 403, apiError("ccdx_local_only", "The Claude gateway accepts native local clients only"));return; }
65
+ if (!authenticated(req.headers, apiKey)) { send(res, 401, apiError("ccdx_gateway_auth", "Invalid local gateway credential"));return; }
66
+ let pathname;try { pathname = new URL(req.url, "http://localhost").pathname; } catch { send(res, 400, apiError("ccdx_invalid_path", "Invalid request path"));return; }
67
+ if (req.method === "GET" && pathname === "/v1/models") {
68
+ const models = provider.models("claude").map(model => ({ id: model.id, type: "model", display_name: typeof model.name === "string" && model.name || model.id }));
69
+ send(res, 200, { data: models, has_more: false, first_id: models[0]?.id || null, last_id: models.at(-1)?.id || null });return;
70
+ }
71
+ if (!["/v1/messages", "/v1/messages/count_tokens"].includes(pathname)) { send(res, 404, apiError("ccdx_not_found", "Not found"));return; }
72
+ if (req.method !== "POST") { send(res, 405, apiError("ccdx_method", "Use POST"));return; }
73
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { send(res, 415, apiError("ccdx_media_type", "Expected application/json"));return; }
74
+ const countTokens = pathname.endsWith("/count_tokens"), requestId = randomUUID();
75
+ const tracker = countTokens ? null : performance.begin("messages", { requestId });
76
+ tracker?.setProvider("m365");
77
+ const abort = createRequestAbort(req, res);
78
+ let release = () => {}, outcome = "failed", model = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
79
+ if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
80
+ await runWithRequestContext({ requestId, provider: "m365", route: "messages", streamPerformance: tracker }, async () => {
81
+ try {
82
+ release = await acquireRequest(req, { signal: abort.signal });
83
+ abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
84
+ let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
85
+ if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
86
+ send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
87
+ }
88
+ model = body.model;stats.last_model = model;streamed = !countTokens && body.stream === true;tracker?.setModel(model);
89
+ const upstream = await provider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
90
+ onUpstreamStart() { abort.setTimeout(streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs, "upstream_timeout"); } });
91
+ body = null;
92
+ tracker?.upstreamHeaders(upstream.status);
93
+ release();release = () => {};
94
+ try { onRequest({ client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude" }); } catch {}
95
+ const headers = safeUpstreamResponseHeaders(upstream.headers);
96
+ for (const [name, value] of upstream.headers) if (/^anthropic-ratelimit-[a-z0-9-]+$/.test(name)) headers[name] = value;
97
+ if (!upstream.ok || !streamed) {
98
+ const raw = await readBoundedResponseText(upstream, { maxBytes: upstream.ok ? config.maxUpstreamResponsesResponseBytes : MAX_UPSTREAM_ERROR_BODY_BYTES,
99
+ label: "Claude gateway response", signal: abort.signal });
100
+ let value;try { value = JSON.parse(raw); } catch {}
101
+ if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
102
+ model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
103
+ sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
104
+ } else if (countTokens && upstream.ok) outcome = "completed";
105
+ if (!res.destroyed && !res.writableEnded) { res.writeHead(upstream.status, headers);res.end(raw); }
106
+ } else {
107
+ if (!/^text\/event-stream(?:\s*;|$)/i.test(upstream.headers.get("content-type") || "")) throw new Error("Expected a Claude event stream");
108
+ abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
109
+ res.writeHead(upstream.status, { ...headers, "Cache-Control": "no-cache" });
110
+ const observer = createMessagesObserver(event => {
111
+ if (event.type === "error") { failedEvent = true;outcome = "failed";return; }
112
+ if (sawStop || failedEvent) return;
113
+ if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
114
+ if (event.type === "content_block_delta") tracker?.firstOutput(event.delta?.type === "input_json_delta" ? "tool_arguments" : "output_text");
115
+ if (event.type === "message_delta") { usage = { ...usage, ...event.usage };stopReason = event.delta?.stop_reason || stopReason; }
116
+ if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
117
+ }, config.maxSseBufferBytes);
118
+ const reader = upstream.body.getReader();
119
+ try {
120
+ while (true) {
121
+ const { value, done } = await reader.read();if (done) break;
122
+ tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
123
+ observer.write(value);
124
+ if (!await writeOrDrain(res, value, { signal: abort.signal })) break;
125
+ if (sawStop || failedEvent) break;
126
+ }
127
+ observer.finish();
128
+ if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
129
+ if (!res.writableEnded) res.end();
130
+ } finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
131
+ }
132
+ } catch (error) {
133
+ outcome = ["client_aborted", "client_closed"].includes(abort.reason) ? "cancelled" : "failed";
134
+ const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
135
+ log("warn", `Claude request ${requestId}: ${error.code || abort.reason || "gateway_error"}`);
136
+ if (!res.headersSent) send(res, error.statusCode || 502, apiError(error.code || "ccdx_gateway_error", message));
137
+ else if (!res.destroyed && !res.writableEnded) res.end(`event: error\ndata: ${JSON.stringify(apiError("ccdx_gateway_error", message))}\n\n`);
138
+ } finally {
139
+ release();abort.cleanup();
140
+ if (!countTokens) {
141
+ stats.active--;stats[outcome]++;
142
+ tracker?.setModel(model);tracker?.setOutputTokens(usage?.output_tokens);
143
+ tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : "upstream_response", reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
144
+ tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: res.statusCode });
145
+ const client = req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude";
146
+ try { void Promise.resolve(record(buildMessagesUsageRecord({ model, responseId, usage, mode: streamed ? "stream" : "json", client }))).catch(() => {}); } catch {}
147
+ }
148
+ }
149
+ });
150
+ }
151
+ const handler = (req, res) => dispatch(req, res).catch(() => send(res, 500, apiError("ccdx_gateway_error", "Claude gateway request failed")));
152
+ handler.snapshot = () => ({ ...stats, admission: acquireRequest.stats(), performance: performance.snapshot() });
153
+ return handler;
154
+ }
155
+
156
+ export async function startClaudeGateway(options = {}) {
157
+ const handler = createClaudeGatewayHandler(options), server = http.createServer(handler);
158
+ server.headersTimeout = 15000;server.requestTimeout = 120000;
159
+ await new Promise((resolve, reject) => { server.once("error", reject);server.listen(options.port ?? 2027, "127.0.0.1", () => { server.off("error", reject);resolve(); }); });
160
+ server.on("error", () => options.log?.("warn", "Claude gateway listener error"));
161
+ return { port: server.address().port, snapshot: handler.snapshot,
162
+ close: () => new Promise(resolve => { server.closeAllConnections();server.close(resolve); }) };
163
+ }
@@ -0,0 +1,133 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { readM365Settings, updateM365Settings } from "./m365-settings.mjs";
3
+ import { readProviderSettings } from "./provider-settings.mjs";
4
+ import { autoReviewPreference } from "./user-settings.mjs";
5
+ import { PROVIDER_MANAGEMENT_PATH } from "./provider-management.mjs";
6
+ import { adapterBaseUrl } from "./running-adapter.mjs";
7
+ import { isLoopbackHost } from "./security.mjs";
8
+ import { terminalCell } from "./terminal-text.mjs";
9
+ import { readBoundedResponseText } from "./upstream-body.mjs";
10
+ import { parseAdapterAddressOptions } from "./cli-options.mjs";
11
+ import { autoReviewReasoningEfforts } from "./models.mjs";
12
+
13
+ export async function fetchActiveProviderModels({ control = providerControl, ...options } = {}) {
14
+ if (readProviderSettings(options).codex !== "m365") {
15
+ const { fetchLiveCopilotModels } = await import("./live-models.mjs");
16
+ return fetchLiveCopilotModels(options);
17
+ }
18
+ const address = parseAdapterAddressOptions(options.env || process.env);
19
+ const result = await control({ host: address.adapterHost, port: address.adapterPort, ...options, action: { action: "models", family: "gpt" } });
20
+ return { source: "catalog", upstreamHost: "Microsoft 365", advertised: result.models.length,
21
+ models: result.models.map(model => ({ id: model.id, vendor: model.publisher, endpoints: ["responses"], preview: false })) };
22
+ }
23
+
24
+ export async function providerControl({ host = "127.0.0.1", port = 2026, action, fetchImpl = fetch, timeoutMs = 35000 } = {}) {
25
+ const url = `${adapterBaseUrl(isLoopbackHost(host) ? host : "127.0.0.1", port)}${PROVIDER_MANAGEMENT_PATH}`;
26
+ const response = await fetchImpl(url, { method: action ? "POST" : "GET", headers: { Accept: "application/json", ...(action ? { "Content-Type": "application/json" } : {}) },
27
+ ...(action ? { body: JSON.stringify(action) } : {}), redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
28
+ const value = JSON.parse(await readBoundedResponseText(response, { maxBytes: 4 * 1024 * 1024, label: "Provider status" }));
29
+ if (!response.ok) throw Object.assign(new Error(value.error?.message || "Provider management is unavailable; restart the updated CCDX service"), { code: value.error?.code || "ccdx_provider_management_unavailable" });
30
+ return value;
31
+ }
32
+
33
+ export function formatM365Status(state) {
34
+ const m = state.m365 || {}, claude = m.claude || {}, models = m.models || {};
35
+ return [
36
+ `Microsoft 365: ${terminalCell(m.state || "not running")}${m.reason ? ` (${terminalCell(m.reason)})` : ""}`,
37
+ ...(m.account?.login ? [`Account: ${terminalCell(m.account.login)}`] : []),
38
+ `Models: ${models.claude || 0} Claude / ${models.gpt || 0} GPT (${models.source || "unavailable"})`,
39
+ `Claude gateway: ${claude.gateway || "not running"}${claude.port ? ` / http://127.0.0.1:${claude.port}` : ""}`,
40
+ ...(claude.reason ? [`Claude detail: ${terminalCell(claude.reason)}`] : []),
41
+ ...(claude.requests ? [`Claude requests: ${claude.requests.completed} completed / ${claude.requests.incomplete} incomplete / ${claude.requests.failed} failed / ${claude.requests.active} active`] : []),
42
+ `Claude Code: ${claude.clients?.code || "unknown"}; Claude App: ${claude.clients?.app || "unknown"}`,
43
+ `Codex provider: ${state.codex_provider || "github"} (default: github)`,
44
+ ].join("\n");
45
+ }
46
+
47
+ export async function runProviderAutoReviewCommand(options = {}) {
48
+ const { runAutoReviewModelCommand } = await import("./auto-review-model.mjs");
49
+ const settings = readProviderSettings(options);
50
+ if (settings.codex !== "m365") return runAutoReviewModelCommand(options);
51
+ const state = await providerControl(options);
52
+ if (state.codex_provider !== "m365") throw new Error("The running provider does not match the saved selection; restart ccdx before changing Auto-review");
53
+ const preference = state.m365?.preference || settings.m365;
54
+ return runAutoReviewModelCommand({ ...options, env: { ...(options.env || process.env), CCDX_AUTO_REVIEW_MODEL: "" },
55
+ loadCatalog: async () => {
56
+ const result = await providerControl({ ...options, action: { action: "models", family: "gpt" } });
57
+ return { modelIds: result.models.map(model => model.id), source: "Microsoft 365",
58
+ reasoningEfforts: Object.fromEntries(result.models.map(model => [model.id, autoReviewReasoningEfforts(model)])) };
59
+ },
60
+ getPreference: () => ({ model: preference.auto_review_model, source: "m365", reasoningEffort: preference.auto_review_effort === undefined ? "low" : preference.auto_review_effort }),
61
+ savePreference: (model, { reasoningEffort }) => providerControl({ ...options, action: { action: "auto-review", model, effort: reasoningEffort } }),
62
+ });
63
+ }
64
+
65
+ export async function runM365Command({ action = "status", provider, model, autoReviewModel, host, port, home,
66
+ env = process.env, input = process.stdin, output = process.stdout, prompt, control = providerControl } = {}) {
67
+ const options = { home, env };
68
+ let readline;
69
+ const ask = prompt || (question => { if (!input.isTTY || !output.isTTY) throw new Error("Use explicit provider/model arguments outside an interactive terminal");
70
+ readline ||= createInterface({ input, output });return readline.question(question); });
71
+ const request = value => control({ host, port, action: value });
72
+ try {
73
+ if (action === "status") {
74
+ try { const state = await request();output.write(formatM365Status(state) + "\n");return state; }
75
+ catch (error) {
76
+ const saved = readM365Settings(options), selected = readProviderSettings(options);
77
+ output.write(`Microsoft 365 preference: ${saved.enabled ? "auto" : "off"}\nCodex provider: ${selected.codex}\nRuntime status unavailable; start or restart ccdx to inspect it.\n`);
78
+ return { saved: true, runtime: "unavailable" };
79
+ }
80
+ }
81
+ if (action === "switch") {
82
+ if (!provider) {
83
+ output.write("Codex provider:\n 1. GitHub Copilot (default)\n 2. Microsoft 365 (backup)\n");
84
+ const answer = String(await ask("Select 1 or 2, or q to cancel: ")).trim();
85
+ if (answer === "q") return { cancelled: true };
86
+ if (!["1", "2"].includes(answer)) throw new Error("Select 1 or 2");provider = answer === "1" ? "github" : "m365";
87
+ }
88
+ if (provider === "m365") {
89
+ const available = await request({ action: "models", family: "gpt" });
90
+ const models = available.models || [], ids = models.map(entry => entry.id);
91
+ if (!ids.length) throw new Error("No M365 GPT models are available; the current provider was retained");
92
+ const saved = readProviderSettings(options).m365;
93
+ const choose = async (label, supplied, preferred) => {
94
+ if (supplied) { if (!ids.includes(supplied)) throw new Error(`${label} model is not available: ${terminalCell(supplied)}`);return supplied; }
95
+ const current = ids.includes(preferred) ? preferred : null;
96
+ if (!prompt && (!input.isTTY || !output.isTTY)) {
97
+ if (current) return current;
98
+ throw new Error(`Specify --${label === "Auto-review" ? "auto-review-model" : "model"} with an available M365 model: ${ids.join(", ")}`);
99
+ }
100
+ output.write(`${label} model:\n${ids.map((id, index) => ` ${index + 1}. ${id}${id === current ? " [current]" : ""}`).join("\n")}\n`);
101
+ const answer = String(await ask(`Select a model${current ? ` [${ids.indexOf(current) + 1}]` : ""}, or q to cancel: `)).trim();
102
+ if (answer === "q") return null;
103
+ const index = answer === "" && current ? ids.indexOf(current) : Number(answer) - 1;
104
+ if (!Number.isInteger(index) || !ids[index]) throw new Error("Invalid model selection");return ids[index];
105
+ };
106
+ model = await choose("Codex", model, saved?.model);if (!model) return { cancelled: true };
107
+ autoReviewModel = await choose("Auto-review", autoReviewModel, saved?.auto_review_model || autoReviewPreference(options).model);
108
+ if (!autoReviewModel) return { cancelled: true };
109
+ output.write("M365 fast tier is not verified. Use Standard in Codex; existing threads keep their selected model until you change it.\n");
110
+ }
111
+ const state = await request({ action: "switch", provider, model, auto_review_model: autoReviewModel });
112
+ output.write(formatM365Status(state) + "\n");
113
+ if (provider === "m365") output.write(`Select ${model} in Codex. Auto-review uses ${autoReviewModel} / low on this provider.\n`);
114
+ return state;
115
+ }
116
+ if (action === "models") {
117
+ const value = await request({ action: "models", family: "claude" });
118
+ output.write((value.models || []).map(model => terminalCell(model.id)).join("\n") + "\n");return value;
119
+ }
120
+ if (["on", "off", "remove"].includes(action)) {
121
+ try { const state = await request({ action });output.write(formatM365Status(state) + "\n");return state; }
122
+ catch (error) {
123
+ if (error.cause?.code !== "ECONNREFUSED") throw error;
124
+ if (action === "on") { updateM365Settings({ enabled: true }, options);output.write("M365 auto-discovery enabled. Run ccdx to start it.\n");return; }
125
+ const { createProviderRuntime } = await import("./provider-runtime.mjs");
126
+ const runtime = createProviderRuntime({ ...options });
127
+ try { const state = await runtime.action({ action });output.write(formatM365Status(state) + "\n");return state; }
128
+ finally { await runtime.close(); }
129
+ }
130
+ }
131
+ throw new Error("Unknown M365 action");
132
+ } finally { readline?.close(); }
133
+ }
@@ -21,7 +21,7 @@ function liveCatalogHeader(catalog, { commandName, models }) {
21
21
  const chat = models.filter((model) => model.endpoints.includes("chat")).length;
22
22
  return [
23
23
  `${commandName} models`,
24
- status("ok", `Live catalog from ${safeText(catalog?.upstreamHost, "GitHub Copilot")}: ${models.length} selectable GPT models of ${Number(catalog?.advertised) || 0} advertised`),
24
+ status("ok", `${catalog?.source === "catalog" ? "Available catalog" : "Live catalog"} from ${safeText(catalog?.upstreamHost, "GitHub Copilot")}: ${models.length} selectable GPT models of ${Number(catalog?.advertised) || 0} advertised`),
25
25
  status("info", `Responses: ${responses}; Chat: ${chat}`),
26
26
  ];
27
27
  }
@@ -29,6 +29,7 @@ const HELP_TOPICS = new Set([
29
29
  "auto-review-model",
30
30
  "suggestion",
31
31
  "prediction",
32
+ "m365",
32
33
  "update",
33
34
  "version",
34
35
  ]);
@@ -151,13 +152,23 @@ export function parseCliArgs(args = []) {
151
152
  return baseCommand("version");
152
153
  }
153
154
  if (command === "start") return parseStartOptions(rest);
155
+ if (command === "m365") {
156
+ const [action = "status", ...args] = rest;
157
+ if (!["status", "models", "switch", "on", "off", "remove"].includes(action)) throw new Error("M365 action must be status, models, switch, on, off or remove");
158
+ let provider, remaining = args;
159
+ if (action === "switch" && args[0] && !args[0].startsWith("--")) { provider = args[0];remaining = args.slice(1); }
160
+ if (provider && !["github", "m365"].includes(provider)) throw new Error("Provider must be github or m365");
161
+ const values = parseOptions(remaining, new Map(action === "switch" ? [["--model", "value"], ["--auto-review-model", "value"]] : []));
162
+ return baseCommand("m365", { action, provider, model: values["--model"], autoReviewModel: values["--auto-review-model"] });
163
+ }
154
164
  if (command === "status" || command === "--status") {
155
165
  if (rest.length) unexpectedArgs(rest);
156
166
  return baseCommand("status");
157
167
  }
158
168
  if (command === "usage") {
159
- const options = parseOptions(rest, new Map([["--format", "value"]]));
160
- return baseCommand("usage", outputFormatOption(options["--format"]));
169
+ const options = parseOptions(rest, new Map([["--format", "value"], ["--provider", "value"]]));
170
+ if (options["--provider"] && !["github", "m365"].includes(options["--provider"])) throw new Error("Usage provider must be github or m365");
171
+ return baseCommand("usage", { ...outputFormatOption(options["--format"]), ...(options["--provider"] ? { provider: options["--provider"] } : {}) });
161
172
  }
162
173
  if (command === "cache") {
163
174
  let cacheArgs = rest;
@@ -370,8 +381,8 @@ function topicHelp(name, topic) {
370
381
  doctor: `Usage:\n ${name} doctor [--online] [--compat] [--fix] [--json]\n ${name} doctor config\n\nChecks credentials, managed configuration, command launchers, adapter, enabled optional features and observed client catalog. Default is read-only; no inference requests. --online validates account entitlement; --compat sends minimal inference requests and consumes a small amount of Copilot usage, requiring successful model completion rather than HTTP 200 alone. --fix repairs owned Windows launchers and managed config, imports a verified existing credential only if none is saved, and asks the running adapter to repair enabled predictions once. No interactive login, client program edits, forced App restarts, policy changes or optional feature activation. Missing-credential repair can contact GitHub without --online. Changed existing config is backed up to config.toml.ccdx-doctor.bak. Partial repairs exit 1. --json emits a redacted report, including before_checks for repairs. App-internal cache and visible predictions are not externally verified. The config subcommand remains strictly read-only.`,
371
382
  "doctor config": `Usage:\n ${name} doctor config\n\nReads ~/.codex/config.toml, checks TOML syntax and CCDX-managed settings, and previews the existing startup writer's changes. Does not merge Codex profiles or validate the complete installed Codex schema. No authentication, network requests, file writes, or adapter/GUI startup. Existing context_management=false is valid. Exit 1 for errors, 0 for OK/warnings; unsupported arguments exit 2.`,
372
383
  status: `Usage:\n ${name} status\n\nShows bounded runtime, routing, performance, queue, and cache metrics from a running adapter.`,
373
- models: `Usage:\n ${name} models [--format table|plain]\n\nPerforms a fresh, read-only Copilot model-directory lookup for the saved account. Interactive terminals use a table by default.`,
374
- usage: `Usage:\n ${name} usage [--format table|plain]\n\nSummarizes local token usage metadata without reading prompt or completion content. Interactive terminals use a table by default.`,
384
+ models: `Usage:\n ${name} models [--format table|plain]\n\nShows GPT models for the selected Codex provider. GitHub performs a fresh read-only lookup; M365 uses its isolated catalog in the running service. Interactive terminals use a table by default.`,
385
+ usage: `Usage:\n ${name} usage [--format table|plain] [--provider github|m365]\n\nSummarizes local token usage metadata without reading prompt or completion content. Optional provider filtering separates sources; default totals include both. Interactive terminals use a table by default.`,
375
386
  cache: `Usage:\n ${name} cache\n ${name} cache --limit <MiB|default>\n ${name} cache --clean [--history] [--yes]\n\nShows runtime cache use, saves and applies the shared response-history limit, or clears the rebuildable image-transform cache. --history also clears in-memory response history for all tasks and can make their next continuation fail, so interactive confirmation or --yes is required. Generated image files and saved Codex transcripts are never deleted. Short aliases: -128 sets 128 MiB and -clean equals --clean.`,
376
387
  limits: `Usage:\n ${name} limits\n ${name} limits --decoded <MiB|default>\n\nShows configured and running request-body limits, or saves a decoded request-body limit from 128 to 512 MiB. The raw-body limit is unchanged. Restart ccdx to apply a saved change; no conversation or cache is cleared. Short alias: -256 sets 256 MiB.`,
377
388
  animation: `Usage:\n ${name} animation\n\nPreviews all terminal activity animations together and selects the theme used the next time the adapter starts.`,
@@ -380,6 +391,7 @@ function topicHelp(name, topic) {
380
391
  "image-status": `Usage:\n ${name} image-status\n\nShows provider configuration and locally advertised generation/editing tools without generating an image or exposing its API key.`,
381
392
  "auto-review-model": `Usage:\n ${name} auto-review-model\n\nSelect a Responses model, then an advertised reasoning effort. Enter keeps the default/current choice; q cancels both steps without saving. Effort 0 follows the client (low when omitted). Settings apply only to Auto-review on the next request; no client patch or restart is required for adapters running 0.9.13 or newer.`,
382
393
  "suggestion": `The CCDX prediction panel has been retired. Run ${name} suggestion off to safely remove unchanged CCDX registrations. This cleanup does not change native predictions; see ${name} prediction --help for that separate opt-in feature.`,
394
+ m365: `Usage:\n ${name} m365 [status|models|on|off|remove]\n ${name} m365 switch [github|m365] [--model ID] [--auto-review-model ID]\n\nM365 is discovered silently at startup on supported managed environments. Claude uses its separate local gateway. Codex stays on GitHub unless you explicitly switch. M365 switching requires a running compatible adapter and available GPT/Auto-review choices; it never substitutes unavailable models. Select an available model in Codex after switching an existing thread. Off restores only owned Claude settings and selects GitHub. Remove also clears the CCDX M365 profile, retaining a disabled preference and historical usage. System Microsoft sign-in, GitHub credentials, predictions and images are preserved.`,
383
395
  prediction: `Usage:\n ${name} prediction [status|on|off|fix]\n\nOptional native next-message predictions; off by default. macOS and Windows. Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup. Quit Codex before on/off, then restart ccdx. On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com. HTTPS on those hosts is decrypted locally; only prediction configuration is changed. No client program files, OS trust, account permissions, MCP or Hooks are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved. Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD remains unsupported. Static IPv4/IPv6 CIDRs match URL IP literals without DNS. The bridge port persists across restarts/updates; a busy saved port disables only predictions. Launch/reuse checks the App's actual route; an older random or missing route may require one full App quit. Official prediction configuration is preserved; the conversation's model is used. App updates require another compatibility check. Status distinguishes saved preference and observed config traffic from unverified candidate visibility.\n\nFix asks a compatible running CCDX adapter to repair the enabled bridge once on its saved port. It never enables predictions, renews certificates or force-restarts Codex. Healthy unchanged bridges are retained. Fix rechecks system proxy settings. Changed routes may need a normal App relaunch to reload cached PAC; failed rechecks preserve the previous bridge with a nonzero exit. Process environment variables and Node trust are not hot-reloaded; changed trust inputs need a CCDX service restart. Startup, status and doctor share sanitized environment diagnostics. Missing App routes require a normal full quit and ccdx launch; partial repair exits 1. An older adapter must first be upgraded and restarted once to gain this repair endpoint.`,
384
396
  update: `Usage:\n ${name} update [npm|github] [--allow-remote]\n\nUpdates the global package from the configured npm registry or the latest stable GitHub release. With no source, an interactive terminal prompts for one. Windows uses system cmd.exe to run npm.cmd without changing PowerShell policy; use the .cmd entrypoint if scripts are blocked. GitHub installs require Git on PATH and dependencies may still use the configured npm registry. By default npm's remote-download policy is preserved. If npm reports EALLOWREMOTE for a trusted mirror tarball, --allow-remote explicitly permits URL dependencies for this one installation's entire dependency tree; it is not a hostname allowlist. No .npmrc, registry or persistent policy is changed, and failed installations are not retried automatically. Use this only if company policy permits it. Restart the running adapter after installation.`,
385
397
  version: `Usage:\n ${name} --version`,
@@ -398,7 +410,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
398
410
  ${name} doctor config
399
411
  ${name} status
400
412
  ${name} models [--format table|plain]
401
- ${name} usage [--format table|plain]
413
+ ${name} usage [--format table|plain] [--provider github|m365]
402
414
  ${name} cache [--limit <MiB|default> | --clean [--history] [--yes]]
403
415
  ${name} limits [--decoded <MiB|default>]
404
416
  ${name} animation
@@ -407,6 +419,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
407
419
  ${name} image-status
408
420
  ${name} auto-review-model
409
421
  ${name} prediction [status|on|off|fix]
422
+ ${name} m365 [status|models|switch|on|off|remove]
410
423
  ${name} update [npm|github] [--allow-remote]
411
424
  ${name} --version
412
425
  ${name} --help
@@ -416,7 +429,7 @@ Commands:
416
429
  auth Inspect the saved GitHub Copilot account
417
430
  doctor Diagnose local config; optional live and inference checks
418
431
  status Show runtime routing, performance, queue, and cache health
419
- models Query a saved account's live Copilot model catalog
432
+ models Show the selected Codex provider's GPT model catalog
420
433
  usage Summarize locally recorded token usage
421
434
  cache Inspect, size, or clear bounded runtime caches
422
435
  limits Inspect or configure the decoded request-body limit
@@ -426,6 +439,7 @@ Commands:
426
439
  image-status Show the optional image provider status
427
440
  auto-review-model Select the Codex Auto-review model and reasoning effort
428
441
  prediction Toggle optional native next-message predictions
442
+ m365 Manage M365 Claude access and the optional Codex backup
429
443
  update Update the global package from npm or GitHub
430
444
 
431
445
  Run ${name} <command> --help for command details.`;