codex-copilot-dx 1.1.1 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -11
- package/bin/cli.mjs +23 -23
- package/docs/ARCHITECTURE.md +40 -6
- package/docs/REFERENCE.md +128 -94
- package/package.json +6 -4
- package/src/auth-device-flow.mjs +1 -1
- package/src/auth-status.mjs +1 -1
- package/src/auto-review-model.mjs +2 -2
- package/src/claude-client-lifecycle.mjs +33 -0
- package/src/claude-gateway.mjs +15 -6
- package/src/cli-auth.mjs +6 -6
- package/src/cli-cache.mjs +5 -5
- package/src/cli-image.mjs +1 -1
- package/src/cli-m365.mjs +5 -5
- package/src/cli-models.mjs +2 -2
- package/src/cli-options.mjs +26 -26
- package/src/cli-status.mjs +6 -1
- package/src/dashboard/console.js +112 -38
- package/src/dashboard/index.html +122 -90
- package/src/dashboard/language.js +791 -362
- package/src/dashboard/status.js +53 -41
- package/src/dashboard/ui.css +13 -0
- package/src/dashboard/ui.js +31 -28
- package/src/dashboard/usage.js +16 -16
- package/src/dashboard-api.mjs +2 -0
- package/src/doctor.mjs +4 -4
- package/src/http-transport.mjs +3 -2
- package/src/launcher.mjs +8 -8
- package/src/native-prediction.mjs +3 -3
- package/src/operation-error.mjs +12 -7
- package/src/package-update.mjs +43 -11
- package/src/prediction-retirement.mjs +2 -7
- package/src/provider-metadata.mjs +2 -1
- package/src/provider-registry.mjs +19 -0
- package/src/provider-runtime.mjs +42 -33
- package/src/provider-settings.mjs +2 -1
- package/src/release-install.mjs +192 -0
- package/src/response-failures.mjs +2 -1
- package/src/service-control.mjs +7 -8
- package/src/startup-ui.mjs +17 -9
- package/src/stream-performance.mjs +29 -1
- package/src/terminal-console.mjs +43 -15
- package/src/usage-store.mjs +10 -5
- package/src/user-settings.mjs +16 -3
- package/src/version.mjs +2 -6
- package/src/windows-command.mjs +13 -1
package/src/launcher.mjs
CHANGED
|
@@ -99,7 +99,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
99
99
|
child.once("error", () => resolve(false));
|
|
100
100
|
child.once("spawn", () => { child.unref(); resolve(true); });
|
|
101
101
|
});
|
|
102
|
-
if (!launched) { onPredictionRoute("unverified");log(status("warn", "Could not
|
|
102
|
+
if (!launched) { onPredictionRoute("unverified");log(status("warn", "Could not open the registered Codex App"));return false; }
|
|
103
103
|
await new Promise(resolve => setTimeout(resolve, 300));
|
|
104
104
|
const actual = windowsAppProcesses(current.app, { env });
|
|
105
105
|
const routeRetained = actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl;
|
|
@@ -114,13 +114,13 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
114
114
|
}
|
|
115
115
|
}
|
|
116
116
|
if (platform !== "darwin") {
|
|
117
|
-
log(status("warn", "
|
|
118
|
-
log(status("info", "Open Codex App
|
|
117
|
+
log(status("warn", "Auto-open needs macOS or Windows suggestion setup."));
|
|
118
|
+
log(status("info", "Open Codex App to use this service."));
|
|
119
119
|
return false;
|
|
120
120
|
}
|
|
121
121
|
|
|
122
122
|
if (!autoLaunchEnabled(env)) {
|
|
123
|
-
log(status("info", "Auto-
|
|
123
|
+
log(status("info", "Auto-open is off. Open Codex App manually.\nCCDX_AUTO_LAUNCH=0"));
|
|
124
124
|
return false;
|
|
125
125
|
}
|
|
126
126
|
|
|
@@ -141,7 +141,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
141
141
|
}
|
|
142
142
|
await preparePredictionRoute?.();
|
|
143
143
|
if (!await tryOpen([predictionApp, ...extraArgs], { spawnImpl })) {
|
|
144
|
-
onPredictionRoute("unverified");log(status("warn", "Could not
|
|
144
|
+
onPredictionRoute("unverified");log(status("warn", "Could not open Codex App"));return false;
|
|
145
145
|
}
|
|
146
146
|
for (let attempt = 0; attempt < 10; attempt++) {
|
|
147
147
|
const actual = macAppProcesses(predictionApp);
|
|
@@ -161,13 +161,13 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
161
161
|
for (const attempt of attempts) {
|
|
162
162
|
const args = [...attempt, ...extraArgs];
|
|
163
163
|
if (await tryOpen(args, { spawnImpl })) {
|
|
164
|
-
log(status("ok", "Codex
|
|
164
|
+
log(status("ok", "Codex opened"));
|
|
165
165
|
return true;
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
168
|
|
|
169
|
-
log(status("warn", "Could not
|
|
170
|
-
log(status("info", "Open Codex App
|
|
169
|
+
log(status("warn", "Could not find or open Codex App.\nChecked com.openai.codex, Codex.app and ChatGPT.app."));
|
|
170
|
+
log(status("info", "Open Codex App to use this service."));
|
|
171
171
|
log(status("info", "Download it from https://openai.com/codex"));
|
|
172
172
|
return false;
|
|
173
173
|
}
|
|
@@ -35,10 +35,10 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
35
35
|
const settings = readPredictionSettings(opts);
|
|
36
36
|
if (action === "fix") {
|
|
37
37
|
if (!settings.enabled) {
|
|
38
|
-
output("
|
|
38
|
+
output("Input suggestions are off. Nothing changed.\nTo enable: ccdx prediction on");
|
|
39
39
|
return { status: "disabled", exitCode: 0 };
|
|
40
40
|
}
|
|
41
|
-
if (!repairRuntime) throw new Error("
|
|
41
|
+
if (!repairRuntime) throw new Error("Start a CCDX version that supports suggestion repair.");
|
|
42
42
|
const result = await repairRuntime();
|
|
43
43
|
const prediction = result.prediction;
|
|
44
44
|
output(`Prediction repair: ${result.status}; bridge: ${prediction.bridge}; candidate: ${prediction.candidate}`);
|
|
@@ -74,7 +74,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
74
74
|
}
|
|
75
75
|
return settings;
|
|
76
76
|
}
|
|
77
|
-
if (!["on", "off"].includes(action)) throw new Error("
|
|
77
|
+
if (!["on", "off"].includes(action)) throw new Error("Choose prediction on, off, status or fix.");
|
|
78
78
|
if (!["darwin", "win32"].includes(platform)) throw new Error("Native prediction setup supports macOS and Windows only; no configuration changed");
|
|
79
79
|
let paths = predictionPaths({ ...opts, app: settings.app });
|
|
80
80
|
if (action === "off") {
|
package/src/operation-error.mjs
CHANGED
|
@@ -4,19 +4,24 @@ export function operationError(code, message, { status = null, retryAt = null }
|
|
|
4
4
|
return Object.assign(new Error(message), { code, status, retryAt });
|
|
5
5
|
}
|
|
6
6
|
|
|
7
|
-
export function operationErrorDetails(error) {
|
|
8
|
-
const code = String(error?.code || error?.cause?.code || "unknown");
|
|
7
|
+
export function operationErrorDetails(error, { reason } = {}) {
|
|
8
|
+
const code = String(reason || error?.code || error?.cause?.code || "unknown");
|
|
9
|
+
const status = Number.isInteger(error?.status) ? error.status : Number.isInteger(error?.statusCode) ? error.statusCode : null;
|
|
9
10
|
let source = "unknown";
|
|
10
|
-
if (
|
|
11
|
+
if (["client_aborted", "client_closed", "cancelled"].includes(code)) source = "cancelled";
|
|
12
|
+
else if (/proxy/i.test(code)) source = "proxy";
|
|
11
13
|
else if (/cert|tls|ssl/i.test(code)) source = "tls";
|
|
12
|
-
else if (/timeout|
|
|
13
|
-
else if (/
|
|
14
|
+
else if (/timeout|timed_out/i.test(code) || error?.name === "TimeoutError") source = "timeout";
|
|
15
|
+
else if (/abort/i.test(code) || error?.name === "AbortError") source = "aborted";
|
|
16
|
+
else if (status === 429 || /limit|429/.test(code)) source = "rate_limit";
|
|
17
|
+
else if (status === 401) source = "authentication";
|
|
18
|
+
else if (status === 403) source = "access_denied";
|
|
14
19
|
else if (/config|format|route|redirect/.test(code)) source = "configuration";
|
|
15
|
-
else if (/HTTP|http/.test(code)) source = "upstream";
|
|
16
20
|
else if (/ENOTFOUND|ECONN|EAI_/.test(code)) source = "network";
|
|
21
|
+
else if (/HTTP|http/.test(code) || status >= 400) source = "upstream";
|
|
17
22
|
return { code: /^[A-Za-z0-9_-]{1,80}$/.test(code) ? code : "unknown", source,
|
|
18
23
|
message: redactDiagnosticText(String(error?.message || "Operation failed")).slice(0, 400),
|
|
19
|
-
status
|
|
24
|
+
status };
|
|
20
25
|
}
|
|
21
26
|
|
|
22
27
|
// Error classifiers consume decoded string fields; responses retain their
|
package/src/package-update.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { spawn, execFileSync } from "node:child_process";
|
|
2
2
|
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { downloadRelease, protectInstallation, verifyPackageRuntime, writePrivateLaunchers, createNpmReleaseFetch } from "./release-install.mjs";
|
|
3
5
|
import path from "node:path";
|
|
4
6
|
import { fileURLToPath } from "node:url";
|
|
5
7
|
import { createInterface } from "node:readline/promises";
|
|
@@ -10,7 +12,7 @@ import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
|
10
12
|
const PACKAGE_NAME = "codex-copilot-dx";
|
|
11
13
|
const UPDATE_SPECS = {
|
|
12
14
|
npm: `${PACKAGE_NAME}@latest`,
|
|
13
|
-
github: "github
|
|
15
|
+
github: "https://github.com/DaleXiao/codex-copilot-dx/releases/download",
|
|
14
16
|
};
|
|
15
17
|
|
|
16
18
|
function npmLaunch(args, { platform, env }) {
|
|
@@ -75,15 +77,17 @@ export function inspectNpmDownloadPolicy({ env = process.env, platform = process
|
|
|
75
77
|
return result;
|
|
76
78
|
}
|
|
77
79
|
|
|
78
|
-
export function globalUpdateCommand(source, { platform = process.platform, releaseTag, allowRemote = false } = {}) {
|
|
80
|
+
export function globalUpdateCommand(source, { platform = process.platform, releaseTag, releaseFile, allowRemote = false } = {}) {
|
|
79
81
|
if (typeof allowRemote !== "boolean") throw new Error("Remote download permission must be a boolean");
|
|
80
82
|
const normalized = normalizeUpdateSource(source);
|
|
81
|
-
if (!normalized) throw new Error(`
|
|
83
|
+
if (!normalized) throw new Error(`Choose npm or github. Received: ${source}`);
|
|
82
84
|
const args = ["install", "--global"];
|
|
83
85
|
if (allowRemote) args.push("--allow-remote=all");
|
|
84
86
|
if (normalized === "github") {
|
|
85
87
|
if (!githubReleaseVersion(releaseTag)) throw new Error("A valid stable GitHub release tag is required");
|
|
86
|
-
|
|
88
|
+
const version = githubReleaseVersion(releaseTag), name = `codex-copilot-dx-${version}.tgz`;
|
|
89
|
+
if (releaseFile !== undefined && releaseFile !== `./${name}`) throw new Error("Invalid verified release filename");
|
|
90
|
+
args.push(releaseFile || `${UPDATE_SPECS.github}/v${version}/${name}`);
|
|
87
91
|
} else {
|
|
88
92
|
args.push(UPDATE_SPECS[normalized]);
|
|
89
93
|
}
|
|
@@ -137,10 +141,13 @@ export async function runPackageUpdateCommand({
|
|
|
137
141
|
inspectPolicyFn = inspectNpmDownloadPolicy,
|
|
138
142
|
verifyInstalledFn = verifyInstalledPackage,
|
|
139
143
|
repairCommandFn,
|
|
144
|
+
downloadReleaseFn = downloadRelease,
|
|
145
|
+
protectInstallationFn = protectInstallation,
|
|
146
|
+
verifyRuntimeFn = verifyPackageRuntime,
|
|
140
147
|
} = {}) {
|
|
141
148
|
if (typeof allowRemote !== "boolean") throw new Error("Remote download permission must be a boolean");
|
|
142
149
|
let selectedSource = normalizeUpdateSource(source);
|
|
143
|
-
if (source && !selectedSource) throw new Error(`
|
|
150
|
+
if (source && !selectedSource) throw new Error(`Choose npm or github. Received: ${source}`);
|
|
144
151
|
|
|
145
152
|
if (!selectedSource) {
|
|
146
153
|
if (!prompt && (!input.isTTY || !output.isTTY)) {
|
|
@@ -158,7 +165,7 @@ export async function runPackageUpdateCommand({
|
|
|
158
165
|
});
|
|
159
166
|
try {
|
|
160
167
|
while (!selectedSource) {
|
|
161
|
-
const answer = String(await ask("
|
|
168
|
+
const answer = String(await ask("Choose update source [1], or q to cancel: ") || "").trim().toLowerCase();
|
|
162
169
|
if (answer === "q" || answer === "quit") {
|
|
163
170
|
output.write("No changes made.\n");
|
|
164
171
|
return { cancelled: true, source: "" };
|
|
@@ -172,6 +179,14 @@ export async function runPackageUpdateCommand({
|
|
|
172
179
|
}
|
|
173
180
|
}
|
|
174
181
|
|
|
182
|
+
const environment = inspectEnvironmentFn({ env, platform });
|
|
183
|
+
if (selectedSource === "github" && fetchImpl === globalThis.fetch) {
|
|
184
|
+
let npmCli;
|
|
185
|
+
try {
|
|
186
|
+
npmCli = platform === "win32" ? path.win32.join(path.win32.dirname(environment.npm), "node_modules", "npm", "bin", "npm-cli.js") : fs.realpathSync(environment.npm);
|
|
187
|
+
} catch { throw new Error("Cannot locate npm for verified Release downloads. Use an approved local package or the platform installer."); }
|
|
188
|
+
fetchImpl = createNpmReleaseFetch(npmCli, { env });
|
|
189
|
+
}
|
|
175
190
|
let release;
|
|
176
191
|
if (selectedSource === "github") {
|
|
177
192
|
output.write("Checking the latest stable GitHub release...\n");
|
|
@@ -180,21 +195,33 @@ export async function runPackageUpdateCommand({
|
|
|
180
195
|
const policy = inspectPolicyFn({ env, platform });
|
|
181
196
|
if (allowRemote && policy.supported === null) throw new Error("Could not verify npm's remote-download option; no installation was started. Check npm --version and npm config get allow-remote.");
|
|
182
197
|
const permitRemote = allowRemote && policy.supported === true;
|
|
183
|
-
|
|
198
|
+
let directory, artifact;
|
|
199
|
+
if (release) {
|
|
200
|
+
directory = fs.mkdtempSync(path.join(os.tmpdir(), "ccdx-update-"));
|
|
201
|
+
try { artifact = await downloadReleaseFn(release.tagName, { fetchImpl, directory }); }
|
|
202
|
+
catch (error) { fs.rmSync(directory, { recursive: true, force: true });throw error; }
|
|
203
|
+
output.write("Release package verified; Git is not required. Dependencies use the configured npm registry.\n");
|
|
204
|
+
}
|
|
205
|
+
try {
|
|
206
|
+
const update = globalUpdateCommand(selectedSource, { platform, releaseTag: release?.tagName, releaseFile: artifact ? `./${artifact.name}` : undefined, allowRemote: permitRemote });
|
|
184
207
|
const sourceLabel = selectedSource === "npm" ? "npm registry" : `GitHub release ${release.tagName}`;
|
|
185
208
|
output.write(`Updating ${PACKAGE_NAME} from ${sourceLabel}...\n`);
|
|
186
209
|
if (policy.allowRemote) output.write(`npm ${terminalCell(policy.version)}: saved allow-remote=${policy.allowRemote}${policy.registryOrigin ? `; registry ${terminalCell(policy.registryOrigin)}` : ""}.\n`);
|
|
187
210
|
if (permitRemote) output.write("Explicit permission for this update only: npm may download URL dependencies throughout the selected package's dependency tree. Registry and persistent npm settings are unchanged.\n");
|
|
188
211
|
else if (allowRemote) output.write("This npm does not expose the remote-download restriction; no unsupported permission flag was added.\n");
|
|
189
|
-
const environment = inspectEnvironmentFn({ env, platform });
|
|
190
212
|
if (environment?.state === "different") {
|
|
191
213
|
output.write(`Warning: npm targets ${terminalCell(environment.target)}, not the running package at ${terminalCell(environment.package_root)}. Existing PATH and prefix choices were preserved.\n`);
|
|
192
214
|
}
|
|
193
|
-
//
|
|
194
|
-
//
|
|
215
|
+
// The verified tarball basename is fixed and safe for cmd.exe. Its directory
|
|
216
|
+
// is passed as cwd, never interpolated into the Windows command string.
|
|
195
217
|
const launch = npmLaunch(update.args, { platform, env });
|
|
218
|
+
const brokerRequired = Boolean(environment?.target && fs.existsSync(path.join(environment.target, "node_modules", "@azure", "msal-node-runtime")));
|
|
219
|
+
const transaction = protectInstallationFn({ ...environment, platform });
|
|
220
|
+
let installedVersion;
|
|
221
|
+
try {
|
|
196
222
|
const child = spawnImpl(launch.command, launch.args, {
|
|
197
223
|
env,
|
|
224
|
+
...(directory ? { cwd: directory } : {}),
|
|
198
225
|
shell: false,
|
|
199
226
|
stdio: "inherit",
|
|
200
227
|
...launch.options,
|
|
@@ -206,7 +233,11 @@ export async function runPackageUpdateCommand({
|
|
|
206
233
|
}
|
|
207
234
|
throw error;
|
|
208
235
|
}
|
|
209
|
-
|
|
236
|
+
installedVersion = verifyInstalledFn(environment?.target, { expectedVersion: release?.version });
|
|
237
|
+
if (environment?.target && installedVersion) verifyRuntimeFn(environment.target, installedVersion, { brokerRequired });
|
|
238
|
+
if (env.CCDX_PRIVATE_INSTALL_PREFIX && environment?.prefix && (platform === "win32" ? path.win32.resolve(env.CCDX_PRIVATE_INSTALL_PREFIX).toLowerCase() === path.win32.resolve(environment.prefix).toLowerCase() : path.resolve(env.CCDX_PRIVATE_INSTALL_PREFIX) === path.resolve(environment.prefix))) await writePrivateLaunchers(environment);
|
|
239
|
+
transaction.commit();
|
|
240
|
+
} catch (error) { transaction.rollback();throw error; }
|
|
210
241
|
if (installedVersion) {
|
|
211
242
|
output.write(`Updated ${PACKAGE_NAME}: installed v${terminalCell(installedVersion)} at ${terminalCell(environment.target)}.\n`);
|
|
212
243
|
if (platform === "win32") {
|
|
@@ -221,4 +252,5 @@ export async function runPackageUpdateCommand({
|
|
|
221
252
|
}
|
|
222
253
|
output.write("Restart the running adapter to use the installed version; an existing service is not replaced automatically.\n");
|
|
223
254
|
return { cancelled: false, source: selectedSource };
|
|
255
|
+
} finally { if (directory) fs.rmSync(directory, { recursive: true, force: true }); }
|
|
224
256
|
}
|
|
@@ -14,12 +14,7 @@ const same = (left, right) => isDeepStrictEqual(left, right);
|
|
|
14
14
|
|
|
15
15
|
export function computeRetiredPredictionConfig(content, filePath) {
|
|
16
16
|
const before = parseCodexToml(content);
|
|
17
|
-
const expected = {
|
|
18
|
-
command: process.execPath,
|
|
19
|
-
args: [fileURLToPath(new URL("./suggestion-mcp.mjs", import.meta.url))],
|
|
20
|
-
env: { CCDX_SUGGESTION_CONFIG: filePath },
|
|
21
|
-
tool_timeout_sec: 40n,
|
|
22
|
-
};
|
|
17
|
+
const expected = parseCodexToml(`command = ${JSON.stringify(process.execPath)}\nargs = ${JSON.stringify([fileURLToPath(new URL("./suggestion-mcp.mjs", import.meta.url))])}\nenv = { CCDX_SUGGESTION_CONFIG = ${JSON.stringify(filePath)} }\ntool_timeout_sec = 40\n`);
|
|
23
18
|
const existing = before.mcp_servers?.ccdx_suggestion;
|
|
24
19
|
const owned = existing && typeof existing.enabled === "boolean"
|
|
25
20
|
&& same({ ...existing, enabled: undefined }, { ...expected, enabled: undefined });
|
|
@@ -46,7 +41,7 @@ export function computeRetiredPredictionConfig(content, filePath) {
|
|
|
46
41
|
const after = parseCodexToml(updated);
|
|
47
42
|
const remaining = [...(before.hooks?.Stop || [])];
|
|
48
43
|
if (hookOwned) {
|
|
49
|
-
const index = remaining.findIndex(group => same(group,
|
|
44
|
+
const index = remaining.findIndex(group => same(group, parseCodexToml(block).hooks.Stop[0]));
|
|
50
45
|
if (index < 0) throw new Error("Retired prediction hook could not be safely removed");
|
|
51
46
|
remaining.splice(index, 1);
|
|
52
47
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { autoReviewReasoningEfforts } from "./models.mjs";
|
|
1
2
|
// Public metadata only. Credentials and provider transport never enter this layer.
|
|
2
3
|
export const isProviderId = value => typeof value === "string" && /^[a-z][a-z0-9_-]{0,63}$/.test(value)
|
|
3
4
|
&& !["constructor", "prototype"].includes(value);
|
|
@@ -13,7 +14,7 @@ export function publicModelCatalog(models, { clients = () => [], selectable = ()
|
|
|
13
14
|
endpoints: [["responses", ["/responses", "/v1/responses"]], ["chat", ["/chat/completions", "/v1/chat/completions"]],
|
|
14
15
|
["messages", ["/v1/messages"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
|
|
15
16
|
preview: model.preview === true, selectable: selectable(model), clients: clients(model),
|
|
16
|
-
reasoning_efforts: modelReasoningEfforts(model),
|
|
17
|
+
reasoning_efforts: modelReasoningEfforts(model), auto_review_efforts: autoReviewReasoningEfforts(model),
|
|
17
18
|
context_window: Number.isSafeInteger(model.capabilities?.limits?.max_context_window_tokens)
|
|
18
19
|
&& model.capabilities.limits.max_context_window_tokens > 0 ? model.capabilities.limits.max_context_window_tokens : null,
|
|
19
20
|
state: model.policy?.state && model.policy.state !== "enabled" ? "restricted" : model.model_picker_enabled === false ? "hidden" : "listed",
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { isProviderId } from "./provider-metadata.mjs";
|
|
2
|
+
|
|
3
|
+
// Internal composition metadata, never a loader for third-party code.
|
|
4
|
+
export const PROVIDER_DEFINITIONS = Object.freeze([
|
|
5
|
+
Object.freeze({ id: "github", name: "GitHub Copilot", codex: true, modelSelection: false }),
|
|
6
|
+
Object.freeze({ id: "m365", name: "Microsoft 365", codex: true, modelSelection: true }),
|
|
7
|
+
]);
|
|
8
|
+
|
|
9
|
+
export function createProviderRegistry(definitions = PROVIDER_DEFINITIONS) {
|
|
10
|
+
const entries = new Map();
|
|
11
|
+
if (!Array.isArray(definitions) || definitions.length > 16) throw new Error("Invalid source registry");
|
|
12
|
+
for (const definition of definitions) {
|
|
13
|
+
if (!isProviderId(definition?.id) || entries.has(definition.id) || typeof definition.name !== "string" || !definition.name.trim()) throw new Error("Invalid or duplicate source");
|
|
14
|
+
entries.set(definition.id, Object.freeze({ ...definition }));
|
|
15
|
+
}
|
|
16
|
+
return Object.freeze({ get: id => entries.get(id), list: () => [...entries.values()] });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const providerRegistry = createProviderRegistry();
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import { autoReviewPreference, writeAutoReviewModel } from "./user-settings.mjs";
|
|
3
|
+
import { autoReviewReasoningEfforts, DEFAULT_CODEX_AUTO_REVIEW_MODEL, responsesModelIdsFromCopilotModels } from "./models.mjs";
|
|
2
4
|
import { publicModelCatalog } from "./provider-metadata.mjs";
|
|
3
5
|
import { createGithubProvider } from "./providers/github.mjs";
|
|
4
6
|
import { readProviderSettings, writeProviderSettings } from "./provider-settings.mjs";
|
|
5
7
|
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey } from "./m365-settings.mjs";
|
|
8
|
+
import { providerRegistry } from "./provider-registry.mjs";
|
|
9
|
+
import { createClaudeClientLifecycle } from "./claude-client-lifecycle.mjs";
|
|
6
10
|
|
|
7
11
|
const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
|
|
8
12
|
{ code: reason, statusCode: 503 });
|
|
@@ -15,7 +19,9 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
15
19
|
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
16
20
|
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
17
21
|
let selection = readProviderSettings(options), m365 = null, gateway = null, pending = null, closed = false, serial = null;
|
|
18
|
-
let reason = null, claudeReason = null,
|
|
22
|
+
let reason = null, claudeReason = null, lastClients = {};
|
|
23
|
+
const clientLifecycle = createClaudeClientLifecycle({ options, configureClients, restoreClients });
|
|
24
|
+
const sources = new Map([[github.id, github]]);
|
|
19
25
|
const dashboardProfiles = new Map();
|
|
20
26
|
const dashboardGeneration = provider => {
|
|
21
27
|
const profile = provider.profileId(), previous = dashboardProfiles.get(provider.id);
|
|
@@ -27,23 +33,12 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
27
33
|
try { enabled = readM365Settings(options).enabled && env.CCDX_M365 !== "0"; }
|
|
28
34
|
catch { enabled = false;reason = "m365_config_invalid"; }
|
|
29
35
|
|
|
30
|
-
let clientSync = null;
|
|
31
36
|
async function syncClaudeClients() {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const integration = configureClients ? null : await import("./claude-client-config.mjs");
|
|
38
|
-
const configure = configureClients || integration.configureClaudeClients;
|
|
39
|
-
const desktopManaged = integration ? await integration.inspectClaudeDesktopPolicy(options) : false;
|
|
40
|
-
if (closed || !enabled || source !== m365 || source.profileId() !== profile || !gateway) return;
|
|
41
|
-
claudeReason = source.models("claude").length ? null : "m365_no_claude_models";
|
|
42
|
-
clients = configure({ ...options, desktopManaged, baseUrl: `http://127.0.0.1:${corePort}/anthropic`,
|
|
43
|
-
apiKey: ensureM365GatewayKey(options), models: source.models("claude") });
|
|
44
|
-
} catch { clients = { code: "configuration_unavailable", app: "configuration_unavailable" };claudeReason = "m365_claude_config_unavailable"; }
|
|
45
|
-
})().finally(() => { clientSync = null; });
|
|
46
|
-
return clientSync;
|
|
37
|
+
const source = m365, profile = source?.profileId();
|
|
38
|
+
if (!source || !gateway || closed || !enabled) return;
|
|
39
|
+
await clientLifecycle.sync({ source, baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: () => ensureM365GatewayKey(options),
|
|
40
|
+
current: () => !closed && enabled && source === m365 && source.profileId() === profile && Boolean(gateway) });
|
|
41
|
+
claudeReason = clientLifecycle.snapshot().reason || (source.models("claude").length ? null : "m365_no_claude_models");
|
|
47
42
|
}
|
|
48
43
|
|
|
49
44
|
async function startM365(forceRefresh = false) {
|
|
@@ -58,6 +53,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
58
53
|
// Reconcile after refresh, outside inference serialization and without a watcher.
|
|
59
54
|
setImmediate(() => { if (!pending && gateway && !closed && enabled) void syncClaudeClients(); });
|
|
60
55
|
} });
|
|
56
|
+
sources.set(m365.id, m365);
|
|
61
57
|
}
|
|
62
58
|
await m365.refresh();if (closed || !enabled) return null;
|
|
63
59
|
const claudeModels = m365.models("claude");
|
|
@@ -86,27 +82,27 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
86
82
|
}
|
|
87
83
|
|
|
88
84
|
const snapshot = () => ({ codex_provider: selection.codex,
|
|
89
|
-
github: { state: "configured", profile: "codex" },
|
|
85
|
+
github: { state: "configured", profile: "codex", preference: autoReviewPreference(options) },
|
|
90
86
|
m365: { ...(m365?.snapshot() || {}), enabled, state: !enabled ? "disabled" : pending ? "checking"
|
|
91
87
|
: !["darwin", "win32"].includes(platform) ? "unsupported" : m365?.snapshot().state || (reason ? "unavailable" : "idle"),
|
|
92
88
|
reason: reason || m365?.snapshot().reason || null,
|
|
93
89
|
preference: selection.m365 || null,
|
|
94
90
|
active_requests: activeM365Requests,
|
|
95
91
|
claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway ? corePort : null,
|
|
96
|
-
base_url: gateway ? `http://127.0.0.1:${corePort}/anthropic` : null, clients:
|
|
92
|
+
base_url: gateway ? `http://127.0.0.1:${corePort}/anthropic` : null, clients: clientLifecycle.snapshot().clients,
|
|
97
93
|
observed_clients: { ...lastClients }, requests: gateway?.snapshot?.() || null } } });
|
|
98
94
|
|
|
99
95
|
function current() {
|
|
100
|
-
|
|
101
|
-
if (!
|
|
102
|
-
return
|
|
96
|
+
const source = sources.get(selection.codex);
|
|
97
|
+
if (!source || selection.codex === "m365" && (!enabled || source.snapshot().state === "disabled")) throw unavailable(reason || "m365_not_ready");
|
|
98
|
+
return source;
|
|
103
99
|
}
|
|
104
100
|
const serialize = task => {
|
|
105
101
|
const next = (serial || Promise.resolve()).then(task);
|
|
106
102
|
serial = next.catch(() => {});return next;
|
|
107
103
|
};
|
|
108
104
|
async function switchSource(provider, preference) {
|
|
109
|
-
if (!
|
|
105
|
+
if (!providerRegistry.get(provider)?.codex) throw new Error("Choose a listed Codex source");
|
|
110
106
|
if (provider === "m365") {
|
|
111
107
|
if (!enabled) throw unavailable("m365_disabled");
|
|
112
108
|
const ready = await startM365();if (!ready) throw unavailable(reason || "m365_not_ready");
|
|
@@ -114,8 +110,10 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
114
110
|
if (!preference || !ids.has(preference.model) || !ids.has(preference.auto_review_model)) {
|
|
115
111
|
throw Object.assign(new Error("Choose available M365 GPT and auto-review models before switching"), { code: "m365_model_selection_required", statusCode: 400 });
|
|
116
112
|
}
|
|
117
|
-
|
|
118
|
-
|
|
113
|
+
const review = m365.models("gpt").find(model => model.id === preference.auto_review_model);
|
|
114
|
+
const effort = preference.auto_review_effort === undefined ? "low" : preference.auto_review_effort;
|
|
115
|
+
if (effort !== null && !autoReviewReasoningEfforts(review).includes(effort)) {
|
|
116
|
+
throw Object.assign(new Error("Choose an M365 review model with the selected thinking level"), { code: "m365_review_effort_unavailable", statusCode: 400 });
|
|
119
117
|
}
|
|
120
118
|
}
|
|
121
119
|
if (closed) throw unavailable("m365_runtime_closed");
|
|
@@ -131,9 +129,8 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
131
129
|
await switchSource("github");
|
|
132
130
|
updateM365Settings({ enabled: false }, options);enabled = false;
|
|
133
131
|
await gateway?.close();gateway = null;m365?.close();
|
|
134
|
-
await pending;m365 = null;
|
|
135
|
-
const
|
|
136
|
-
const result = restore(options);clients = { code: result.preserved ? "preserved" : "restored", app: result.preserved ? "preserved" : "restored" };
|
|
132
|
+
await pending;sources.delete("m365");m365 = null;
|
|
133
|
+
const result = await clientLifecycle.restore();
|
|
137
134
|
if (remove) {
|
|
138
135
|
if (result.remaining) throw Object.assign(new Error("User-modified Claude settings were preserved; M365 profile cleanup is incomplete"), { code: "m365_cleanup_preserved" });
|
|
139
136
|
const paths = m365Paths(options);
|
|
@@ -156,7 +153,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
156
153
|
selection: () => selection,
|
|
157
154
|
dashboardProviders() {
|
|
158
155
|
const state = snapshot(), service = githubClient.runtimeStatus?.() || {}, ms = state.m365;
|
|
159
|
-
|
|
156
|
+
const projections = [
|
|
160
157
|
{ id: "github", name: "GitHub Copilot", generation: dashboardGeneration(github), enabled: true, state: service.token_cached ? "ready" : "unknown",
|
|
161
158
|
auth: { state: "unknown", token_cached: service.token_cached === true, expires_in_ms: service.token_expires_in_ms ?? null },
|
|
162
159
|
models: { count: githubRegistry?.models?.data?.length ?? null, source: githubRegistry?.source || "unknown" },
|
|
@@ -168,10 +165,12 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
168
165
|
models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
|
|
169
166
|
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "m365", state: selection.codex === "m365" ? ms.state : "standby" },
|
|
170
167
|
...[["code", "Claude Code"], ["app", "Claude App"]].map(([id, name]) => ({ id: `claude_${id}`, name,
|
|
171
|
-
selected: enabled, state: clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
|
|
168
|
+
selected: enabled, state: clientLifecycle.snapshot().clients[id], gateway: gateway ? "running" : "unavailable", reason: claudeReason,
|
|
172
169
|
last_request_at: lastClients[`claude_${id}`] || null }))],
|
|
173
170
|
requests: ms.claude.requests, request_scope: "Claude Messages" },
|
|
174
171
|
];
|
|
172
|
+
return providerRegistry.list().map(definition => ({ ...projections.find(source => source.id === definition.id),
|
|
173
|
+
id: definition.id, name: definition.name, selection: { codex: definition.codex, models_required: definition.modelSelection } }));
|
|
175
174
|
},
|
|
176
175
|
async dashboardCatalog({ provider = selection.codex } = {}) {
|
|
177
176
|
if (provider === "github") return null;
|
|
@@ -211,16 +210,26 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
211
210
|
if (closed) throw unavailable("m365_runtime_closed");
|
|
212
211
|
if (input.action === "models") { await startM365();return { state: snapshot(), models: m365?.models(input.family === "claude" ? "claude" : "gpt") || [] }; }
|
|
213
212
|
if (input.action === "auto-review") {
|
|
214
|
-
if (
|
|
213
|
+
if (input.provider && input.provider !== selection.codex) throw new Error("Save the source before changing review settings");
|
|
214
|
+
if (selection.codex === "github") {
|
|
215
|
+
if (String(env.CCDX_AUTO_REVIEW_MODEL || "").trim()) throw new Error("Review model is controlled by CCDX_AUTO_REVIEW_MODEL");
|
|
216
|
+
const models = githubRegistry?.models?.data || [];
|
|
217
|
+
const model = models.find(model => model.id === input.model);
|
|
218
|
+
if (!responsesModelIdsFromCopilotModels(models).includes(input.model)
|
|
219
|
+
|| input.effort !== null && !autoReviewReasoningEfforts(model).includes(input.effort)) throw new Error("Choose an available review model and thinking level");
|
|
220
|
+
const result = writeAutoReviewModel(input.model === DEFAULT_CODEX_AUTO_REVIEW_MODEL ? "" : input.model, { ...options, reasoningEffort: input.effort });
|
|
221
|
+
return { changed: result.changed, ...snapshot() };
|
|
222
|
+
}
|
|
223
|
+
if (!m365) throw unavailable("m365_not_selected");
|
|
215
224
|
const model = m365.models("gpt").find(model => model.id === input.model);
|
|
216
|
-
if (!model || input.effort !== null && !model.
|
|
225
|
+
if (!model || input.effort !== null && !autoReviewReasoningEfforts(model).includes(input.effort)) {
|
|
217
226
|
throw Object.assign(new Error("The selected M365 review model or effort is not available"), { statusCode: 400, code: "m365_review_effort_unavailable" });
|
|
218
227
|
}
|
|
219
228
|
const preference = { ...selection.m365, auto_review_model: input.model, auto_review_effort: input.effort };
|
|
220
229
|
const changed = JSON.stringify(preference) !== JSON.stringify(selection.m365);
|
|
221
230
|
selection = writeProviderSettings("m365", preference, options);return { changed, ...snapshot() };
|
|
222
231
|
}
|
|
223
|
-
if (input.action === "switch") return switchSource(input.provider, { model: input.model, auto_review_model: input.auto_review_model });
|
|
232
|
+
if (input.action === "switch") return switchSource(input.provider, { model: input.model, auto_review_model: input.auto_review_model ?? selection.m365?.auto_review_model, ...(input.auto_review_effort !== undefined ? { auto_review_effort: input.auto_review_effort } : selection.m365?.auto_review_effort !== undefined ? { auto_review_effort: selection.m365.auto_review_effort } : {}) });
|
|
224
233
|
if (input.action === "off" || input.action === "remove") return disable(input.action === "remove");
|
|
225
234
|
if (input.action === "on") {
|
|
226
235
|
updateM365Settings({ enabled: true }, options);enabled = env.CCDX_M365 !== "0";
|
|
@@ -4,13 +4,14 @@ import { userSettingsPath } from "./user-settings.mjs";
|
|
|
4
4
|
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
5
5
|
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
6
6
|
import { withFileLockSync } from "./lock.mjs";
|
|
7
|
+
import { providerRegistry } from "./provider-registry.mjs";
|
|
7
8
|
|
|
8
9
|
export function providerSettingsPath(options = {}) {
|
|
9
10
|
return path.join(path.dirname(userSettingsPath(options)), "providers.json");
|
|
10
11
|
}
|
|
11
12
|
const invalid = () => Object.assign(new Error("Provider selection is invalid; review providers.json before starting ccdx. The existing file was preserved"), { code: "ccdx_provider_selection_invalid" });
|
|
12
13
|
function checked(value) {
|
|
13
|
-
if (!value || value.version !== 1 || !
|
|
14
|
+
if (!value || value.version !== 1 || !providerRegistry.get(value.codex)?.codex) throw invalid();
|
|
14
15
|
if (value.m365 !== undefined && (!value.m365 || typeof value.m365 !== "object"
|
|
15
16
|
|| ["model", "auto_review_model"].some(key => typeof value.m365[key] !== "string" || !/^gpt-[\w.-]{1,120}$/.test(value.m365[key])))) throw invalid();
|
|
16
17
|
if (value.codex === "m365" && !value.m365) throw invalid();
|