codex-copilot-dx 1.3.7 → 1.3.8
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 +7 -16
- package/bin/cli.mjs +55 -31
- package/docs/ARCHITECTURE.md +10 -0
- package/docs/REFERENCE.md +34 -5
- package/package.json +1 -1
- package/src/cli-command-spec.mjs +3 -2
- package/src/cli-image.mjs +2 -80
- package/src/cli-options.mjs +1 -1
- package/src/client-integration.mjs +11 -4
- package/src/dashboard/connections.js +4 -0
- package/src/dashboard/console.js +12 -6
- package/src/dashboard/features.js +68 -0
- package/src/dashboard/index.html +11 -9
- package/src/dashboard/language.js +56 -14
- package/src/dashboard/tools.js +4 -1
- package/src/dashboard/ui.js +1 -1
- package/src/dashboard-api.mjs +2 -2
- package/src/dashboard-tools.mjs +2 -1
- package/src/dashboard.mjs +1 -0
- package/src/doctor-compat.mjs +19 -13
- package/src/doctor.mjs +1 -1
- package/src/image-setup.mjs +110 -0
- package/src/local-tools.mjs +8 -2
- package/src/native-prediction-profile.mjs +5 -2
- package/src/native-prediction.mjs +18 -2
- package/src/optional-routes.mjs +1 -1
- package/src/prediction-control.mjs +64 -0
- package/src/prediction-operations.mjs +68 -0
- package/src/prediction-preference.mjs +75 -0
- package/src/service-control.mjs +33 -7
- package/src/service-supervisor.mjs +39 -18
- package/src/service-worker.mjs +13 -1
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
4
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
5
|
+
import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
6
|
+
import { computeImageMcpCodexConfig } from "./config.mjs";
|
|
7
|
+
import { updateImageSkill } from "./image-skill.mjs";
|
|
8
|
+
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
9
|
+
import { imageProviderConfigPath, inspectImageProvider, normalizeImageEndpoint, readImageProviderConfig, validateImageProviderConfig } from "./image-provider-config.mjs";
|
|
10
|
+
export function fileContent(filePath) {
|
|
11
|
+
try { return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(fs.readFileSync(filePath)); }
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error?.code === "ENOENT") return "";
|
|
14
|
+
if (error?.code === "ERR_ENCODING_INVALID_ENCODED_DATA") {
|
|
15
|
+
throw new Error("Codex configuration is not valid UTF-8 TOML; no configuration changes were written");
|
|
16
|
+
}
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function enableImageProvider(options) {
|
|
22
|
+
return withFileLockSync(`${options.codexPath}.ccdx.lock`, () => enableImageProviderUnlocked(options));
|
|
23
|
+
}
|
|
24
|
+
function enableImageProviderUnlocked({ providerConfig, providerPath, codexPath, codexContent, adapterPort, adapterHost }) {
|
|
25
|
+
const codex = computeImageMcpCodexConfig(codexContent, {
|
|
26
|
+
enabled: true,
|
|
27
|
+
adapterPort,
|
|
28
|
+
adapterHost,
|
|
29
|
+
});
|
|
30
|
+
const normalized = validateImageProviderConfig(providerConfig, { filePath: providerPath });
|
|
31
|
+
const skill = updateImageSkill({ enabled: true, codexPath, adapterPort, adapterHost });
|
|
32
|
+
try {
|
|
33
|
+
if (fileContent(codexPath) !== codexContent) {
|
|
34
|
+
throw new Error("Codex configuration changed during image setup; retry to preserve the newer settings");
|
|
35
|
+
}
|
|
36
|
+
atomicWriteFilePairSync(
|
|
37
|
+
codexPath,
|
|
38
|
+
codex.content,
|
|
39
|
+
providerPath,
|
|
40
|
+
`${JSON.stringify(normalized, null, 2)}\n`,
|
|
41
|
+
{ mode: 0o600, writeFile: atomicWriteFileIfChangedSync },
|
|
42
|
+
);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
skill.rollback();
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
return { codexChanged: codex.changed, config: normalized };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function disableImageProvider(options) {
|
|
51
|
+
if (!fs.existsSync(options.codexPath)) return disableImageProviderUnlocked(options);
|
|
52
|
+
return withFileLockSync(`${options.codexPath}.ccdx.lock`, () => disableImageProviderUnlocked(options));
|
|
53
|
+
}
|
|
54
|
+
function disableImageProviderUnlocked({ providerPath, codexPath, codexContent, adapterPort, adapterHost }) {
|
|
55
|
+
const codex = computeImageMcpCodexConfig(codexContent, {
|
|
56
|
+
enabled: false,
|
|
57
|
+
adapterPort,
|
|
58
|
+
adapterHost,
|
|
59
|
+
});
|
|
60
|
+
const providerExists = fs.existsSync(providerPath);
|
|
61
|
+
const skill = updateImageSkill({ enabled: false, codexPath, adapterPort, adapterHost });
|
|
62
|
+
try {
|
|
63
|
+
if (fs.existsSync(codexPath)) {
|
|
64
|
+
if (fileContent(codexPath) !== codexContent) {
|
|
65
|
+
throw new Error("Codex configuration changed during image cleanup; retry to preserve the newer settings");
|
|
66
|
+
}
|
|
67
|
+
atomicWriteFilePairSync(codexPath, codex.content, providerPath, null, {
|
|
68
|
+
mode: 0o600, writeFile: atomicWriteFileIfChangedSync,
|
|
69
|
+
});
|
|
70
|
+
} else if (providerExists) {
|
|
71
|
+
fs.unlinkSync(providerPath);
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
skill.rollback();
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
return { changed: providerExists || codex.changed || skill.changed, preservedGuidance: Boolean(skill.preserved) };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function syncEnabledImageSkill({ home = os.homedir(), env = process.env, codexPath = codexPaths({ env, home }).config, ...options } = {}) {
|
|
81
|
+
return updateImageSkill({ ...options, enabled: true, codexPath });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
export function imageSetupSummary(options = {}) {
|
|
86
|
+
const value = readImageProviderConfig({ ...options, strict: true });
|
|
87
|
+
if (!value) return { configured: false };
|
|
88
|
+
const endpoint = new URL(value.endpoint);
|
|
89
|
+
return { configured: true, endpoint: endpoint.origin + endpoint.pathname, model: value.model, protocol: value.protocol };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function configureImageSetup({ operation, endpoint, key, model }, options = {}) {
|
|
93
|
+
const { env = process.env, home = os.homedir(), adapterPort = 2026, adapterHost = "127.0.0.1", fetchImpl = fetch } = options;
|
|
94
|
+
const codexPath = codexPaths({ env, home }).config, providerPath = imageProviderConfigPath({ env, home });
|
|
95
|
+
if (operation === "remove") return { configured: false, ...disableImageProvider({ providerPath, codexPath, codexContent: fileContent(codexPath), adapterPort, adapterHost }) };
|
|
96
|
+
if (!["inspect", "setup"].includes(operation)) throw new Error("Choose image inspect, setup or remove");
|
|
97
|
+
const current = readImageProviderConfig({ env, home, strict: true });
|
|
98
|
+
const normalized = normalizeImageEndpoint(endpoint || current?.endpoint);
|
|
99
|
+
const sameOrigin = current && new URL(normalized).origin === new URL(current.endpoint).origin;
|
|
100
|
+
const apiKey = String(key || "").trim() || (sameOrigin ? current.api_key : "");
|
|
101
|
+
if (!apiKey) throw new Error("Enter an image API key for this address");
|
|
102
|
+
const inspected = await inspectImageProvider({ endpoint: normalized, apiKey, fetchImpl,
|
|
103
|
+
selectModel: ids => model || (ids.includes(current?.model) ? current.model : ids[0]) });
|
|
104
|
+
if (operation === "inspect") return { endpoint: inspected.endpoint, models: inspected.modelIds, protocol: inspected.protocol };
|
|
105
|
+
if (!model || !inspected.modelIds.includes(model)) throw new Error("Choose a listed image model");
|
|
106
|
+
enableImageProvider({ providerPath, codexPath, codexContent: fileContent(codexPath), adapterPort, adapterHost,
|
|
107
|
+
providerConfig: { endpoint: inspected.endpoint, api_key: apiKey, model, protocol: inspected.protocol } });
|
|
108
|
+
if (!servicePreferences({ env, home }).image_enabled) writeServicePreference("image_enabled", true, { env, home });
|
|
109
|
+
return imageSetupSummary({ env, home });
|
|
110
|
+
}
|
package/src/local-tools.mjs
CHANGED
|
@@ -8,10 +8,11 @@ import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
|
8
8
|
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
9
9
|
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
10
10
|
import { localPackageVersion } from "./version.mjs";
|
|
11
|
+
import { inspectAdapterCompatibility } from "./doctor-compat.mjs";
|
|
11
12
|
|
|
12
13
|
export function createLocalTools({ home = os.homedir(), env = process.env, host = "127.0.0.1", port = 2026,
|
|
13
14
|
platform = process.platform, collect = collectDoctorChecks, inspectConfig = inspectCodexConfig, repairConfig = repairCodexConfig,
|
|
14
|
-
inspectNetwork = inspectPredictionEnvironment } = {}) {
|
|
15
|
+
inspectNetwork = inspectPredictionEnvironment, inspectCompatibility = inspectAdapterCompatibility } = {}) {
|
|
15
16
|
const options = { home, env, host, port, platform };
|
|
16
17
|
let last = null, flight = null;
|
|
17
18
|
const safe = text => redactDiagnosticText(String(text || "")).split(home).join("~")
|
|
@@ -48,6 +49,11 @@ export function createLocalTools({ home = os.homedir(), env = process.env, host
|
|
|
48
49
|
const value = inspectNetwork({ env, platform });
|
|
49
50
|
return { source: "network_check", checked_at: new Date().toISOString(), summary: safe(formatPredictionEnvironment(value.summary)) };
|
|
50
51
|
}
|
|
51
|
-
|
|
52
|
+
async function compatibility() {
|
|
53
|
+
if (flight) throw new Error("A diagnostic operation is already running");
|
|
54
|
+
flight = Promise.resolve().then(async () => ({ source: "compatibility_check", checked_at: new Date().toISOString(), checks: project(await inspectCompatibility(options)) })).finally(() => { flight = null; });
|
|
55
|
+
return flight;
|
|
56
|
+
}
|
|
57
|
+
return { snapshot, check, preview, repair, network, compatibility, busy: () => Boolean(flight), report: () => ({ version: localPackageVersion(),
|
|
52
58
|
exported_at: new Date().toISOString(), scope: "local checks only; accounts and credentials omitted", ...snapshot() }) };
|
|
53
59
|
}
|
|
@@ -46,7 +46,10 @@ export function assertPredictionProxyCompatible({ env = process.env, systemProxy
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
export function assertCodexClosed({ exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
49
|
-
if (platform === "win32")
|
|
49
|
+
if (platform === "win32") {
|
|
50
|
+
try { return assertWindowsCodexClosed({ ...options, exec }); }
|
|
51
|
+
catch (error) { if (/Quit Codex/.test(error.message)) error.code = "ccdx_prediction_app_open";throw error; }
|
|
52
|
+
}
|
|
50
53
|
for (const name of ["ChatGPT", "Codex"]) {
|
|
51
54
|
try {
|
|
52
55
|
exec("/usr/bin/pgrep", ["-x", name], { stdio: "pipe", timeout: 2000 });
|
|
@@ -54,7 +57,7 @@ export function assertCodexClosed({ exec = execFileSync, platform = process.plat
|
|
|
54
57
|
if (error.status === 1) continue;
|
|
55
58
|
throw new Error("Could not check whether Codex is closed; prediction setup was skipped");
|
|
56
59
|
}
|
|
57
|
-
throw new Error("Quit Codex App before changing native prediction setup; no running App will be stopped");
|
|
60
|
+
throw Object.assign(new Error("Quit Codex App before changing native prediction setup; no running App will be stopped"), { code: "ccdx_prediction_app_open" });
|
|
58
61
|
}
|
|
59
62
|
}
|
|
60
63
|
|
|
@@ -11,6 +11,8 @@ import { updatePredictionRoute } from "./native-prediction-route.mjs";
|
|
|
11
11
|
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
12
12
|
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
13
13
|
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
14
|
+
import { predictionDisplayPreference, writePredictionDisplayPreference } from "./prediction-preference.mjs";
|
|
15
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
14
16
|
|
|
15
17
|
function certificateDirectory(settings, paths) {
|
|
16
18
|
if (!settings.credentialsDirectory) return paths.directory;
|
|
@@ -56,7 +58,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
56
58
|
return { ...result, exitCode: ["ready", "disabled"].includes(result.status) ? 0 : 1 };
|
|
57
59
|
}
|
|
58
60
|
if (action === "status") {
|
|
59
|
-
output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (
|
|
61
|
+
output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (new integrations: on)`);
|
|
60
62
|
if (settings.enabled && !servicePreferences(opts).prediction_enabled) output("Prediction configuration adaptation: paused by the WebUI preference; trust and route are retained.");
|
|
61
63
|
output("Uses the conversation's model.");
|
|
62
64
|
if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; bridge startup will recheck compatibility. Unsupported changes still require explicit setup.");
|
|
@@ -127,15 +129,19 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
127
129
|
const next = { version: 1, enabled: true, app, store: paths.store, certificateHash: certificate.hash, credentialsDirectory,
|
|
128
130
|
...(Number.isInteger(settings.bridgePort) ? { bridgePort: settings.bridgePort } : {}) };
|
|
129
131
|
let trustAdded = false;
|
|
132
|
+
const previousSettings = fs.existsSync(paths.settings) ? fs.readFileSync(paths.settings) : null;
|
|
130
133
|
try {
|
|
131
134
|
// Add the new trust before committing activation; retain the old record
|
|
132
135
|
// until the commit succeeds so a failed write cannot break an existing setup.
|
|
133
136
|
trustAdded = await updatePredictionTrust(paths.store, certificate);
|
|
134
137
|
writeSettings(next, opts);
|
|
138
|
+
writePredictionDisplayPreference(true, opts);
|
|
135
139
|
}
|
|
136
140
|
catch (error) {
|
|
137
141
|
if (trustAdded) await updatePredictionTrust(paths.store, certificate, { remove: true }).catch(() => {});
|
|
138
142
|
if (generated) fs.rmSync(credentialsDirectory, { recursive: true, force: true });
|
|
143
|
+
if (previousSettings !== null) atomicWriteFileSync(paths.settings, previousSettings);
|
|
144
|
+
else if (fs.existsSync(paths.settings)) fs.unlinkSync(paths.settings);
|
|
139
145
|
throw error;
|
|
140
146
|
}
|
|
141
147
|
if (previous && previous.hash !== certificate.hash) {
|
|
@@ -155,7 +161,17 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
155
161
|
export async function startNativePrediction({ env = process.env, platform = process.platform,
|
|
156
162
|
warning = () => {}, state, ...options } = {}) {
|
|
157
163
|
const opts = { ...options, env, platform };
|
|
158
|
-
|
|
164
|
+
if (options.autoSetup === true && ["darwin", "win32"].includes(platform)
|
|
165
|
+
&& !fs.existsSync(predictionPaths(opts).settings) && servicePreferences(opts).prediction_enabled && predictionDisplayPreference(opts).enabled) {
|
|
166
|
+
await runPredictionCommand({ ...opts, action: "on", output: warning });
|
|
167
|
+
}
|
|
168
|
+
let settings = readPredictionSettings(opts);
|
|
169
|
+
if (settings.displayPending && options.autoSetup === true) {
|
|
170
|
+
try {
|
|
171
|
+
writePredictionDisplayPreference(servicePreferences(opts).prediction_enabled, opts);
|
|
172
|
+
settings = { ...settings, displayPending: false };writePredictionSettings(settings, opts);
|
|
173
|
+
} catch (error) { if (!/Quit Codex/.test(error.message)) throw error; }
|
|
174
|
+
}
|
|
159
175
|
state?.configure(settings.enabled);
|
|
160
176
|
if (!settings.enabled) return null;
|
|
161
177
|
if (!["darwin", "win32"].includes(platform)) throw new Error("Native predictions were skipped: unsupported platform");
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/features.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
|
|
2
2
|
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections", "/_ccdx/ui/context", "/_ccdx/ui/privacy"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { readPredictionSettings, predictionPaths, writePredictionSettings } from "./native-prediction-profile.mjs";
|
|
3
|
+
import { predictionDisplayPreference } from "./prediction-preference.mjs";
|
|
4
|
+
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
5
|
+
import { openCodex } from "./launcher.mjs";
|
|
6
|
+
import { withFileLock } from "./lock.mjs";
|
|
7
|
+
import { runPredictionOperation } from "./prediction-operations.mjs";
|
|
8
|
+
|
|
9
|
+
export function predictionControlSnapshot(options = {}) {
|
|
10
|
+
const saved = readPredictionSettings(options);
|
|
11
|
+
const fresh = !fs.existsSync(predictionPaths(options).settings), display = predictionDisplayPreference(options);
|
|
12
|
+
return { configured: saved.enabled === true, enabled: servicePreferences(options).prediction_enabled && (!fresh || display.enabled),
|
|
13
|
+
default: fresh, display,
|
|
14
|
+
display_pending: saved.displayPending === true };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function controlPrediction(operation, { integration, nativeOperation = runPredictionOperation, ...options } = {}) {
|
|
18
|
+
if (!["enable", "disable", "setup", "remove", "pause", "resume", "repair", "open"].includes(operation)) throw new Error("Unknown prediction operation");
|
|
19
|
+
const settings = readPredictionSettings(options);
|
|
20
|
+
if (operation === "repair" && !settings.displayPending) return integration?.fix() || { status: "needs_service" };
|
|
21
|
+
if (operation === "open") {
|
|
22
|
+
if (!integration) throw new Error("Start CCDX before opening Codex from this control");
|
|
23
|
+
if (!settings.enabled) throw new Error("Enable predictions before opening Codex");
|
|
24
|
+
if (settings.displayPending) {
|
|
25
|
+
await nativeOperation("display", { ...options, enabled: servicePreferences(options).prediction_enabled, requireClosed: true });
|
|
26
|
+
writePredictionSettings({ ...settings, displayPending: false }, options);
|
|
27
|
+
}
|
|
28
|
+
const native = await integration.start();
|
|
29
|
+
if (!native) throw new Error("Prediction bridge is unavailable");
|
|
30
|
+
await native.prepareRoute?.();
|
|
31
|
+
return { opened: await openCodex({ predictionPacUrl: native.pacUrl, predictionApp: native.app, predictionProfile: native.profile,
|
|
32
|
+
env: { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" }, persistedPredictionRoute: false,
|
|
33
|
+
preparePredictionRoute: () => native.prepareRoute?.(), onPredictionRoute: value => integration.launched(value) }) };
|
|
34
|
+
}
|
|
35
|
+
const enabled = operation === "repair" ? servicePreferences(options).prediction_enabled : ["enable", "setup", "resume"].includes(operation);
|
|
36
|
+
let reconfigured = false;
|
|
37
|
+
if (operation === "resume" && !settings.enabled) {
|
|
38
|
+
writeServicePreference("prediction_enabled", true, options);
|
|
39
|
+
return { ...predictionControlSnapshot(options), status: "needs_setup" };
|
|
40
|
+
}
|
|
41
|
+
if (enabled && (!settings.enabled || operation === "setup")) {
|
|
42
|
+
await nativeOperation("command", { ...options, action: "on" });
|
|
43
|
+
reconfigured = true;
|
|
44
|
+
} else if (operation === "remove") {
|
|
45
|
+
integration?.setPredictionActive(false);
|
|
46
|
+
await nativeOperation("command", { ...options, action: "off" });
|
|
47
|
+
writeServicePreference("prediction_enabled", false, options);
|
|
48
|
+
}
|
|
49
|
+
const { pending } = await nativeOperation("display", { ...options, enabled });
|
|
50
|
+
writeServicePreference("prediction_enabled", enabled, options);
|
|
51
|
+
await withFileLock(`${predictionPaths(options).settings}.lock`, () => {
|
|
52
|
+
writePredictionSettings({ ...readPredictionSettings(options), displayPending: pending }, options);
|
|
53
|
+
});
|
|
54
|
+
integration?.setPredictionActive(enabled);
|
|
55
|
+
let runtime;
|
|
56
|
+
if (enabled && integration) {
|
|
57
|
+
if (reconfigured) await integration.pauseForUpdate?.();
|
|
58
|
+
await integration.start();
|
|
59
|
+
runtime = await integration.fix();
|
|
60
|
+
}
|
|
61
|
+
if (operation === "repair" && integration) return integration.fix();
|
|
62
|
+
return { ...predictionControlSnapshot(options), status: pending ? "needs_app_close" : runtime?.status || (!integration ? "next_start" : enabled ? "configured" : "disabled"),
|
|
63
|
+
...(runtime?.prediction ? { bridge: runtime.prediction.bridge } : {}) };
|
|
64
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
3
|
+
import { readPredictionSettings, writePredictionSettings, predictionPaths, assertCodexClosed, installedPredictionApp } from "./native-prediction-profile.mjs";
|
|
4
|
+
import { predictionDisplayPreference, writePredictionDisplayPreference } from "./prediction-preference.mjs";
|
|
5
|
+
import { servicePreferences } from "./user-settings.mjs";
|
|
6
|
+
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
7
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
8
|
+
|
|
9
|
+
// Native OS discovery/crypto is bounded but can block Node. Keep it out of the
|
|
10
|
+
// gateway event loop. Environment results stay private to the bridge lifecycle.
|
|
11
|
+
export async function handlePredictionOperation(operation, options = {}) {
|
|
12
|
+
if (operation === "command") {
|
|
13
|
+
const { runPredictionCommand } = await import("./native-prediction.mjs");
|
|
14
|
+
return runPredictionCommand({ ...options, output() {} });
|
|
15
|
+
}
|
|
16
|
+
if (operation === "display") {
|
|
17
|
+
try { assertCodexClosed(options); }
|
|
18
|
+
catch (error) { if (!options.requireClosed && error.code === "ccdx_prediction_app_open") return { pending: true };throw error; }
|
|
19
|
+
writePredictionDisplayPreference(options.enabled, options);return { pending: false };
|
|
20
|
+
}
|
|
21
|
+
if (operation !== "startup") throw new Error("Unknown native prediction operation");
|
|
22
|
+
let settings = readPredictionSettings(options);
|
|
23
|
+
if (options.autoSetup === true && ["darwin", "win32"].includes(options.platform || process.platform)
|
|
24
|
+
&& !fs.existsSync(predictionPaths(options).settings) && servicePreferences(options).prediction_enabled && predictionDisplayPreference(options).enabled) {
|
|
25
|
+
// Absence/incompatibility must fail before expensive trust and proxy checks.
|
|
26
|
+
const app = await installedPredictionApp(options);
|
|
27
|
+
const { runPredictionCommand } = await import("./native-prediction.mjs");
|
|
28
|
+
await runPredictionCommand({ ...options, action: "on", resolveApp: () => app, output() {} });
|
|
29
|
+
settings = readPredictionSettings(options);
|
|
30
|
+
}
|
|
31
|
+
if (settings.displayPending && options.autoSetup === true) {
|
|
32
|
+
const display = await handlePredictionOperation("display", { ...options, enabled: servicePreferences(options).prediction_enabled });
|
|
33
|
+
if (!display.pending) { settings = { ...settings, displayPending: false };writePredictionSettings(settings, options); }
|
|
34
|
+
}
|
|
35
|
+
return settings.enabled ? { configured: true, environment: inspectPredictionEnvironment(options) } : { configured: false };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function runPredictionOperation(operation, options = {}) {
|
|
39
|
+
const data = Object.fromEntries(["env", "home", "platform", "action", "enabled", "requireClosed", "autoSetup"].filter(key => options[key] !== undefined).map(key => [key, options[key]]));
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const worker = new Worker(new URL(import.meta.url), { workerData: { kind: "prediction_operation", operation, options: data }, stdout: true, stderr: true });
|
|
42
|
+
worker.stdout.resume();worker.stderr.resume();let settled = false;
|
|
43
|
+
const finish = (error, result) => { if (settled) return;settled = true;clearTimeout(timer);error ? reject(error) : resolve(result); };
|
|
44
|
+
const timer = setTimeout(() => { finish(new Error("Native prediction configuration deadline exceeded"));void worker.terminate(); }, 180000);
|
|
45
|
+
worker.once("message", message => {
|
|
46
|
+
if (message.error) finish(Object.assign(new Error(message.error.message), { code: message.error.code, predictionEnvironment: message.error.predictionEnvironment }));
|
|
47
|
+
else {
|
|
48
|
+
const plan = message.result?.environment?.network?.networkRoute;
|
|
49
|
+
if (plan) for (const key of ["http", "https"]) if (plan[key]) plan[key].url = new URL(plan[key].url);
|
|
50
|
+
finish(null, message.result);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
worker.once("error", error => finish(error));worker.once("exit", code => { if (!settled) finish(new Error(`Native prediction operation stopped (${code})`)); });
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (!isMainThread && workerData?.kind === "prediction_operation") {
|
|
58
|
+
try {
|
|
59
|
+
const result = await handlePredictionOperation(workerData.operation, workerData.options);
|
|
60
|
+
const plan = result?.environment?.network?.networkRoute;
|
|
61
|
+
// URL objects are not structured-cloneable. Credentials remain private to
|
|
62
|
+
// this IPC result, and bypass/trust data keeps its original representation.
|
|
63
|
+
if (plan) for (const key of ["http", "https"]) if (plan[key]) plan[key] = { ...plan[key], url: plan[key].url.href };
|
|
64
|
+
parentPort.postMessage({ result });
|
|
65
|
+
}
|
|
66
|
+
catch (error) { parentPort.postMessage({ error: { message: redactDiagnosticText(String(error.message)).slice(0, 600), code: error.code, predictionEnvironment: error.predictionEnvironment } }); }
|
|
67
|
+
finally { parentPort.close(); }
|
|
68
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { stringify } from "smol-toml";
|
|
4
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
5
|
+
import { parseCodexToml, codexTomlStatements, validateManagedConfigEdit } from "./config-toml.mjs";
|
|
6
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
7
|
+
import { atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
8
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
9
|
+
import { assertCodexClosed } from "./native-prediction-profile.mjs";
|
|
10
|
+
|
|
11
|
+
const KEY = "composer-predictions-enabled";
|
|
12
|
+
const ATOMS = "electron-persisted-atom-state";
|
|
13
|
+
const object = value => value && typeof value === "object" && !Array.isArray(value);
|
|
14
|
+
const read = file => {
|
|
15
|
+
try { return new TextDecoder("utf-8", { fatal: true }).decode(readBoundedFileSync(file)); }
|
|
16
|
+
catch (error) { if (error.code === "ENOENT") return "";throw error; }
|
|
17
|
+
};
|
|
18
|
+
const stateAt = text => {
|
|
19
|
+
try { return text ? JSON.parse(text) : {}; }
|
|
20
|
+
catch { throw new Error("Codex display settings are invalid; existing settings were preserved"); }
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function predictionDisplayPreference(options = {}) {
|
|
24
|
+
const { directory, config } = codexPaths(options);
|
|
25
|
+
const modern = parseCodexToml(read(config)).desktop?.[KEY];
|
|
26
|
+
if (modern !== undefined) {
|
|
27
|
+
if (typeof modern !== "boolean") throw new Error("Codex prediction display setting must be boolean");
|
|
28
|
+
return { enabled: modern, source: "desktop" };
|
|
29
|
+
}
|
|
30
|
+
const legacy = read(path.join(directory, ".codex-global-state.json"));
|
|
31
|
+
const saved = stateAt(legacy);
|
|
32
|
+
if (!object(saved) || (saved[ATOMS] !== undefined && !object(saved[ATOMS]))) throw new Error("Codex display settings are invalid; existing settings were preserved");
|
|
33
|
+
const value = modern ?? saved[ATOMS]?.[KEY];
|
|
34
|
+
if (value !== undefined && typeof value !== "boolean") throw new Error("Codex prediction display setting must be boolean");
|
|
35
|
+
return { enabled: value !== false, source: modern !== undefined ? "desktop" : value !== undefined ? "legacy" : "default" };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Codex moved this setting from persisted atoms to desktop TOML. Update both
|
|
39
|
+
// representations while closed; the App owns migration and its live state.
|
|
40
|
+
export function writePredictionDisplayPreference(enabled, options = {}) {
|
|
41
|
+
if (typeof enabled !== "boolean") throw new Error("Prediction display requires a boolean");
|
|
42
|
+
const { directory, config } = codexPaths(options);
|
|
43
|
+
const legacyFile = path.join(directory, ".codex-global-state.json");
|
|
44
|
+
return withFileLockSync(`${config}.ccdx.lock`, () => {
|
|
45
|
+
assertCodexClosed(options);
|
|
46
|
+
const content = read(config), legacy = read(legacyFile), before = parseCodexToml(content);
|
|
47
|
+
const saved = stateAt(legacy);
|
|
48
|
+
if (!object(saved) || (saved[ATOMS] !== undefined && !object(saved[ATOMS]))) throw new Error("Codex display settings are invalid; existing settings were preserved");
|
|
49
|
+
if (before.desktop !== undefined && !object(before.desktop)) throw new Error("Codex desktop settings are invalid; existing settings were preserved");
|
|
50
|
+
const statements = codexTomlStatements(content);
|
|
51
|
+
const exact = statements.find(item => item.kind === "value" && item.keys.length === 2 && item.keys[0] === "desktop" && item.keys[1] === KEY);
|
|
52
|
+
let next = content;
|
|
53
|
+
if (exact) next = content.slice(0, exact.valueStart) + enabled + content.slice(exact.valueEnd);
|
|
54
|
+
else {
|
|
55
|
+
const inline = statements.find(item => item.kind === "value" && item.keys.length === 1 && item.keys[0] === "desktop");
|
|
56
|
+
const table = statements.find(item => item.kind === "table" && item.keys.length === 1 && item.keys[0] === "desktop");
|
|
57
|
+
if (inline) next = content.slice(0, inline.start) + content.slice(inline.end) + "\n" + stringify({ desktop: { ...before.desktop, [KEY]: enabled } });
|
|
58
|
+
else if (table) next = content.slice(0, table.end) + `\n${KEY} = ${enabled}` + content.slice(table.end);
|
|
59
|
+
else {
|
|
60
|
+
const first = statements.find(item => item.kind === "table")?.start ?? content.length;
|
|
61
|
+
next = content.slice(0, first) + `\ndesktop.${KEY} = ${enabled}\n` + content.slice(first);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
validateManagedConfigEdit(before, next, [["desktop", KEY]]);
|
|
65
|
+
if (parseCodexToml(next).desktop?.[KEY] !== enabled) throw new Error("Prediction display could not be updated; existing settings were preserved");
|
|
66
|
+
saved[ATOMS] = { ...saved[ATOMS], [KEY]: enabled };
|
|
67
|
+
assertCodexClosed(options);
|
|
68
|
+
if (read(config) !== content || read(legacyFile) !== legacy) throw new Error("Codex settings changed; retry after quitting the App");
|
|
69
|
+
const data = JSON.stringify(saved) + "\n";
|
|
70
|
+
if (next === content && data === legacy) return { enabled, changed: false };
|
|
71
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
72
|
+
atomicWriteFilePairSync(config, next, legacyFile, data);
|
|
73
|
+
return { enabled, changed: true };
|
|
74
|
+
});
|
|
75
|
+
}
|
package/src/service-control.mjs
CHANGED
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
|
|
2
2
|
writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
|
|
3
|
-
nightlyUpdatePreference, writeNightlyUpdatePreference } from "./user-settings.mjs";
|
|
3
|
+
nightlyUpdatePreference, writeNightlyUpdatePreference, decodedBodyLimitPreference, writeDecodedBodyLimitMib } from "./user-settings.mjs";
|
|
4
4
|
import { readImageProviderConfig } from "./image-provider-config.mjs";
|
|
5
5
|
import { readPredictionSettings } from "./native-prediction-profile.mjs";
|
|
6
6
|
import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
|
|
7
7
|
import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
|
|
8
8
|
import { settingsPreferencesSnapshot, writeSettingsPreferences } from "./settings-preferences.mjs";
|
|
9
|
+
import { predictionControlSnapshot, controlPrediction } from "./prediction-control.mjs";
|
|
10
|
+
import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
|
|
9
11
|
|
|
10
12
|
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
11
13
|
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
14
|
+
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup,
|
|
15
|
+
adapterPort = 2026, adapterHost = "127.0.0.1",
|
|
12
16
|
readImages = () => readImageProviderConfig({ env, home }), readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
13
17
|
const options = { env, home };
|
|
14
|
-
let serial = Promise.resolve();
|
|
18
|
+
let serial = Promise.resolve(), lastOperation = null, pending = 0;
|
|
19
|
+
const featureSnapshot = read => { try { return read(options); } catch { return { status: "unavailable" }; } };
|
|
15
20
|
function snapshot() {
|
|
16
21
|
const { saved, theme, color_theme, historyLimit } = serviceSettingsSnapshot(options), prediction = clientIntegration?.snapshot().prediction;
|
|
17
22
|
let imageConfigured = false, predictionConfigured = false;
|
|
@@ -19,6 +24,8 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
19
24
|
try { predictionConfigured = readPrediction().enabled === true; } catch {}
|
|
20
25
|
const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
|
|
21
26
|
return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: providerRuntime?.privacy?.snapshot(),
|
|
27
|
+
features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: featureSnapshot(imageSetupSummary) },
|
|
28
|
+
decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
|
|
22
29
|
nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
|
|
23
30
|
effective: {
|
|
24
31
|
terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
|
|
@@ -34,10 +41,26 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
34
41
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
35
42
|
const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
|
|
36
43
|
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
44
|
+
prediction: ["action", "operation"], image: ["action", "operation", "endpoint", "key", "model"],
|
|
45
|
+
update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
|
|
37
46
|
preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
|
|
38
47
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
39
48
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
40
|
-
|
|
49
|
+
lastOperation = null;
|
|
50
|
+
if (input.action === "prediction") {
|
|
51
|
+
lastOperation = { feature: "prediction", result: await predictionControl(input.operation, { ...options, integration: clientIntegration }) };
|
|
52
|
+
} else if (input.action === "image") {
|
|
53
|
+
for (const [key, limit] of [["endpoint", 2048], ["key", 8192], ["model", 200]]) if (input[key] !== undefined && (typeof input[key] !== "string" || input[key].length > limit)) throw new Error("Invalid image setup input");
|
|
54
|
+
if (["pause", "resume"].includes(input.operation)) writeServicePreference("image_enabled", input.operation === "resume", options);
|
|
55
|
+
else lastOperation = { feature: "image", result: await imageControl(input, { ...options, adapterPort, adapterHost }) };
|
|
56
|
+
} else if (input.action === "update") {
|
|
57
|
+
if (input.confirmed !== true) throw new Error("Confirm installation and the idle service switch");
|
|
58
|
+
if (!manualUpdate) throw new Error("This launch cannot update itself; use the installer or start CCDX from its installed command");
|
|
59
|
+
lastOperation = { feature: "update", result: await manualUpdate() };
|
|
60
|
+
} else if (input.action === "decoded_limit") {
|
|
61
|
+
if (decodedBodyLimitPreference(options).source === "environment") throw new Error("Request limit is controlled by the launch environment");
|
|
62
|
+
writeDecodedBodyLimitMib(input.mib, options);
|
|
63
|
+
} else if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
|
|
41
64
|
const before = nightlyUpdatePreference(options);
|
|
42
65
|
writeSettingsPreferences(input, options);
|
|
43
66
|
if (input.action !== "preferences" || Object.keys(input.values || {}).some(key => key.startsWith("privacy_"))) providerRuntime?.privacy?.settingsChanged();
|
|
@@ -47,8 +70,8 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
47
70
|
} else if (input.action === "nightly_update") {
|
|
48
71
|
writeNightlyUpdatePreference(input.enabled, options);nightlyChanged(input.enabled);
|
|
49
72
|
} else if (input.action === "preference") {
|
|
50
|
-
|
|
51
|
-
|
|
73
|
+
if (input.key === "prediction_enabled") await predictionControl(input.value ? "enable" : "disable", { ...options, integration: clientIntegration });
|
|
74
|
+
else writeServicePreference(input.key, input.value, options);
|
|
52
75
|
terminal?.apply?.({ ...servicePreferences(options) });
|
|
53
76
|
} else if (input.action === "color_theme") {
|
|
54
77
|
writeTerminalColorTheme(input.theme, options);terminal?.apply?.({ color_theme: input.theme });
|
|
@@ -57,7 +80,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
57
80
|
writeTerminalAnimationTheme(input.theme, options);terminal?.apply?.({ theme: input.theme });
|
|
58
81
|
} else if (input.action === "prediction_fix") {
|
|
59
82
|
if (!clientIntegration) throw new Error("Prediction integration is unavailable");
|
|
60
|
-
await clientIntegration
|
|
83
|
+
await predictionControl("repair", { ...options, integration: clientIntegration });
|
|
61
84
|
} else if (input.action === "history_limit") {
|
|
62
85
|
if (responseHistoryLimitPreference(options).source === "environment") throw new Error("History limit is controlled by CCDX_RESPONSE_HISTORY_MAX_BYTES");
|
|
63
86
|
if (!Number.isSafeInteger(input.mib)) throw new Error("History limit must be an integer MiB value");
|
|
@@ -74,5 +97,8 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
74
97
|
}
|
|
75
98
|
return snapshot();
|
|
76
99
|
}
|
|
77
|
-
return { snapshot,
|
|
100
|
+
return { snapshot, busy: () => pending > 0, action(input) {
|
|
101
|
+
const counted = input?.action !== "update";if (counted) pending++;
|
|
102
|
+
const operation = serial.then(() => apply(input)).finally(() => { if (counted) pending--; });serial = operation.catch(() => {});return operation;
|
|
103
|
+
} };
|
|
78
104
|
}
|
|
@@ -4,9 +4,10 @@ import { fork } from 'node:child_process';
|
|
|
4
4
|
import { nightlyUpdatePreference, userSettingsPath } from './user-settings.mjs';
|
|
5
5
|
import { atomicWriteFileIfChangedSync } from './atomic-file.mjs';
|
|
6
6
|
import { createNpmReleaseFetch } from './release-install.mjs';
|
|
7
|
+
import { isVersionGreater } from './version.mjs';
|
|
7
8
|
import { installedUpdateEnvironment, retainCurrentRuntime, lookupNightlyRelease, eligiblePatch, nightlyWindow, nightlyDay, NIGHTLY_IDLE_MS, prepareNightlyRelease, verifyNightlyRuntime, readNightlyState } from './nightly-update.mjs';
|
|
8
9
|
|
|
9
|
-
export function launchServiceWorker(target, { args = [], env = process.env, state, preserve = false, warm = false, sources = [], onPreference = () => {}, forkImpl = fork } = {}) {
|
|
10
|
+
export function launchServiceWorker(target, { args = [], env = process.env, state, preserve = false, warm = false, sources = [], onPreference = () => {}, onManualUpdate = () => {}, forkImpl = fork } = {}) {
|
|
10
11
|
const child = forkImpl(path.join(target,'bin/cli.mjs'),preserve ? [...args.filter(value=>value!=='--no-browser'),'--no-browser'] : args, {
|
|
11
12
|
env:{...env,CCDX_SUPERVISED_SERVICE:'1',...(preserve?{CCDX_AUTO_LAUNCH:'0'}:{})},stdio:['inherit','inherit','inherit','ipc'],serialization:'advanced',windowsHide:true,
|
|
12
13
|
});
|
|
@@ -21,6 +22,7 @@ export function launchServiceWorker(target, { args = [], env = process.env, stat
|
|
|
21
22
|
if(message?.type==='ccdx:boot'){child.send({type:'ccdx:init',protocol:1,preserve,warm,sources,state});state=undefined;}
|
|
22
23
|
else if(message?.type==='ccdx:ready'){settled=true;clearTimeout(timer);readyResolve(message.value);}
|
|
23
24
|
else if(message?.type==='ccdx:preference')onPreference(message.enabled===true);
|
|
25
|
+
else if(message?.type==='ccdx:manual-update')onManualUpdate();
|
|
24
26
|
else if(message?.type==='ccdx:reply'){
|
|
25
27
|
const entry=pending.get(message.id);if(!entry)return;pending.delete(message.id);message.error?entry.reject(new Error(message.error)):entry.resolve(message.value);
|
|
26
28
|
}
|
|
@@ -130,9 +132,9 @@ export async function runServiceSupervisor({args=process.argv.slice(2),env=proce
|
|
|
130
132
|
now=()=>new Date(),launch=launchServiceWorker,prepare=prepareNightlyRelease,lookup,processObj=process,log=message=>console.log(message),
|
|
131
133
|
retain=retainCurrentRuntime,verify=verifyNightlyRuntime,timers={setInterval,clearInterval}}={}) {
|
|
132
134
|
let current=retain(environment),version=JSON.parse(fs.readFileSync(path.join(current.target,'package.json'))).version;
|
|
133
|
-
let stopping=false,worker,pendingWorker,timer,scheduler;const retired=new Set();
|
|
134
|
-
const start=(target,options={})=>pendingWorker=launch(target,{args,env,...options,onPreference:enabled=>{if(!enabled)scheduler?.cancel();}});
|
|
135
|
-
const stop=()=>{if(stopping)return;stopping=true;timers.clearInterval(timer);scheduler?.cancel();void worker?.stop().catch(()=>{});if(pendingWorker!==worker)void pendingWorker?.stop().catch(()=>{});for(const item of retired)void item.worker.stop().catch(()=>{});};
|
|
135
|
+
let stopping=false,worker,pendingWorker,timer,scheduler,manualFlight=null,manualController=null,requestManualUpdate;const retired=new Set();
|
|
136
|
+
const start=(target,options={})=>pendingWorker=launch(target,{args,env,...options,onPreference:enabled=>{if(!enabled)scheduler?.cancel();},onManualUpdate:()=>{void requestManualUpdate?.();}});
|
|
137
|
+
const stop=()=>{if(stopping)return;stopping=true;timers.clearInterval(timer);scheduler?.cancel();manualController?.abort();void worker?.stop().catch(()=>{});if(pendingWorker!==worker)void pendingWorker?.stop().catch(()=>{});for(const item of retired)void item.worker.stop().catch(()=>{});};
|
|
136
138
|
processObj.once('SIGINT',stop);processObj.once('SIGTERM',stop);
|
|
137
139
|
try{
|
|
138
140
|
await verify(current.target,version,{brokerRequired:fs.existsSync(path.join(current.target,'node_modules/@azure/msal-node-runtime'))});
|
|
@@ -142,27 +144,46 @@ export async function runServiceSupervisor({args=process.argv.slice(2),env=proce
|
|
|
142
144
|
const stateFile=path.join(path.dirname(userSettingsPath({env})),'nightly-update-state.json');let state;
|
|
143
145
|
try{state=readNightlyState(stateFile);}catch{state=null;worker.status({phase:'unavailable'});worker.notice('update_records_unreadable');}
|
|
144
146
|
let fetchImpl;
|
|
145
|
-
|
|
147
|
+
const readRelease=lookup|| (async options=>{fetchImpl||=createNpmReleaseFetch(environment.npmCli,{env});return lookupNightlyRelease(fetchImpl,options);});
|
|
148
|
+
async function installCandidate(candidate,baseline,options,manual=false) {
|
|
149
|
+
try {
|
|
150
|
+
if(JSON.parse(fs.readFileSync(path.join(environment.target,'package.json'))).version!==version){candidate.cleanup();throw new Error('installation_changed');}
|
|
151
|
+
const result=await switchServiceVersion({worker,current,candidate,baseline,launch:start,stopped:()=>stopping,
|
|
152
|
+
cancelled:()=>stopping||!manual&&(!nightlyUpdatePreference({env})||!nightlyWindow(now())),onPhase:phase=>worker.status({phase,version:candidate.version}),signal:options.signal});
|
|
153
|
+
worker=result.worker;current=result.current;version=result.version;
|
|
154
|
+
if(result.retired)retired.add(result.retired);
|
|
155
|
+
}catch(error){if(error.restoredWorker)worker=error.restoredWorker;throw error;}
|
|
156
|
+
}
|
|
157
|
+
async function manualUpdate() {
|
|
158
|
+
if(stopping||manualFlight)return;
|
|
159
|
+
scheduler?.cancel();
|
|
160
|
+
manualController=new AbortController();
|
|
161
|
+
manualFlight=(async()=>{
|
|
162
|
+
await scheduler?.wait();worker.status({phase:'checking',manual:true});
|
|
163
|
+
const baseline=await worker.call('inspect');
|
|
164
|
+
if(baseline.busy||baseline.activity.active)throw new Error('service_busy');
|
|
165
|
+
const release=await readRelease({currentVersion:version,signal:manualController.signal});
|
|
166
|
+
if(!release||!isVersionGreater(release.version,version)){worker.status({phase:'current',manual:true});return;}
|
|
167
|
+
worker.status({phase:'preparing',version:release.version,manual:true});
|
|
168
|
+
const candidate=await prepare(release,{environment,env,fetchImpl,signal:manualController.signal});
|
|
169
|
+
try {await installCandidate(candidate,baseline,{signal:manualController.signal},true);worker.status({phase:'updated',version,manual:true});}
|
|
170
|
+
catch(error){candidate.cleanup();throw error;}
|
|
171
|
+
})().catch(error=>{worker.status({phase:error.message==='service_busy'?'deferred':'failed',manual:true});worker.notice('manual_update_failed');}).finally(()=>{manualFlight=null;manualController=null;});
|
|
172
|
+
await manualFlight;
|
|
173
|
+
}
|
|
174
|
+
requestManualUpdate=manualUpdate;
|
|
175
|
+
scheduler=createNightlyScheduler({enabled:()=>!stopping&&!manualFlight&&retired.size===0&&state!==null&&nightlyUpdatePreference({env}),now,currentVersion:()=>version,state:state||undefined,
|
|
146
176
|
persist:value=>atomicWriteFileIfChangedSync(stateFile,JSON.stringify(value)+'\n',{mode:0o600}),
|
|
147
177
|
inspect:()=>worker.call('inspect'),status:value=>worker.status(value),
|
|
148
178
|
onFailure:code=>worker.notice(code),
|
|
149
|
-
lookup:
|
|
179
|
+
lookup:readRelease,
|
|
150
180
|
prepare:(release,options)=>prepare(release,{environment,env,...options,fetchImpl}),
|
|
151
|
-
apply:
|
|
152
|
-
try{
|
|
153
|
-
const globalVersion=JSON.parse(fs.readFileSync(path.join(environment.target,'package.json'))).version;
|
|
154
|
-
if(globalVersion!==version){candidate.cleanup();throw new Error('installation_changed');}
|
|
155
|
-
const result=await switchServiceVersion({worker,current,candidate,baseline,launch:start,stopped:()=>stopping,
|
|
156
|
-
cancelled:()=>stopping||!nightlyUpdatePreference({env})||!nightlyWindow(now()),onPhase:phase=>worker.status({phase,version:candidate.version}),signal:options.signal});
|
|
157
|
-
worker=result.worker;current=result.current;version=result.version;
|
|
158
|
-
if(result.retired)retired.add(result.retired);
|
|
159
|
-
}catch(error){if(error.restoredWorker)worker=error.restoredWorker;throw error;}
|
|
160
|
-
},
|
|
181
|
+
apply:installCandidate,
|
|
161
182
|
});
|
|
162
183
|
timer=timers.setInterval(()=>scheduler.tick(),60000);timer.unref?.();
|
|
163
184
|
// An unexpected worker exit is reported once. A deliberate Ctrl+C never restarts it.
|
|
164
|
-
while(!stopping){const observed=worker;await observed.exited;if(scheduler.busy)
|
|
185
|
+
while(!stopping){const observed=worker;await observed.exited;if(manualFlight)await manualFlight;if(scheduler.busy)await scheduler.wait();if(worker!==observed)continue;break;}
|
|
165
186
|
const deliberate=stopping;stop();await scheduler.close();await worker.stop();return deliberate?0:1;
|
|
166
187
|
}catch(error){if(!worker&&!stopping)throw error;if(!stopping)log('[WARN] Nightly supervisor could not continue; run ccdx again.');const deliberate=stopping;stop();return deliberate?0:1;}
|
|
167
|
-
finally{timers.clearInterval(timer);processObj.off('SIGINT',stop);processObj.off('SIGTERM',stop);if(stopping)await worker?.stop();for(const item of retired){try{await item.worker.stop();item.current.cleanup();}catch{}}current.cleanup();}
|
|
188
|
+
finally{timers.clearInterval(timer);processObj.off('SIGINT',stop);processObj.off('SIGTERM',stop);if(stopping)await worker?.stop();if(manualFlight)await manualFlight;for(const item of retired){try{await item.worker.stop();item.current.cleanup();}catch{}}current.cleanup();}
|
|
168
189
|
}
|