codex-copilot-dx 1.2.12 → 1.2.14

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 (43) hide show
  1. package/README.md +14 -14
  2. package/bin/cli.mjs +12 -8
  3. package/docs/ARCHITECTURE.md +54 -5
  4. package/docs/REFERENCE.md +91 -1
  5. package/package.json +2 -2
  6. package/src/access-settings.mjs +98 -0
  7. package/src/adapter.mjs +19 -7
  8. package/src/api-secrets.mjs +69 -0
  9. package/src/auto-review-model.mjs +4 -3
  10. package/src/claude-client-config.mjs +16 -11
  11. package/src/claude-gateway.mjs +11 -8
  12. package/src/cli-m365.mjs +48 -8
  13. package/src/cli-models.mjs +2 -1
  14. package/src/cli-options.mjs +1 -1
  15. package/src/cli-status.mjs +1 -1
  16. package/src/client-gateway-keys.mjs +29 -0
  17. package/src/codex-api-config.mjs +51 -0
  18. package/src/connection-runtime.mjs +289 -0
  19. package/src/conversation-source-guard.mjs +42 -0
  20. package/src/dashboard/connections.js +182 -0
  21. package/src/dashboard/console.js +6 -4
  22. package/src/dashboard/flow.js +4 -4
  23. package/src/dashboard/index.html +43 -0
  24. package/src/dashboard/language.js +85 -2
  25. package/src/dashboard/status.js +1 -1
  26. package/src/dashboard/ui.css +24 -0
  27. package/src/dashboard/ui.js +4 -2
  28. package/src/dashboard-api.mjs +19 -4
  29. package/src/dashboard.mjs +1 -0
  30. package/src/optional-routes.mjs +2 -2
  31. package/src/private-helper-environment.mjs +7 -0
  32. package/src/provider-management.mjs +1 -1
  33. package/src/provider-runtime.mjs +37 -5
  34. package/src/providers/api-network.mjs +51 -0
  35. package/src/providers/api.mjs +129 -0
  36. package/src/proxy-tunnel.mjs +6 -4
  37. package/src/responses-handler.mjs +6 -4
  38. package/src/startup-ui.mjs +9 -0
  39. package/src/stream-performance.mjs +7 -6
  40. package/src/terminal-console.mjs +1 -1
  41. package/src/usage-store.mjs +1 -1
  42. package/src/windows-http-network.mjs +11 -6
  43. package/src/windows-prediction-network.cs +6 -4
@@ -0,0 +1,69 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { accessSettingsPath, accessError } from "./access-settings.mjs";
5
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
6
+ import { readBoundedFileSync } from "./bounded-file.mjs";
7
+ import { windowsPowerShellEnvironment } from "./windows-process.mjs";
8
+ import { privateHelperEnvironment } from "./private-helper-environment.mjs";
9
+
10
+ const SERVICE = "codex-copilot-dx.manual-api";
11
+ export function secretProcess(command, args, input = "", env = process.env) {
12
+ return new Promise((resolve, reject) => {
13
+ const privateEnv = privateHelperEnvironment(env);
14
+ const child = spawn(command, args, { env: process.platform === "win32" ? windowsPowerShellEnvironment(privateEnv) : privateEnv,
15
+ shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
16
+ let output = "", settled = false;
17
+ const finish = (error, value) => { if (settled) return;settled = true;clearTimeout(timer);error ? reject(accessError("ccdx_api_secret_unavailable", 503)) : resolve(value); };
18
+ const timer = setTimeout(() => { child.kill();finish(true); }, 10000);
19
+ child.on("error", () => finish(true));child.stderr.resume();child.stdin.on("error", () => {});
20
+ child.stdout.setEncoding("utf8");child.stdout.on("data", chunk => { output += chunk;if (output.length > 65536) { child.kill();finish(true); } });
21
+ child.on("close", code => finish(code !== 0, output.trim()));child.stdin.end(input);
22
+ });
23
+ }
24
+ export function checkedApiKey(key) {
25
+ if (typeof key !== "string" || !/^[\x21-\x7e]{8,4096}$/.test(key)) throw accessError("ccdx_api_key_invalid");return key;
26
+ }
27
+ export function createApiSecretStore({ platform = process.platform, env = process.env, run = secretProcess, ...options } = {}) {
28
+ const cache = new Map(), folder = path.join(path.dirname(accessSettingsPath({ ...options, env })), "api-secrets");
29
+ const ref = id => { if (!/^[a-f0-9]{32}$/.test(id)) throw accessError("ccdx_api_key_invalid");return id; };
30
+ const powershell = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
31
+ const ps = async (script, input) => run(powershell, ["-NoProfile", "-NonInteractive", "-Command",
32
+ "$ErrorActionPreference='Stop';" + script], input + "\n", windowsPowerShellEnvironment(env));
33
+ return {
34
+ async get(id) {
35
+ ref(id);if (cache.has(id)) return cache.get(id);
36
+ let key;
37
+ if (platform === "darwin") key = await run("/usr/bin/security", ["find-generic-password", "-s", SERVICE, "-a", id, "-w"], "", env);
38
+ else if (platform === "win32") {
39
+ let encrypted;try { encrypted = readBoundedFileSync(path.join(folder, id), { encoding: "utf8", maxBytes: 65536 }); } catch { throw accessError("ccdx_api_secret_unavailable", 503); }
40
+ if (!/^[A-Za-z0-9+/]{64,65536}={0,2}$/.test(encrypted) || encrypted.length % 4) throw accessError("ccdx_api_secret_unavailable", 503);
41
+ key = await ps("$null=[Reflection.Assembly]::LoadWithPartialName('System.Security');$b=[Convert]::FromBase64String([Console]::In.ReadLine());$p=[Security.Cryptography.ProtectedData]::Unprotect($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Write([Text.Encoding]::UTF8.GetString($p))", encrypted);
42
+ } else key = await run("/usr/bin/secret-tool", ["lookup", "service", SERVICE, "reference", id], "", env);
43
+ checkedApiKey(key);cache.set(id, key);return key;
44
+ },
45
+ async set(id, key) {
46
+ ref(id);checkedApiKey(key);
47
+ if (platform === "darwin") {
48
+ const quote = value => '"' + value.replace(/[\\"]/g, "\\$&") + '"';
49
+ await run("/usr/bin/security", ["-i"], `add-generic-password -a ${quote(id)} -s ${quote(SERVICE)} -w ${quote(key)}\n`, env);
50
+ // Interactive security commands can exit zero after an individual failure.
51
+ const saved = await run("/usr/bin/security", ["find-generic-password", "-s", SERVICE, "-a", id, "-w"], "", env);
52
+ if (saved !== key) throw accessError("ccdx_api_secret_unavailable", 503);
53
+ } else if (platform === "win32") {
54
+ // Use inbox .NET directly: cmdlet auto-discovery can stall in a private child environment.
55
+ const encrypted = await ps("$null=[Reflection.Assembly]::LoadWithPartialName('System.Security');$b=[Text.Encoding]::UTF8.GetBytes([Console]::In.ReadLine());$c=[Security.Cryptography.ProtectedData]::Protect($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Write([Convert]::ToBase64String($c))", key);
56
+ if (!/^[A-Za-z0-9+/]{64,65536}={0,2}$/.test(encrypted) || encrypted.length % 4) throw accessError("ccdx_api_secret_unavailable", 503);
57
+ fs.mkdirSync(folder, { recursive: true, mode: 0o700 });atomicWriteFileSync(path.join(folder, id), encrypted, { mode: 0o600 });
58
+ } else await run("/usr/bin/secret-tool", ["store", "--label=CCDX API", "service", SERVICE, "reference", id], key, env);
59
+ cache.set(id, key);
60
+ },
61
+ async remove(id) {
62
+ ref(id);cache.delete(id);
63
+ if (platform === "darwin") await run("/usr/bin/security", ["delete-generic-password", "-s", SERVICE, "-a", id], "", env);
64
+ else if (platform === "win32") fs.rmSync(path.join(folder, id), { force: true });
65
+ else await run("/usr/bin/secret-tool", ["clear", "service", SERVICE, "reference", id], "", env);
66
+ },
67
+ close() { cache.clear(); },
68
+ };
69
+ }
@@ -90,6 +90,7 @@ export async function runAutoReviewModelCommand({
90
90
  prompt,
91
91
  getPreference = autoReviewPreference,
92
92
  savePreference = (model, options) => writeAutoReviewModel(model === DEFAULT_CODEX_AUTO_REVIEW_MODEL ? "" : model, options),
93
+ followClientLabel = "follow client (low when omitted)",
93
94
  } = {}) {
94
95
  if (!prompt && (!input.isTTY || !output.isTTY)) {
95
96
  throw new Error(`${commandName} auto-review-model requires an interactive terminal`);
@@ -103,7 +104,7 @@ export async function runAutoReviewModelCommand({
103
104
 
104
105
  output.write(`${commandName} auto-review-model\n`);
105
106
  output.write(`Current: ${current.model} (${current.source})\n`);
106
- output.write(`Reasoning: ${current.reasoningEffort || "follow client (low when omitted)"}\n`);
107
+ output.write(`Reasoning: ${current.reasoningEffort || followClientLabel}\n`);
107
108
  output.write(`Responses models from ${catalog.source}:\n`);
108
109
  modelIds.forEach((model, index) => {
109
110
  const markers = [];
@@ -144,7 +145,7 @@ export async function runAutoReviewModelCommand({
144
145
  const effortIndex = selectedModel === current.model && current.reasoningEffort === null
145
146
  ? 0 : currentEffort ? efforts.indexOf(currentEffort) + 1 : efforts.indexOf("low") + 1;
146
147
  output.write(`Reasoning for ${selectedModel}:\n`);
147
- output.write(" 0. Follow client (low when omitted)\n");
148
+ output.write(` 0. ${followClientLabel[0].toUpperCase() + followClientLabel.slice(1)}\n`);
148
149
  efforts.forEach((effort, index) => {
149
150
  const markers = [];
150
151
  if (effort === currentEffort) markers.push("current");
@@ -171,7 +172,7 @@ export async function runAutoReviewModelCommand({
171
172
 
172
173
  const result = await savePreference(selectedModel, { env, home, reasoningEffort: selectedEffort });
173
174
  output.write(`${result.changed ? "Saved" : "Kept"} Auto Review model: ${selectedModel}\n`);
174
- output.write(`Reasoning: ${selectedEffort || "follow client (low when omitted)"}\n`);
175
+ output.write(`Reasoning: ${selectedEffort || followClientLabel}\n`);
175
176
  if (String(env.CCDX_AUTO_REVIEW_MODEL || "").trim()) {
176
177
  output.write(`CCDX_AUTO_REVIEW_MODEL=${current.model} remains the effective override until it is unset. Reasoning is bound to ${selectedModel}.\n`);
177
178
  } else {
@@ -104,7 +104,9 @@ function reconcile(operations, { restore = false, ...options } = {}) {
104
104
  throw new Error("Claude configuration ownership is invalid; files were preserved");
105
105
  }
106
106
  const states = new Map(), pending = [], nextJournal = structuredClone(journal), skipped = [];
107
- const list = restore ? journal.operations : operations;
107
+ const forClient = op => (!options.client || (options.client === "claude_code" ? op.file === paths.code : op.file !== paths.code))
108
+ && (!options.fields || options.fields.includes(op.keys.join(".")));
109
+ const list = restore ? journal.operations.filter(forClient) : operations;
108
110
  for (const operation of list) {
109
111
  if (!allowed.has(operation.file)) throw new Error("Unexpected Claude configuration path");
110
112
  if (!states.has(operation.file)) states.set(operation.file, read(operation.file));
@@ -148,11 +150,11 @@ function reconcile(operations, { restore = false, ...options } = {}) {
148
150
  }
149
151
  writeM365Json(journalPath, oldJournal);throw error;
150
152
  }
151
- return { changed: pending.length > 0, preserved: [...new Set(skipped)].length, remaining: nextJournal.operations.length };
153
+ return { changed: pending.length > 0, preserved: [...new Set(skipped)].length, remaining: nextJournal.operations.filter(forClient).length };
152
154
  });
153
155
  }
154
156
 
155
- export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, ...options } = {}) {
157
+ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, ...options } = {}) {
156
158
  const entries = claudeModelEntries(models);
157
159
  const paths = claudeClientPaths(options), ids = entries.map(model => model.name), operations = [], result = {};
158
160
  const endpoint = new URL(baseUrl);
@@ -167,29 +169,32 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
167
169
  const codeEnv = code?.env || {};
168
170
  const envConflict = env.ANTHROPIC_BASE_URL && env.ANTHROPIC_BASE_URL !== baseUrl
169
171
  || env.ANTHROPIC_AUTH_TOKEN && env.ANTHROPIC_AUTH_TOKEN !== apiKey
170
- || codeEnv.ANTHROPIC_AUTH_TOKEN && codeEnv.ANTHROPIC_AUTH_TOKEN !== apiKey
172
+ || codeEnv.ANTHROPIC_AUTH_TOKEN && codeEnv.ANTHROPIC_AUTH_TOKEN !== apiKey && !owns(paths.code, ["env", "ANTHROPIC_AUTH_TOKEN"], codeEnv.ANTHROPIC_AUTH_TOKEN)
171
173
  || env.ANTHROPIC_API_KEY && env.ANTHROPIC_API_KEY !== apiKey
172
174
  || codeEnv.ANTHROPIC_API_KEY && codeEnv.ANTHROPIC_API_KEY !== apiKey
173
175
  || code?.apiKeyHelper
174
176
  || ["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] || ""));
175
- if (!code) { /* Keep independent App setup available when Code settings are damaged. */ }
177
+ if (options.client === "claude_app") { /* The other client's configuration has a separate lifecycle. */ }
178
+ else if (!code) { /* Keep independent App setup available when Code settings are damaged. */ }
176
179
  else if (envConflict || codeEnv.ANTHROPIC_BASE_URL && codeEnv.ANTHROPIC_BASE_URL !== baseUrl
177
180
  && !owns(paths.code, ["env", "ANTHROPIC_BASE_URL"], codeEnv.ANTHROPIC_BASE_URL)) result.code = "preserved";
178
181
  else {
179
182
  add(paths.code, ["env", "ANTHROPIC_BASE_URL"], baseUrl);
180
183
  add(paths.code, ["env", "ANTHROPIC_AUTH_TOKEN"], apiKey);
181
184
  add(paths.code, ["env", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"], "1");
182
- if (env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS === undefined) add(paths.code, ["env", "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"], "1");
185
+ if (disableExperimentalBetas && env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS === undefined) add(paths.code, ["env", "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"], "1");
183
186
  add(paths.code, ["env", "ANTHROPIC_CUSTOM_HEADERS"], "X-CCDX-Client: claude-code");
184
- if (ids.length && (!codeEnv.ANTHROPIC_MODEL || models.some(model => model.id === codeEnv.ANTHROPIC_MODEL))) {
185
- const index = models.findIndex(model => model.id === codeEnv.ANTHROPIC_MODEL);
187
+ if (ids.length && (!codeEnv.ANTHROPIC_MODEL || models.some(model => model.id === codeEnv.ANTHROPIC_MODEL)
188
+ || owns(paths.code, ["env", "ANTHROPIC_MODEL"], codeEnv.ANTHROPIC_MODEL))) {
189
+ const index = models.findIndex(model => model.id === codeEnv.ANTHROPIC_MODEL || claudeClientModelId(model.id) === codeEnv.ANTHROPIC_MODEL);
186
190
  add(paths.code, ["env", "ANTHROPIC_MODEL"], ids[Math.max(0, index)]);
187
191
  }
188
192
  result.code = "configured";
189
193
  }
190
194
  const installed = desktopInstalled ?? (fs.existsSync(path.dirname(paths.normal)) || fs.existsSync(path.dirname(paths.threep))
191
195
  || (options.platform || process.platform) === "darwin" && fs.existsSync("/Applications/Claude.app"));
192
- if (!installed) result.app = "not_installed";
196
+ if (options.client === "claude_code") { /* The other client's configuration has a separate lifecycle. */ }
197
+ else if (!installed) result.app = "not_installed";
193
198
  else if (desktopManaged !== false || env.CLAUDE_USER_DATA_DIR) result.app = "preserved";
194
199
  else {
195
200
  let meta, profile;
@@ -199,7 +204,7 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
199
204
  || profile.inferenceProvider && profile.inferenceProvider !== "gateway"
200
205
  || profile.inferenceGatewayBaseUrl && profile.inferenceGatewayBaseUrl !== baseUrl
201
206
  && !owns(paths.profile, ["inferenceGatewayBaseUrl"], profile.inferenceGatewayBaseUrl)
202
- || profile.inferenceGatewayApiKey && profile.inferenceGatewayApiKey !== apiKey) result.app = "preserved";
207
+ || profile.inferenceGatewayApiKey && profile.inferenceGatewayApiKey !== apiKey && !owns(paths.profile, ["inferenceGatewayApiKey"], profile.inferenceGatewayApiKey)) result.app = "preserved";
203
208
  else {
204
209
  add(paths.profile, ["inferenceProvider"], "gateway");
205
210
  add(paths.profile, ["inferenceGatewayBaseUrl"], baseUrl);
@@ -214,7 +219,7 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
214
219
  const orderedEntries = [...entries].sort((left, right) => (order.get(left.name) ?? Infinity) - (order.get(right.name) ?? Infinity));
215
220
  add(paths.profile, ["inferenceModels"], JSON.stringify(orderedEntries));
216
221
  add(paths.profile, ["inferenceCustomHeaders"], JSON.stringify({ "X-CCDX-Client": "claude-app" }));
217
- add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: M365_CLAUDE_PROFILE_NAME }, M365_CLAUDE_PROFILE_ID);
222
+ add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: profileName }, M365_CLAUDE_PROFILE_ID);
218
223
  add(paths.meta, ["appliedId"], M365_CLAUDE_PROFILE_ID);
219
224
  add(paths.threep, ["deploymentMode"], "3p");
220
225
  result.app = "configured";
@@ -1,5 +1,5 @@
1
1
  import { isProviderId } from "./provider-metadata.mjs";
2
- import { claudeModelEntries } from "./claude-models.mjs";
2
+ import { claudeModelEntries, resolveClaudeModel } from "./claude-models.mjs";
3
3
  import http from "node:http";
4
4
  import { randomUUID, timingSafeEqual } from "node:crypto";
5
5
  import { createRequestAbort, abortErrorStatusCode, readJsonBody, readBoundedResponseText, writeOrDrain, MAX_UPSTREAM_ERROR_BODY_BYTES } from "./http-transport.mjs";
@@ -57,10 +57,10 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024) {
57
57
  finish() { consume(decoder.decode());if (fragments.length) line(fragments.join(""));frame(); } };
58
58
  }
59
59
 
60
- export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, onRequest = () => {}, env = process.env,
60
+ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
61
61
  record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
62
62
  if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
63
- const config = loadRuntimeConfig(env), performance = createStreamPerformanceMetrics({ routeNames: ["messages"] });
63
+ const config = loadRuntimeConfig(env), performance = sharedPerformance || createStreamPerformanceMetrics({ routeNames: ["messages"] });
64
64
  const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
65
65
  const stats = { total: 0, active: 0, completed: 0, incomplete: 0, failed: 0, cancelled: 0, last_request_at: null, last_model: null };
66
66
  async function dispatch(req, res) {
@@ -85,7 +85,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
85
85
  const tracker = countTokens ? null : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
86
86
  tracker?.setProvider(provider.id);
87
87
  const abort = createRequestAbort(req, res);
88
- let release = () => {}, outcome = "failed", model = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
88
+ let release = () => {}, outcome = "failed", model = null, configuredModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
89
89
  let terminalOrigin = "client_validation", failureStatus = null;
90
90
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
91
91
  await runWithRequestContext({ requestId, provider: provider.id, route: "messages", streamPerformance: tracker }, async () => {
@@ -96,7 +96,10 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
96
96
  if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
97
97
  send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
98
98
  }
99
- model = body.model;stats.last_model = model;streamed = !countTokens && body.stream === true;tracker?.setModel(model);
99
+ model = body.model;stats.last_model = model;streamed = !countTokens && body.stream === true;
100
+ configuredModel = provider.configuredModels ? resolveClaudeModel(provider.models("claude"), model)?.id : null;
101
+ tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
102
+ validateConversation?.(body, req.headers);
100
103
  terminalOrigin = "transport";
101
104
  const upstream = await provider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
102
105
  onUpstreamStart() { abort.setTimeout(streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs, "upstream_timeout"); } });
@@ -146,10 +149,10 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
146
149
  const detail = operationErrorDetails(error, { reason: abort.reason });
147
150
  outcome = detail.source === "cancelled" ? "cancelled" : "failed";
148
151
  const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
149
- failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : "transport";
152
+ failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
150
153
  const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
151
154
  log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}`);
152
- tracker?.setErrorOrigin(outcome === "cancelled" ? "client_disconnect" : "transport");
155
+ tracker?.setErrorOrigin(terminalOrigin);
153
156
  if (outcome === "cancelled") return;
154
157
  if (!res.headersSent) send(res, statusCode, apiError(error.code || abort.reason || "ccdx_gateway_error", message));
155
158
  else if (!res.destroyed && !res.writableEnded) res.end(`event: error\ndata: ${JSON.stringify(apiError("ccdx_gateway_error", message))}\n\n`);
@@ -157,7 +160,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
157
160
  release();abort.cleanup();
158
161
  if (!countTokens) {
159
162
  stats.active--;stats[outcome]++;
160
- tracker?.setModel(model);tracker?.setOutputTokens(usage?.output_tokens);
163
+ tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
161
164
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
162
165
  tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode });
163
166
  const client = req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude";
package/src/cli-m365.mjs CHANGED
@@ -12,9 +12,29 @@ import { autoReviewReasoningEfforts } from "./models.mjs";
12
12
  import { m365AccountMessage } from "./providers/m365-accounts.mjs";
13
13
  import { m365CatalogDiagnostic, m365CatalogMessage } from "./providers/m365-catalog-diagnostic.mjs";
14
14
  import { m365NetworkDiagnostic, m365NetworkMessage } from "./providers/m365-network-diagnostic.mjs";
15
+ import fs from "node:fs";
16
+ import { accessSettingsPath, readAccessSettings } from "./access-settings.mjs";
17
+
18
+ function codexSelection(options) {
19
+ const settings = readProviderSettings(options), access = fs.existsSync(accessSettingsPath(options)) ? readAccessSettings(options) : null;
20
+ const client = access?.clients.codex, provider = client ? client.enabled ? client.source : null : settings.codex;
21
+ if (provider === null) throw new Error("Codex access is paused. Review Settings in the WebUI.");
22
+ return { settings, access, client, provider };
23
+ }
15
24
 
16
25
  export async function fetchActiveProviderModels({ control = providerControl, ...options } = {}) {
17
- if (readProviderSettings(options).codex !== "m365") {
26
+ const selected = codexSelection(options);
27
+ if (selected.access) {
28
+ const config = selected.access, client = selected.client;
29
+ if (client.source.startsWith("api_")) {
30
+ const api = config.apis.find(api => api.id === client.source && api.enabled);
31
+ if (!api) throw new Error("The selected API is disabled. Review Settings in the WebUI.");
32
+ const models = api.models.filter(model => model.protocols.includes("responses"));
33
+ return { source: "configured", upstreamHost: new URL(api.base_url).hostname, advertised: models.length,
34
+ models: models.map(model => ({ id: model.id, vendor: "Unknown", endpoints: ["responses"], preview: false })) };
35
+ }
36
+ }
37
+ if (selected.provider !== "m365") {
18
38
  const { fetchLiveCopilotModels } = await import("./live-models.mjs");
19
39
  return fetchLiveCopilotModels(options);
20
40
  }
@@ -50,17 +70,28 @@ export function formatM365Status(state) {
50
70
  ...(claude.reason ? [`Claude detail: ${terminalCell(claude.reason)}`] : []),
51
71
  ...(claude.requests ? [`Claude requests: ${claude.requests.completed} completed / ${claude.requests.incomplete} incomplete / ${claude.requests.failed} failed / ${claude.requests.active} active`] : []),
52
72
  `Claude Code: ${claude.clients?.code || "unknown"}; Claude App: ${claude.clients?.app || "unknown"}`,
53
- `Codex provider: ${state.codex_provider || "github"} (default: github)`,
73
+ `Codex provider: ${state.codex_provider === null ? "off" : terminalCell(state.connections?.providers?.find(provider => provider.id === state.codex_provider)?.name || state.codex_provider || "github")} (default: github)`,
54
74
  ].join("\n");
55
75
  }
56
76
 
57
77
  export async function runProviderAutoReviewCommand(options = {}) {
58
78
  const { runAutoReviewModelCommand } = await import("./auto-review-model.mjs");
59
- const settings = readProviderSettings(options);
60
- if (settings.codex !== "m365") return runAutoReviewModelCommand(options);
79
+ const selected = codexSelection(options), settings = selected.settings;
80
+ if (selected.provider.startsWith("api_")) {
81
+ const api = selected.access.apis.find(api => api.id === selected.provider && api.enabled);
82
+ if (!api) throw new Error("The selected API is disabled. Review Settings in the WebUI.");
83
+ const state = await providerControl(options);if (state.codex_provider !== selected.provider) throw new Error("Saved and active sources differ. Restart CCDX before changing review settings.");
84
+ const preference = selected.client, models = api.models.filter(model => model.protocols.includes("responses"));
85
+ return runAutoReviewModelCommand({ ...options, env: { ...(options.env || process.env), CCDX_AUTO_REVIEW_MODEL: "" }, followClientLabel: "follow client (no override)",
86
+ loadCatalog: async () => ({ modelIds: models.map(model => model.id), source: api.name, reasoningEfforts: Object.fromEntries(models.map(model => [model.id, model.reasoning_efforts || []])) }),
87
+ getPreference: () => ({ model: preference.auto_review_model || preference.model, source: api.name, reasoningEffort: preference.auto_review_effort ?? null }),
88
+ savePreference: (model, { reasoningEffort }) => providerControl({ ...options, action: { action: "auto-review", provider: selected.provider, model, effort: reasoningEffort } }),
89
+ });
90
+ }
91
+ if (selected.provider !== "m365") return runAutoReviewModelCommand(options);
61
92
  const state = await providerControl(options);
62
93
  if (state.codex_provider !== "m365") throw new Error("Saved and active sources differ.\nRestart CCDX before changing review settings.");
63
- const preference = state.m365?.preference || settings.m365;
94
+ const preference = selected.client?.auto_review_model ? selected.client : state.m365?.preference || settings.m365;
64
95
  return runAutoReviewModelCommand({ ...options, env: { ...(options.env || process.env), CCDX_AUTO_REVIEW_MODEL: "" },
65
96
  loadCatalog: async () => {
66
97
  const result = await providerControl({ ...options, action: { action: "models", family: "gpt" } });
@@ -112,10 +143,15 @@ export async function runM365Command({ action = "status", provider, model, autoR
112
143
  }
113
144
  if (action === "switch") {
114
145
  if (!provider) {
115
- output.write("Codex provider:\n 1. GitHub Copilot (default)\n 2. Microsoft 365 (backup)\n");
116
- const answer = String(await ask("Choose 1 or 2; q cancels: ")).trim();
146
+ const graph = fs.existsSync(accessSettingsPath(options)) ? readAccessSettings(options) : null;
147
+ const choices = graph ? [{ id: "github", name: "GitHub Copilot" }, { id: "m365", name: "Microsoft 365" }, ...graph.apis.filter(api => api.enabled && api.models.some(model => model.protocols.includes("responses")))
148
+ .map(api => ({ id: api.id, name: api.name }))].filter(source => graph.clients.codex.allowed.includes(source.id) && (source.id.startsWith("api_") || graph.providers[source.id]))
149
+ : [{ id: "github", name: "GitHub Copilot (default)" }, { id: "m365", name: "Microsoft 365 (backup)" }];
150
+ if (!choices.length) throw new Error("No enabled Codex source. Review Settings in the WebUI.");
151
+ output.write("Codex provider:\n" + choices.map((source, index) => ` ${index + 1}. ${terminalCell(source.name)}\n`).join(""));
152
+ const answer = String(await ask(choices.length === 2 ? "Choose 1 or 2; q cancels: " : "Choose a source, or q to cancel: ")).trim();
117
153
  if (answer === "q") return { cancelled: true };
118
- if (!["1", "2"].includes(answer)) throw new Error("Choose 1 or 2");provider = answer === "1" ? "github" : "m365";
154
+ const index = Number(answer) - 1;if (!Number.isInteger(index) || !choices[index]) throw new Error("Choose a listed source");provider = choices[index].id;
119
155
  }
120
156
  if (provider === "m365") {
121
157
  const available = await request({ action: "models", family: "gpt" });
@@ -141,6 +177,10 @@ export async function runM365Command({ action = "status", provider, model, autoR
141
177
  output.write("M365 fast tier is not verified. Use Standard in Codex; existing threads keep their selected model until you change it.\n");
142
178
  }
143
179
  const state = await request({ action: "switch", provider, model, auto_review_model: autoReviewModel });
180
+ if (provider.startsWith("api_")) {
181
+ const api = state.connections?.providers.find(source => source.id === provider), client = state.connections?.clients.find(client => client.id === "codex");
182
+ output.write(`Codex source: ${terminalCell(api?.name || provider)}\nModel: ${terminalCell(client?.model)}\nReview: ${terminalCell(client?.auto_review_model)} / ${terminalCell(client?.auto_review_effort || "follow client")}\n`);return state;
183
+ }
144
184
  output.write(formatM365Status(state) + "\n");
145
185
  if (provider === "m365") output.write(`Select ${model} in Codex. Auto-review uses ${autoReviewModel} / low on this provider.\n`);
146
186
  return state;
@@ -21,7 +21,8 @@ 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", `${catalog?.source === "catalog" ? "Available catalog" : "Live catalog"} from ${safeText(catalog?.upstreamHost, "GitHub Copilot")}: ${models.length} selectable GPT models of ${Number(catalog?.advertised) || 0} advertised`),
24
+ status("ok", catalog?.source === "configured" ? `Configured models from ${safeText(catalog.upstreamHost)}: ${models.length}; access not checked`
25
+ : `${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
26
  status("info", `Responses: ${responses}; Chat: ${chat}`),
26
27
  ];
27
28
  }
@@ -174,7 +174,7 @@ export function parseCliArgs(args = []) {
174
174
  if (!["status", "models", "switch", "on", "off", "remove", "accounts", "account"].includes(action)) throw new Error("Choose status, models, accounts, account, switch, on, off or remove");
175
175
  let provider, remaining = args;
176
176
  if (action === "switch" && args[0] && !args[0].startsWith("--")) { provider = args[0];remaining = args.slice(1); }
177
- if (provider && !["github", "m365"].includes(provider)) throw new Error("Choose github or m365");
177
+ if (provider && !["github", "m365"].includes(provider) && !/^api_[a-z0-9_-]{1,60}$/.test(provider)) throw new Error("Choose github, m365 or a listed API source ID");
178
178
  const values = parseOptions(remaining, new Map(action === "switch" ? [["--model", "value"], ["--auto-review-model", "value"]] : action === "account" ? [["--id", "value"]] : []));
179
179
  if (values["--id"] && !/^[a-f0-9]{64}$/.test(values["--id"])) throw new Error("Use an account ID from ccdx m365 accounts");
180
180
  return baseCommand("m365", { action, provider, model: values["--model"], autoReviewModel: values["--auto-review-model"], ...(values["--id"] ? { accountId: values["--id"] } : {}) });
@@ -162,7 +162,7 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
162
162
  status("info", `Conversation buffer: ${mebibytes(history.bytes)} / ${mebibytes(limits.response_history_max_bytes)}, ${count(history.entries)} entries, ${count(history.evicted)} evicted ID markers`),
163
163
  status("info", `Image cache: ${count(images.cache_entries)} entries, ${cacheHitRate(images)} hits, ${mebibytes(images.cache_bytes)} / ${mebibytes(images.cache_max_bytes)}`),
164
164
  ];
165
- const sourceRoutes = { ...data.stream_performance?.by_route, ...data.providers?.m365?.claude?.requests?.performance?.by_route };
165
+ const sourceRoutes = { ...data.stream_performance?.by_route, ...(data.providers?.claude || data.providers?.m365?.claude)?.requests?.performance?.by_route };
166
166
  for (const [route, metrics] of Object.entries(sourceRoutes)) for (const [source, stats] of Object.entries(metrics.by_provider || {})) {
167
167
  const totals = stats.terminal_outcomes.totals;
168
168
  lines.push(status("info", `Source ${source} / ${route}: ${count(stats.active)} active, ${count(totals.completed)} completed, ${count(totals.incomplete)} incomplete, ${count(totals.failed)} failed, ${count(totals.cancelled)} cancelled, ${count(totals.unknown)} unknown`));
@@ -0,0 +1,29 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomBytes, timingSafeEqual } from "node:crypto";
4
+ import { accessSettingsPath, CLIENT_IDS, accessError } from "./access-settings.mjs";
5
+ import { readBoundedFileSync } from "./bounded-file.mjs";
6
+ import { withFileLockSync } from "./lock.mjs";
7
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
8
+
9
+ export function readClientGatewayKeys(options = {}) {
10
+ const file = path.join(path.dirname(accessSettingsPath(options)), "client-gateway-keys.json");
11
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
12
+ return withFileLockSync(`${file}.lock`, () => {
13
+ let value;
14
+ try { value = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 2048 })); }
15
+ catch (error) {
16
+ if (error.code !== "ENOENT") throw accessError("ccdx_client_keys_invalid", 409);
17
+ value = Object.fromEntries(CLIENT_IDS.map(id => [id, randomBytes(32).toString("hex")]));
18
+ atomicWriteFileSync(file, JSON.stringify(value) + "\n", { mode: 0o600 });
19
+ }
20
+ if (!value || Object.keys(value).length !== CLIENT_IDS.length || CLIENT_IDS.some(id => !/^[a-f0-9]{64}$/.test(value[id]))) throw accessError("ccdx_client_keys_invalid", 409);
21
+ return value;
22
+ });
23
+ }
24
+ export function gatewayClient(headers, keys) {
25
+ const candidate = typeof headers?.["x-api-key"] === "string" ? headers["x-api-key"] : /^Bearer (.+)$/i.exec(headers?.authorization || "")?.[1];
26
+ if (!candidate || candidate.length !== 64) return null;
27
+ const bytes = Buffer.from(candidate);if (bytes.length !== 64) return null;
28
+ return CLIENT_IDS.find(id => timingSafeEqual(bytes, Buffer.from(keys[id]))) || null;
29
+ }
@@ -0,0 +1,51 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { parse } from "smol-toml";
4
+ import { codexPaths } from "./codex-paths.mjs";
5
+ import { accessSettingsPath, accessError } from "./access-settings.mjs";
6
+ import { readBoundedFileSync } from "./bounded-file.mjs";
7
+ import { atomicWriteFilePairSync } from "./atomic-file.mjs";
8
+ import { withFileLockSync } from "./lock.mjs";
9
+
10
+ const ID = "ccdx_gateway";
11
+ // Only the provider, selected model and private provider table are owned.
12
+ export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...options } = {}) {
13
+ if (!restore) {
14
+ let url;try { url = new URL(baseUrl); } catch { throw accessError("ccdx_codex_config_invalid"); }
15
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/v1" || url.username || url.password || url.search || url.hash
16
+ || !/^[a-f0-9]{64}$/.test(apiKey)) throw accessError("ccdx_codex_config_invalid");
17
+ }
18
+ const file = codexPaths(options).config, journal = path.join(path.dirname(accessSettingsPath(options)), "codex-gateway-owner.json");
19
+ if (restore && !fs.existsSync(journal)) return { state: "unchanged" };
20
+ fs.mkdirSync(path.dirname(journal), { recursive: true, mode: 0o700 });fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
21
+ return withFileLockSync(`${journal}.lock`, () => {
22
+ let content = "", owner = null;
23
+ try { content = readBoundedFileSync(file, { encoding: "utf8", maxBytes: 1024 * 1024 }); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_codex_config_invalid", 409); }
24
+ try { owner = JSON.parse(readBoundedFileSync(journal, { encoding: "utf8", maxBytes: 16384 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_codex_config_invalid", 409); }
25
+ let config;try { config = parse(content); } catch { throw accessError("ccdx_codex_config_invalid", 409); }
26
+ if (owner && (owner.version !== 1 || typeof owner.section !== "string" || !Object.hasOwn(owner, "beforeProvider") || !Object.hasOwn(owner, "beforeSection"))) throw accessError("ccdx_codex_config_invalid", 409);
27
+ const firstTable = content.search(/^\s*\[/m), head = firstTable < 0 ? content : content.slice(0, firstTable), tail = firstTable < 0 ? "" : content.slice(firstTable);
28
+ const sectionPattern = /^\[model_providers\.ccdx_gateway\]\r?\n[^]*?(?=^\[|$(?![^]))/m;
29
+ const currentSection = tail.match(sectionPattern)?.[0] || null;
30
+ if (owner && (config.model_provider !== ID || currentSection !== owner.section || owner.model !== undefined && config.model !== owner.model)) return { state: "preserved" };
31
+ if (!owner && (config.model_provider && config.model_provider !== "openai" || config.model_providers?.[ID])) return { state: "preserved" };
32
+ let next, nextOwner = null;
33
+ if (restore) {
34
+ if (!owner) return { state: "unchanged" };
35
+ let root = head.replace(/^model_provider\s*=.*(?:\r?\n|$)/m, owner.beforeProvider || "");
36
+ if (owner.model !== undefined) root = root.replace(/^model\s*=.*(?:\r?\n|$)/m, owner.beforeModel || "");
37
+ next = root + tail.replace(sectionPattern, owner.beforeSection || "");
38
+ } else {
39
+ const section = `[model_providers.${ID}]\nname = "CCDX"\nbase_url = ${JSON.stringify(baseUrl)}\nmodel_catalog_url = ${JSON.stringify(baseUrl + "/models")}\nwire_api = "responses"\nexperimental_bearer_token = ${JSON.stringify(apiKey)}\n\n`;
40
+ let root = head;
41
+ if (model) root = root.match(/^model\s*=/m) ? root.replace(/^model\s*=.*(?:\r?\n|$)/m, `model = ${JSON.stringify(model)}\n`) : `model = ${JSON.stringify(model)}\n` + root;
42
+ next = (root.match(/^model_provider\s*=/m) ? root.replace(/^model_provider\s*=.*(?:\r?\n|$)/m, `model_provider = "${ID}"\n`) : `model_provider = "${ID}"\n` + root)
43
+ + (currentSection ? tail.replace(sectionPattern, section) : tail + (tail && !tail.endsWith("\n") ? "\n" : "") + "\n" + section);
44
+ nextOwner = { version: 1, beforeProvider: owner ? owner.beforeProvider : head.match(/^model_provider\s*=.*(?:\r?\n|$)/m)?.[0] || null,
45
+ beforeSection: owner ? owner.beforeSection : currentSection, section,
46
+ ...(model ? { model, beforeModel: owner && Object.hasOwn(owner, "beforeModel") ? owner.beforeModel : head.match(/^model\s*=.*(?:\r?\n|$)/m)?.[0] || null } : {}) };
47
+ }
48
+ parse(next);if (next !== content || JSON.stringify(nextOwner) !== JSON.stringify(owner)) atomicWriteFilePairSync(file, next, journal, nextOwner ? JSON.stringify(nextOwner) + "\n" : null, { mode: 0o600 });
49
+ return { state: "configured", changed: next !== content };
50
+ });
51
+ }