codex-copilot-dx 1.2.21 → 1.2.22
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 +6 -6
- package/bin/cli.mjs +77 -14
- package/docs/ARCHITECTURE.md +70 -3
- package/docs/REFERENCE.md +100 -2
- package/package.json +2 -1
- package/src/account-tools.mjs +1 -1
- package/src/adapter.mjs +17 -2
- package/src/api-catalog-refresh.mjs +1 -0
- package/src/api-secrets.mjs +28 -9
- package/src/auth.mjs +2 -0
- package/src/bounded-result-cache.mjs +12 -0
- package/src/client-gateway-keys.mjs +7 -3
- package/src/client-integration.mjs +3 -0
- package/src/connection-runtime.mjs +16 -5
- package/src/dashboard/console.js +6 -1
- package/src/dashboard/flow.js +17 -7
- package/src/dashboard/index.html +6 -0
- package/src/dashboard/language.js +24 -0
- package/src/dashboard/ui.css +16 -2
- package/src/dashboard/ui.js +4 -4
- package/src/dashboard/view-boundary.js +41 -0
- package/src/dashboard-tools.mjs +1 -0
- package/src/dashboard.mjs +26 -5
- package/src/image-mcp.mjs +3 -0
- package/src/image-references.mjs +9 -0
- package/src/local-tools.mjs +1 -1
- package/src/m365-settings.mjs +5 -0
- package/src/nightly-update.mjs +107 -0
- package/src/optional-routes.mjs +19 -5
- package/src/provider-runtime.mjs +3 -2
- package/src/providers/api.mjs +6 -4
- package/src/release-install.mjs +24 -12
- package/src/response-history.mjs +50 -0
- package/src/service-control.mjs +9 -3
- package/src/service-supervisor.mjs +168 -0
- package/src/service-worker.mjs +87 -0
- package/src/terminal-console.mjs +1 -0
- package/src/user-settings.mjs +15 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { inspectPackageUpdateEnvironment } from './package-update.mjs';
|
|
7
|
+
import { downloadRelease, createNpmReleaseFetch, protectInstallation, stableVersion, writePrivateLaunchers, privateUnixLauncher } from './release-install.mjs';
|
|
8
|
+
import { inspectWindowsCommand } from './windows-command.mjs';
|
|
9
|
+
import { isVersionGreater } from './version.mjs';
|
|
10
|
+
import { readBoundedResponseText } from './upstream-body.mjs';
|
|
11
|
+
import { readBoundedFileSync } from './bounded-file.mjs';
|
|
12
|
+
|
|
13
|
+
const run = promisify(execFile);
|
|
14
|
+
export const NIGHTLY_IDLE_MS = 10 * 60 * 1000;
|
|
15
|
+
export function nightlyWindow(now) { return now.getHours() < 4; }
|
|
16
|
+
export function nightlyDay(now) { return `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`; }
|
|
17
|
+
export function eligiblePatch(current, release, now = Date.now()) {
|
|
18
|
+
const version = stableVersion(release?.version), before = stableVersion(current), published = Date.parse(release?.published_at);
|
|
19
|
+
return Boolean(before && version && isVersionGreater(version, before) && version.split('.').slice(0,2).join('.') === before.split('.').slice(0,2).join('.')
|
|
20
|
+
&& Number.isFinite(published) && now - published >= 24 * 60 * 60 * 1000);
|
|
21
|
+
}
|
|
22
|
+
export function installedUpdateEnvironment(options = {}) {
|
|
23
|
+
const environment = inspectPackageUpdateEnvironment(options);
|
|
24
|
+
if (environment.state !== 'matched') throw new Error('installation_not_owned');
|
|
25
|
+
fs.accessSync(path.dirname(environment.target), fs.constants.W_OK);
|
|
26
|
+
const windows = (options.platform || process.platform) === 'win32';
|
|
27
|
+
const cli = windows ? path.win32.join(path.win32.dirname(environment.npm), 'node_modules/npm/bin/npm-cli.js') : fs.realpathSync(environment.npm);
|
|
28
|
+
if (!fs.statSync(cli).isFile()) throw new Error('npm_unavailable');
|
|
29
|
+
if (windows) {
|
|
30
|
+
if (inspectWindowsCommand({ packageRoot: environment.target }).status !== 'ready') throw new Error('command_not_owned');
|
|
31
|
+
} else {
|
|
32
|
+
const privateInstall = options.env?.CCDX_PRIVATE_INSTALL_PREFIX || process.env.CCDX_PRIVATE_INSTALL_PREFIX;
|
|
33
|
+
for (const name of ['ccdx','codex-copilot-dx']) {
|
|
34
|
+
const file = path.join(environment.prefix,'bin',name);
|
|
35
|
+
if (privateInstall && path.resolve(privateInstall) === path.resolve(environment.prefix)) {
|
|
36
|
+
if (readBoundedFileSync(file,{encoding:'utf8',maxBytes:16384}) !== privateUnixLauncher({...environment,name})) throw new Error('command_not_owned');
|
|
37
|
+
} else if (fs.realpathSync(file) !== fs.realpathSync(path.join(environment.target,'bin',name === 'ccdx' ? 'cli.mjs' : 'codex-copilot-dx.mjs'))) throw new Error('command_not_owned');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { ...environment, npmCli: cli };
|
|
41
|
+
}
|
|
42
|
+
export async function lookupNightlyRelease(fetchImpl, { signal } = {}) {
|
|
43
|
+
const response = await fetchImpl('https://api.github.com/repos/DaleXiao/codex-copilot-dx/releases/latest', {
|
|
44
|
+
signal: AbortSignal.any([signal || new AbortController().signal, AbortSignal.timeout(10000)]), redirect:'error',
|
|
45
|
+
headers:{Accept:'application/vnd.github+json','User-Agent':'codex-copilot-dx'},
|
|
46
|
+
});
|
|
47
|
+
if (!response.ok) { await response.body?.cancel();throw new Error('release_unavailable'); }
|
|
48
|
+
const value = JSON.parse(await readBoundedResponseText(response,{maxBytes:128*1024,signal,label:'Release metadata'}));
|
|
49
|
+
const version = stableVersion(value.tag_name);
|
|
50
|
+
if (!version || value.draft !== false || value.prerelease !== false || !Number.isFinite(Date.parse(value.published_at))) throw new Error('release_invalid');
|
|
51
|
+
return {version,published_at:value.published_at};
|
|
52
|
+
}
|
|
53
|
+
export async function verifyNightlyRuntime(target, version, { signal, brokerRequired = false } = {}) {
|
|
54
|
+
const program = `const {createRequire}=require('node:module');const r=createRequire(${JSON.stringify(path.join(target,'package.json'))});const p=r('./package.json');if(p.name!=='codex-copilot-dx'||p.version!==${JSON.stringify(version)})throw Error('version');r('sharp')({create:{width:1,height:1,channels:3,background:'white'}}).png().toBuffer().then(()=>{${brokerRequired?"if(!r('@azure/msal-node-runtime').msalNodeRuntime)throw Error('broker');":''}}).catch(()=>process.exitCode=1);`;
|
|
55
|
+
await run(process.execPath,['-e',program],{signal,timeout:30000,maxBuffer:65536,windowsHide:true});
|
|
56
|
+
const {stdout}=await run(process.execPath,[path.join(target,'bin/cli.mjs'),'version'],{signal,timeout:15000,maxBuffer:65536,windowsHide:true});
|
|
57
|
+
if (!stdout.includes(`ccdx v${version} `)) throw new Error('command_version_invalid');
|
|
58
|
+
}
|
|
59
|
+
export function nightlyRuntimeRoot({home=os.homedir()}={}) { return path.join(home,'.local/share/codex-copilot-dx/runtime'); }
|
|
60
|
+
export async function prepareNightlyRelease(release, { environment, root=nightlyRuntimeRoot(), env=process.env, signal,
|
|
61
|
+
fetchImpl=createNpmReleaseFetch(environment.npmCli,{env}), execute=run, verify=verifyNightlyRuntime }={}) {
|
|
62
|
+
const version=stableVersion(release?.version);if(!version)throw new Error('release_invalid');
|
|
63
|
+
fs.mkdirSync(root,{recursive:true,mode:0o700});const directory=fs.mkdtempSync(path.join(root,'candidate-'));
|
|
64
|
+
const target=path.join(directory,...(process.platform==='win32'?[]:['lib']),'node_modules/codex-copilot-dx');
|
|
65
|
+
const brokerRequired=fs.existsSync(path.join(environment.target,'node_modules/@azure/msal-node-runtime'));
|
|
66
|
+
try {
|
|
67
|
+
const artifact=await downloadRelease(version,{directory,fetchImpl,signal});
|
|
68
|
+
const args=['install','--global','--ignore-scripts','--no-audit','--no-fund'];
|
|
69
|
+
await execute(process.execPath,[environment.npmCli,...args,'--prefix',directory,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
|
|
70
|
+
await verify(target,version,{signal,brokerRequired});
|
|
71
|
+
return { version, target, directory,
|
|
72
|
+
async install() {
|
|
73
|
+
signal?.throwIfAborted();const transaction=protectInstallation(environment);
|
|
74
|
+
try {
|
|
75
|
+
await execute(process.execPath,[environment.npmCli,...args,'--prefix',environment.prefix,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
|
|
76
|
+
await verify(environment.target,version,{signal,brokerRequired});
|
|
77
|
+
const normalize=value=>process.platform==='win32'?path.resolve(value).toLowerCase():path.resolve(value);
|
|
78
|
+
if(env.CCDX_PRIVATE_INSTALL_PREFIX&&normalize(env.CCDX_PRIVATE_INSTALL_PREFIX)===normalize(environment.prefix))await writePrivateLaunchers(environment);
|
|
79
|
+
if (process.platform==='win32') {
|
|
80
|
+
const {inspectWindowsCommand}=await import(new URL('./windows-command.mjs',import.meta.url));
|
|
81
|
+
if(inspectWindowsCommand({packageRoot:environment.target,repair:true}).status!=='ready')throw new Error('command_setup_failed');
|
|
82
|
+
}
|
|
83
|
+
return transaction;
|
|
84
|
+
}catch(error){transaction.rollback();throw error;}
|
|
85
|
+
},
|
|
86
|
+
cleanup(){fs.rmSync(directory,{recursive:true,force:true});},
|
|
87
|
+
};
|
|
88
|
+
}catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
|
|
89
|
+
}
|
|
90
|
+
// The foreground supervisor keeps its workers on immutable package trees, so a
|
|
91
|
+
// global npm install cannot replace modules under an in-flight request.
|
|
92
|
+
export function retainCurrentRuntime(environment,{root=nightlyRuntimeRoot(),copy=fs.cpSync}={}) {
|
|
93
|
+
fs.mkdirSync(root,{recursive:true,mode:0o700});const directory=fs.mkdtempSync(path.join(root,'current-'));
|
|
94
|
+
const target=path.join(directory,'codex-copilot-dx');
|
|
95
|
+
try {copy(environment.package_root,target,{recursive:true,verbatimSymlinks:true,mode:fs.constants.COPYFILE_FICLONE});return {target,directory,cleanup(){fs.rmSync(directory,{recursive:true,force:true});}};}
|
|
96
|
+
catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function readNightlyState(file) {
|
|
100
|
+
try {
|
|
101
|
+
const value=JSON.parse(readBoundedFileSync(file,{encoding:'utf8',maxBytes:8192}));
|
|
102
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).some(key=>!['attempted_day','paused_version'].includes(key))
|
|
103
|
+
||value.attempted_day!==null&&!/^\d{4}-\d{1,2}-\d{1,2}$/.test(value.attempted_day||'')
|
|
104
|
+
||value.paused_version!==null&&!stableVersion(value.paused_version))throw new Error('invalid_update_state');
|
|
105
|
+
return value;
|
|
106
|
+
}catch(error){if(error.code==='ENOENT')return {attempted_day:null,paused_version:null};throw error;}
|
|
107
|
+
}
|
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", "/time.js", "/animation.js", "/status.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.js"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.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"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
@@ -11,29 +11,43 @@ export function isOptionalRoute(method, pathname) {
|
|
|
11
11
|
export function createOptionalRoutes(options = {}) {
|
|
12
12
|
let imageMcpHandler = options.imageMcpHandler || null;
|
|
13
13
|
let tools = null;
|
|
14
|
+
let pending = 0;
|
|
14
15
|
return {
|
|
15
16
|
dispose() { tools?.dispose(); },
|
|
17
|
+
busy: () => pending > 0 || tools?.busy?.() === true,
|
|
18
|
+
exportState() { const images = imageMcpHandler?.exportState?.() || [];return { images, bytes: (imageMcpHandler?.referenceBytes?.() || 0) + images.length * 64 }; },
|
|
19
|
+
async importState(state) {
|
|
20
|
+
if (!state || !Array.isArray(state.images)) throw new Error("Invalid optional-service handoff");
|
|
21
|
+
if (state.images.length) {
|
|
22
|
+
const { createImageMcpHandler } = await import("./image-mcp.mjs");
|
|
23
|
+
imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
|
|
24
|
+
imageMcpHandler.importState(state.images);
|
|
25
|
+
}
|
|
26
|
+
},
|
|
16
27
|
imageStats() { return imageMcpHandler?.stats?.(); },
|
|
17
28
|
async handle(req, res, pathname) {
|
|
29
|
+
pending++;
|
|
30
|
+
try {
|
|
18
31
|
if (DASHBOARD_API_PATHS.has(pathname)) {
|
|
19
32
|
const { handleDashboardApi } = await import("./dashboard-api.mjs");
|
|
20
33
|
if (["/_ccdx/ui/account", "/_ccdx/ui/checks"].includes(pathname)) {
|
|
21
34
|
const { createDashboardTools } = await import("./dashboard-tools.mjs");
|
|
22
35
|
tools ||= createDashboardTools(options.dashboardOptions);
|
|
23
36
|
}
|
|
24
|
-
return handleDashboardApi(req, res, pathname, { ...options.dashboardOptions, tools });
|
|
37
|
+
return await handleDashboardApi(req, res, pathname, { ...options.dashboardOptions, tools });
|
|
25
38
|
}
|
|
26
39
|
if ((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname)) {
|
|
27
40
|
const { serveDashboard } = await import("./dashboard.mjs");
|
|
28
|
-
return serveDashboard(req, res, pathname);
|
|
41
|
+
return await serveDashboard(req, res, pathname);
|
|
29
42
|
}
|
|
30
43
|
if (pathname === "/mcp/image") {
|
|
31
|
-
if (imageMcpHandler) return imageMcpHandler(req, res);
|
|
32
|
-
return import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
|
|
44
|
+
if (imageMcpHandler) return await imageMcpHandler(req, res);
|
|
45
|
+
return await import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
|
|
33
46
|
imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
|
|
34
47
|
return imageMcpHandler(req, res);
|
|
35
48
|
});
|
|
36
49
|
}
|
|
50
|
+
} finally { pending--; }
|
|
37
51
|
},
|
|
38
52
|
};
|
|
39
53
|
}
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -34,7 +34,7 @@ export function createProviderRuntime(options = {}) {
|
|
|
34
34
|
|
|
35
35
|
function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
|
|
36
36
|
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
|
|
37
|
-
discoverM365 = requestM365Accounts, managedClaude, onClaudeReady } = {}) {
|
|
37
|
+
discoverM365 = requestM365Accounts, managedClaude, onClaudeReady, preserveClientConfiguration } = {}) {
|
|
38
38
|
const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
|
|
39
39
|
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
40
40
|
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
@@ -56,6 +56,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
56
56
|
catch { enabled = false;reason = "m365_config_invalid"; }
|
|
57
57
|
|
|
58
58
|
async function syncClaudeClients() {
|
|
59
|
+
if (preserveClientConfiguration?.()) return;
|
|
59
60
|
if (managedClaude?.()) { await onClaudeReady?.();return; }
|
|
60
61
|
const source = m365, profile = source?.profileId();
|
|
61
62
|
if (!source || !gateway || closed || !enabled) return;
|
|
@@ -82,7 +83,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
82
83
|
const claudeModels = m365.models("claude");
|
|
83
84
|
claudeReason = !claudeModels.length ? "m365_no_claude_models" : null;
|
|
84
85
|
if (claudeModels.length && !claudeReason) try {
|
|
85
|
-
const apiKey = ensureM365GatewayKey(options);
|
|
86
|
+
const apiKey = ensureM365GatewayKey({ ...options, create: !preserveClientConfiguration?.() });
|
|
86
87
|
if (!gateway) {
|
|
87
88
|
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
88
89
|
const opened = await start({ provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
|
package/src/providers/api.mjs
CHANGED
|
@@ -13,6 +13,7 @@ import { transportErrorDetails } from "../operation-error.mjs";
|
|
|
13
13
|
import { resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
|
|
14
14
|
import { apiModelMetadata } from "./api-model-metadata.mjs";
|
|
15
15
|
import { markRequestObservation } from "../stream-performance.mjs";
|
|
16
|
+
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
16
17
|
|
|
17
18
|
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
18
19
|
export function apiCatalog(config, env = process.env) {
|
|
@@ -33,7 +34,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
33
34
|
const modelsUrl = config.base_url.replace(/\/+$/, "") + "/models", targets = [...Object.values(config.endpoints), modelsUrl];
|
|
34
35
|
if (config.endpoints.messages) targets.push(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens");
|
|
35
36
|
if (config.endpoints.responses) targets.push(config.endpoints.responses.replace(/\/+$/, "") + "/compact");
|
|
36
|
-
let network,
|
|
37
|
+
let network, closed = false;
|
|
38
|
+
const initialization = createAbortAwareSingleflight(), lifetime = new AbortController();
|
|
37
39
|
const retiring = new Set();
|
|
38
40
|
const registry = { models: { data: catalog.filter(model => model.supported_endpoints.includes(paths.responses)) }, source: "configured", generation };
|
|
39
41
|
const getNetwork = async signal => {
|
|
@@ -44,8 +46,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
44
46
|
retiring.add(previous);
|
|
45
47
|
void Promise.resolve(previous.retire()).then(() => retiring.delete(previous), () => { previous.close();retiring.delete(previous); });
|
|
46
48
|
} else previous?.close();
|
|
47
|
-
|
|
48
|
-
|
|
49
|
+
return initialization.run("network", sharedSignal => networkFactory({ targets, env, platform, signal: AbortSignal.any([sharedSignal, lifetime.signal]) })
|
|
50
|
+
.then(value => { if (closed || sharedSignal.aborted) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }), { signal });
|
|
49
51
|
};
|
|
50
52
|
const selected = (id, api) => {
|
|
51
53
|
const model = api === "messages" ? resolveClaudeModel(catalog, id) : catalog.find(model => model.id === id);
|
|
@@ -147,6 +149,6 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
147
149
|
if (!resp.ok) { await resp.body?.cancel();const code = `ccdx_api_http_${resp.status}`;return { resp: new Response(JSON.stringify({ error: { code, message: code } }), { status: resp.status, headers: { "Content-Type": "application/json" } }), reqContext: context, errorText: code, usedRetryPolicies: new Set() }; }
|
|
148
150
|
return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
|
|
149
151
|
} },
|
|
150
|
-
close() { closed = true;network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
|
|
152
|
+
close() { closed = true;lifetime.abort();network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
|
|
151
153
|
};
|
|
152
154
|
}
|
package/src/release-install.mjs
CHANGED
|
@@ -47,8 +47,8 @@ export function createNpmReleaseFetch(npmCli, { env = process.env, exec = execFi
|
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
export async function releaseBytes(url, { fetchImpl = fetch, maxBytes, timeoutMs = 60000 } = {}) {
|
|
51
|
-
const response = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.timeout(timeoutMs), headers: { "User-Agent": "codex-copilot-dx", Accept: "application/octet-stream" } });
|
|
50
|
+
export async function releaseBytes(url, { fetchImpl = fetch, maxBytes, timeoutMs = 60000, signal } = {}) {
|
|
51
|
+
const response = await fetchImpl(url, { redirect: "follow", signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs), headers: { "User-Agent": "codex-copilot-dx", Accept: "application/octet-stream" } });
|
|
52
52
|
const final = response.url && new URL(response.url);
|
|
53
53
|
if (!response.ok || final && (final.protocol !== "https:" || !["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"].includes(final.hostname))) {
|
|
54
54
|
await response.body?.cancel();throw new Error(`Release download refused (HTTP ${response.status}). Check company proxy, certificates and approved download access. No fallback was attempted.`);
|
|
@@ -85,12 +85,12 @@ export function packageMetadata(bytes) {
|
|
|
85
85
|
if (metadata?.name !== "codex-copilot-dx" || !stableVersion(metadata.version)) throw new Error("Release package identity is invalid");
|
|
86
86
|
return metadata;
|
|
87
87
|
}
|
|
88
|
-
export async function downloadRelease(tag, { fetchImpl = fetch, directory } = {}) {
|
|
88
|
+
export async function downloadRelease(tag, { fetchImpl = fetch, directory, signal } = {}) {
|
|
89
89
|
const version = stableVersion(tag);if (!version) throw new Error("A valid stable GitHub release tag is required");
|
|
90
90
|
const name = `codex-copilot-dx-${version}.tgz`, base = `${RELEASE_BASE}/v${version}`;
|
|
91
|
-
const manifest = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536 });
|
|
91
|
+
const manifest = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536, signal });
|
|
92
92
|
const expected = releaseChecksum(manifest, name);
|
|
93
|
-
const bytes = await releaseBytes(`${base}/${name}`, { fetchImpl, maxBytes: 16 * 1024 * 1024 });
|
|
93
|
+
const bytes = await releaseBytes(`${base}/${name}`, { fetchImpl, maxBytes: 16 * 1024 * 1024, signal });
|
|
94
94
|
if (createHash("sha256").update(bytes).digest("hex") !== expected) throw new Error("Release checksum mismatch; no installation was started");
|
|
95
95
|
if (packageMetadata(bytes).version !== version) throw new Error("Release package version does not match its tag");
|
|
96
96
|
const file = path.join(directory, name);fs.writeFileSync(file, bytes, { flag: "wx", mode: 0o600 });return { file, name, version };
|
|
@@ -109,19 +109,25 @@ export function protectInstallation({ target, prefix, platform = process.platfor
|
|
|
109
109
|
const entries = [target, ...["ccdx", "codex-copilot-dx"].flatMap(name => platform === "win32"
|
|
110
110
|
? [name, `${name}.cmd`, `${name}.ps1`].map(file => path.join(prefix, file)) : [path.join(prefix, "bin", name)])];
|
|
111
111
|
const saved = [];
|
|
112
|
-
const
|
|
112
|
+
const closeLock = () => { if (fd !== undefined) { const handle = fd;fd = undefined;fs.closeSync(handle); } };
|
|
113
|
+
const copyEntry = (from, to) => {
|
|
114
|
+
if (fs.lstatSync(from).isSymbolicLink()) fs.symlinkSync(fs.readlinkSync(from), to);
|
|
115
|
+
else fs.cpSync(from, to, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true });
|
|
116
|
+
};
|
|
117
|
+
const clean = () => { fs.rmSync(backup, { recursive: true, force: true });closeLock();fs.unlinkSync(lock); };
|
|
113
118
|
try {
|
|
114
119
|
entries.forEach((file, index) => {
|
|
115
120
|
let stat;try { stat = fs.lstatSync(file); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
116
121
|
if (file === target && stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error("The npm target is linked or not a regular installation; use its owning installer");
|
|
117
122
|
const copy = path.join(backup, String(index));
|
|
118
|
-
if (stat)
|
|
123
|
+
if (stat) copyEntry(file, copy);
|
|
119
124
|
saved.push({ file, copy, existed: Boolean(stat) });
|
|
120
125
|
});
|
|
121
126
|
} catch (error) { clean();throw error; }
|
|
122
127
|
let finalized = false;
|
|
123
128
|
return {
|
|
124
129
|
commit() {
|
|
130
|
+
if (finalized) return;
|
|
125
131
|
finalized = true;
|
|
126
132
|
try { clean(); }
|
|
127
133
|
catch { console.error(`CCDX was installed, but backup cleanup needs attention: ${backup}; check ${lock} before retrying.`); }
|
|
@@ -131,13 +137,15 @@ export function protectInstallation({ target, prefix, platform = process.platfor
|
|
|
131
137
|
try {
|
|
132
138
|
for (const { file, copy, existed } of saved) {
|
|
133
139
|
fs.rmSync(file, { recursive: true, force: true });
|
|
134
|
-
if (existed)
|
|
140
|
+
if (existed) copyEntry(copy, file);
|
|
135
141
|
}
|
|
136
|
-
clean();
|
|
137
142
|
} catch (error) {
|
|
138
|
-
|
|
143
|
+
closeLock();
|
|
139
144
|
throw new Error(`Restore could not finish. Previous package and commands remain at ${backup}; do not delete the install lock until restored.`, { cause: error });
|
|
140
145
|
}
|
|
146
|
+
finalized = true;
|
|
147
|
+
try { clean(); }
|
|
148
|
+
catch { console.error(`Previous CCDX was restored, but backup cleanup needs attention: ${backup}; check ${lock} before retrying.`); }
|
|
141
149
|
},
|
|
142
150
|
};
|
|
143
151
|
}
|
|
@@ -149,8 +157,12 @@ export function verifyPackageRuntime(target, version, { brokerRequired = false }
|
|
|
149
157
|
if (!output.includes(`ccdx v${version} `)) throw new Error("Installed command version could not be verified");
|
|
150
158
|
}
|
|
151
159
|
|
|
152
|
-
export
|
|
160
|
+
export function privateUnixLauncher({ prefix, target, name, node = process.execPath }) {
|
|
153
161
|
const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
162
|
+
const cli = path.join(target, "bin", name === "ccdx" ? "cli.mjs" : "codex-copilot-dx.mjs");
|
|
163
|
+
return `#!/bin/sh\nPATH=${quote(path.dirname(node))}:"$PATH"\nexport PATH\nCCDX_PRIVATE_INSTALL_PREFIX=${quote(prefix)}\nexport CCDX_PRIVATE_INSTALL_PREFIX\nif [ -z "\${npm_config_prefix:-}\${NPM_CONFIG_PREFIX:-}" ]; then npm_config_prefix=${quote(prefix)}; export npm_config_prefix; fi\nexec ${quote(node)} ${quote(cli)} "$@"\n`;
|
|
164
|
+
}
|
|
165
|
+
export async function writePrivateLaunchers({ prefix, target }) {
|
|
154
166
|
const windows = process.platform === "win32"
|
|
155
167
|
? await import(pathToFileURL(path.join(target, "src", "windows-command.mjs")).href) : null;
|
|
156
168
|
for (const name of ["ccdx", "codex-copilot-dx"]) {
|
|
@@ -159,7 +171,7 @@ export async function writePrivateLaunchers({ prefix, target }) {
|
|
|
159
171
|
fs.writeFileSync(path.join(prefix, `${name}.cmd`), windows.privateWindowsCommand({ node: process.execPath, cli, prefix }));
|
|
160
172
|
} else {
|
|
161
173
|
const file = path.join(prefix, "bin", name);fs.rmSync(file, { force: true });
|
|
162
|
-
fs.writeFileSync(file,
|
|
174
|
+
fs.writeFileSync(file, privateUnixLauncher({ prefix, target, name }), { mode: 0o755 });
|
|
163
175
|
}
|
|
164
176
|
}
|
|
165
177
|
if (windows && windows.inspectWindowsCommand({ packageRoot: target, repair: true }).status !== "ready") throw new Error("Private Windows commands could not be verified");
|
package/src/response-history.mjs
CHANGED
|
@@ -455,3 +455,53 @@ export function rememberResponseHistoryNode({
|
|
|
455
455
|
touchTree(rootId);
|
|
456
456
|
return true;
|
|
457
457
|
}
|
|
458
|
+
|
|
459
|
+
// Private process handoff only: no HTTP route or plaintext persistence.
|
|
460
|
+
export function exportResponseHistory() {
|
|
461
|
+
if (pinnedTrees.size) throw new Error('Response history is busy');
|
|
462
|
+
let bytes = totalBytes;
|
|
463
|
+
for (const [id, entry] of histories) {
|
|
464
|
+
bytes += Buffer.byteLength(id) + Buffer.byteLength(entry.parentId || '') + Buffer.byteLength(entry.rootId) + 512;
|
|
465
|
+
if (bytes > 64 * 1024 * 1024) throw new Error('state_too_large');
|
|
466
|
+
}
|
|
467
|
+
return { version: 1, bytes, entries: [...histories], roots: [...treeLru.keys()], evicted: [...evictedIds],
|
|
468
|
+
counters: { evictedEntriesTotal, lookupMisses, evictedLookupMisses } };
|
|
469
|
+
}
|
|
470
|
+
export function importResponseHistory(state) {
|
|
471
|
+
if (histories.size || pinnedTrees.size || state?.version !== 1 || !Array.isArray(state.entries) || state.entries.length > maxEntries
|
|
472
|
+
|| !Array.isArray(state.roots) || !Array.isArray(state.evicted) || state.evicted.length > 256) throw new Error('Invalid response-history handoff');
|
|
473
|
+
const restored = new Map();let bytes = 0;
|
|
474
|
+
const idOK = id => typeof id === 'string' && id.length > 0 && id.length <= 2048;
|
|
475
|
+
for (const pair of state.entries) {
|
|
476
|
+
if (!Array.isArray(pair) || pair.length !== 2 || !idOK(pair[0]) || restored.has(pair[0])) throw new Error('Invalid response-history handoff');
|
|
477
|
+
const [id, entry] = pair;
|
|
478
|
+
if (!entry || !Array.isArray(entry.inputItems) || !(entry.outputItems === undefined || Array.isArray(entry.outputItems))
|
|
479
|
+
|| !(entry.parentId === null || idOK(entry.parentId)) || !idOK(entry.rootId) || typeof entry.hasOpaque !== 'boolean'
|
|
480
|
+
|| !(entry.routeAffinity === null || typeof entry.routeAffinity === 'object')) throw new Error('Invalid response-history handoff');
|
|
481
|
+
const owned = structuredClone(entry);
|
|
482
|
+
owned.bytes = jsonByteLength(owned.routeAffinity ? [owned.inputItems, owned.outputItems, { routeAffinity: owned.routeAffinity, hasOpaque: owned.hasOpaque }] : [owned.inputItems, owned.outputItems]);
|
|
483
|
+
bytes += owned.bytes;if (bytes > maxBytes) throw new Error('Response-history handoff exceeds this version\'s limit');
|
|
484
|
+
restored.set(id, owned);
|
|
485
|
+
}
|
|
486
|
+
const roots = new Map();
|
|
487
|
+
for (const [id, entry] of restored) {
|
|
488
|
+
let at = id;const seen = new Set(), chain = [];
|
|
489
|
+
while (!roots.has(at)) {
|
|
490
|
+
if (seen.has(at)) throw new Error('Cyclic response-history handoff');
|
|
491
|
+
seen.add(at);chain.push(at);const current = restored.get(at);
|
|
492
|
+
if (!current) throw new Error('Incomplete response-history handoff');
|
|
493
|
+
if (!current.parentId) { roots.set(at, at);break; }at = current.parentId;
|
|
494
|
+
}
|
|
495
|
+
for (const item of chain) roots.set(item, roots.get(at));
|
|
496
|
+
if (entry.rootId !== roots.get(id)) throw new Error('Invalid response-history root');
|
|
497
|
+
}
|
|
498
|
+
if (state.roots.some(id => !idOK(id) || roots.get(id) !== id) || new Set(state.roots).size !== state.roots.length
|
|
499
|
+
|| state.evicted.some(id => !idOK(id) || restored.has(id))) throw new Error('Invalid response-history handoff');
|
|
500
|
+
for (const [id, entry] of restored) { histories.set(id, entry);linkChild(entry.parentId, id); }
|
|
501
|
+
for (const id of state.roots) touchTree(id);
|
|
502
|
+
for (const [id, root] of roots) if (id === root && !treeLru.has(id)) touchTree(id);
|
|
503
|
+
for (const id of state.evicted) evictedIds.add(id);
|
|
504
|
+
totalBytes = bytes;
|
|
505
|
+
const count = name => Number.isSafeInteger(state.counters?.[name]) && state.counters[name] >= 0 ? state.counters[name] : 0;
|
|
506
|
+
evictedEntriesTotal = count('evictedEntriesTotal');lookupMisses = count('lookupMisses');evictedLookupMisses = count('evictedLookupMisses');
|
|
507
|
+
}
|
package/src/service-control.mjs
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
|
|
2
|
-
writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib
|
|
2
|
+
writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
|
|
3
|
+
nightlyUpdatePreference, writeNightlyUpdatePreference } from "./user-settings.mjs";
|
|
3
4
|
import { readImageProviderConfig } from "./image-provider-config.mjs";
|
|
4
5
|
import { readPredictionSettings } from "./native-prediction-profile.mjs";
|
|
5
6
|
import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
|
|
6
7
|
import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
|
|
7
8
|
|
|
8
9
|
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
10
|
+
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
9
11
|
readImages = () => readImageProviderConfig({ env, home }), readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
10
12
|
const options = { env, home };
|
|
11
13
|
let serial = Promise.resolve();
|
|
@@ -14,7 +16,9 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
14
16
|
let imageConfigured = false, predictionConfigured = false;
|
|
15
17
|
try { imageConfigured = Boolean(readImages()); } catch {}
|
|
16
18
|
try { predictionConfigured = readPrediction().enabled === true; } catch {}
|
|
19
|
+
const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
|
|
17
20
|
return { source: "service_settings", saved, theme, color_theme,
|
|
21
|
+
nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
|
|
18
22
|
effective: {
|
|
19
23
|
terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
|
|
20
24
|
state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
|
|
@@ -27,11 +31,13 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
27
31
|
}
|
|
28
32
|
async function apply(input) {
|
|
29
33
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
30
|
-
const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"], color_theme: ["action", "theme"],
|
|
34
|
+
const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
|
|
31
35
|
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
32
36
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
33
37
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
34
|
-
if (input.action === "
|
|
38
|
+
if (input.action === "nightly_update") {
|
|
39
|
+
writeNightlyUpdatePreference(input.enabled, options);nightlyChanged(input.enabled);
|
|
40
|
+
} else if (input.action === "preference") {
|
|
35
41
|
writeServicePreference(input.key, input.value, options);
|
|
36
42
|
if (input.key === "prediction_enabled") clientIntegration?.setPredictionActive(input.value);
|
|
37
43
|
terminal?.apply?.({ ...servicePreferences(options) });
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fork } from 'node:child_process';
|
|
4
|
+
import { nightlyUpdatePreference, userSettingsPath } from './user-settings.mjs';
|
|
5
|
+
import { atomicWriteFileIfChangedSync } from './atomic-file.mjs';
|
|
6
|
+
import { createNpmReleaseFetch } from './release-install.mjs';
|
|
7
|
+
import { installedUpdateEnvironment, retainCurrentRuntime, lookupNightlyRelease, eligiblePatch, nightlyWindow, nightlyDay, NIGHTLY_IDLE_MS, prepareNightlyRelease, verifyNightlyRuntime, readNightlyState } from './nightly-update.mjs';
|
|
8
|
+
|
|
9
|
+
export function launchServiceWorker(target, { args = [], env = process.env, state, preserve = false, warm = false, sources = [], onPreference = () => {}, forkImpl = fork } = {}) {
|
|
10
|
+
const child = forkImpl(path.join(target,'bin/cli.mjs'),preserve ? [...args.filter(value=>value!=='--no-browser'),'--no-browser'] : args, {
|
|
11
|
+
env:{...env,CCDX_SUPERVISED_SERVICE:'1',...(preserve?{CCDX_AUTO_LAUNCH:'0'}:{})},stdio:['inherit','inherit','inherit','ipc'],serialization:'advanced',windowsHide:true,
|
|
12
|
+
});
|
|
13
|
+
let sequence=0,settled=false;const pending=new Map();
|
|
14
|
+
let readyResolve,readyReject;const ready=new Promise((resolve,reject)=>{readyResolve=resolve;readyReject=reject;});
|
|
15
|
+
const timer=setTimeout(()=>readyReject(new Error('startup_timeout')),90000);
|
|
16
|
+
let exitedResolve;const exited=new Promise(resolve=>{exitedResolve=resolve;});
|
|
17
|
+
const fail=error=>{if(!settled){settled=true;clearTimeout(timer);readyReject(error);}for(const entry of pending.values())entry.reject(error);pending.clear();};
|
|
18
|
+
child.on('error',()=>{fail(new Error('worker_failed'));if(!child.pid)exitedResolve({code:1,signal:null});});
|
|
19
|
+
child.on('exit',(code,signal)=>{fail(new Error('worker_exited'));exitedResolve({code,signal});});
|
|
20
|
+
child.on('message',message=>{
|
|
21
|
+
if(message?.type==='ccdx:boot'){child.send({type:'ccdx:init',protocol:1,preserve,warm,sources,state});state=undefined;}
|
|
22
|
+
else if(message?.type==='ccdx:ready'){settled=true;clearTimeout(timer);readyResolve(message.value);}
|
|
23
|
+
else if(message?.type==='ccdx:preference')onPreference(message.enabled===true);
|
|
24
|
+
else if(message?.type==='ccdx:reply'){
|
|
25
|
+
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
|
+
}
|
|
27
|
+
});
|
|
28
|
+
function call(action, value) {
|
|
29
|
+
let timer;const id=++sequence;
|
|
30
|
+
return Promise.race([new Promise((resolve,reject)=>{
|
|
31
|
+
if(!child.connected){reject(new Error('worker_disconnected'));return;}
|
|
32
|
+
pending.set(id,{resolve,reject});child.send({type:'ccdx:call',id,action,value},error=>{if(error){pending.delete(id);reject(new Error('worker_disconnected'));}});
|
|
33
|
+
}),new Promise((_,reject)=>{timer=setTimeout(()=>{pending.delete(id);reject(new Error('worker_timeout'));},20000);})]).finally(()=>clearTimeout(timer));
|
|
34
|
+
}
|
|
35
|
+
return { child,ready,exited,call,
|
|
36
|
+
status(value){if(child.connected)child.send({type:'ccdx:update-status',value},()=>{});},
|
|
37
|
+
notice(code){if(child.connected)child.send({type:'ccdx:notice',code},()=>{});},
|
|
38
|
+
async stop(){if(!child.pid||child.exitCode!==null||child.signalCode)return;child.send?.({type:'ccdx:stop'},()=>{});let timer,forced;
|
|
39
|
+
try{await Promise.race([exited,new Promise((resolve,reject)=>{timer=setTimeout(()=>{child.kill('SIGKILL');exited.then(resolve);forced=setTimeout(()=>reject(new Error('worker_stop_timeout')),5000);},15000);})]);}finally{clearTimeout(timer);clearTimeout(forced);}
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Runtime-independent transaction, exercised with real child processes by CI.
|
|
45
|
+
export async function switchServiceVersion({ worker, current, candidate, baseline, launch, stopped = () => false, cancelled = stopped, onPhase = () => {}, signal }) {
|
|
46
|
+
let transaction,next,transfer;
|
|
47
|
+
const abort = () => { void next?.stop().catch(() => {}); };
|
|
48
|
+
signal?.addEventListener('abort',abort,{once:true});
|
|
49
|
+
const matches = value => value?.fingerprint === baseline.fingerprint && Array.isArray(value.business) && value.business.length === baseline.business.length
|
|
50
|
+
&& baseline.business.every(before => {
|
|
51
|
+
const after = value.business.find(client => client.id === before.id);
|
|
52
|
+
if (!after || ['enabled','source','default_model'].some(key => before[key] !== after[key]) || JSON.stringify(before.scopes) !== JSON.stringify(after.scopes)
|
|
53
|
+
|| !before.default_unavailable && after.default_unavailable || !Array.isArray(after.models)) return false;
|
|
54
|
+
const models = new Set(after.models.map(model => JSON.stringify(model)));
|
|
55
|
+
return (before.models || []).every(model => models.has(JSON.stringify(model)));
|
|
56
|
+
});
|
|
57
|
+
const healthy = (value, promoted = false) => Object.entries(baseline.health || {}).every(([key, needed]) => !needed || key === 'prediction' && !promoted || value.health?.[key] === true);
|
|
58
|
+
try {
|
|
59
|
+
if(cancelled())throw new Error('update_cancelled');
|
|
60
|
+
const before=await worker.call('inspect');
|
|
61
|
+
if(before.busy||before.fingerprint!==baseline.fingerprint||JSON.stringify(before.business)!==JSON.stringify(baseline.business))throw new Error('service_changed');
|
|
62
|
+
const sources=[...new Set(baseline.business.flatMap(client=>client.models?.map(model=>model[0])||[]))];
|
|
63
|
+
next=launch(candidate.target,{preserve:true,warm:true,sources});
|
|
64
|
+
const ready=await next.ready;
|
|
65
|
+
if(ready.version!==candidate.version||!matches(ready))throw new Error('candidate_state_changed');
|
|
66
|
+
if(!healthy(ready))throw new Error('candidate_unavailable');
|
|
67
|
+
if(cancelled())throw new Error('update_cancelled');
|
|
68
|
+
transaction=await candidate.install();
|
|
69
|
+
if(cancelled())throw new Error('update_cancelled');
|
|
70
|
+
onPhase('switching');transfer=await worker.call('quiesce');
|
|
71
|
+
if(transfer.fingerprint!==baseline.fingerprint||JSON.stringify(transfer.business)!==JSON.stringify(baseline.business)||transfer.activity.total!==baseline.activity.total)throw new Error('service_changed');
|
|
72
|
+
if(cancelled())throw new Error('update_cancelled');
|
|
73
|
+
await next.call('import',transfer.state);
|
|
74
|
+
await worker.call('release');
|
|
75
|
+
if(cancelled())throw new Error('update_cancelled');
|
|
76
|
+
const promoted=await next.call('promote');
|
|
77
|
+
if(!matches(promoted)||!healthy(promoted,true))throw new Error('candidate_state_changed');
|
|
78
|
+
if(cancelled())throw new Error('update_cancelled');
|
|
79
|
+
await next.call('commit');transaction.commit();transaction=null;
|
|
80
|
+
let retired;
|
|
81
|
+
try { await worker.stop();current.cleanup(); } catch { retired = { worker, current };next.notice?.('old_runtime_cleanup_pending'); }
|
|
82
|
+
transfer=null;return {worker:next,current:candidate,version:candidate.version,retired};
|
|
83
|
+
}catch(error){
|
|
84
|
+
await next?.stop();
|
|
85
|
+
let failure=error;
|
|
86
|
+
try{transaction?.rollback();}catch{failure=new Error('installation_restore_failed');}
|
|
87
|
+
if(!stopped()){
|
|
88
|
+
await worker.call('resume').catch(()=>{});
|
|
89
|
+
}
|
|
90
|
+
candidate.cleanup();failure.restoredWorker=worker;throw failure;
|
|
91
|
+
} finally { signal?.removeEventListener('abort',abort); }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function createNightlyScheduler({enabled,inspect,currentVersion,lookup,prepare,apply,status=()=>{},onFailure=()=>{},now=()=>new Date(),state={attempted_day:null,paused_version:null},persist=()=>{}}) {
|
|
95
|
+
let attemptedDay=state.attempted_day,flight=null,controller,lastBusyAt=now().getTime(),lastTickAt=lastBusyAt,lastCount=null,pausedVersion=state.paused_version;
|
|
96
|
+
const save=()=>persist({attempted_day:attemptedDay,paused_version:pausedVersion});
|
|
97
|
+
const publish=(phase,extra={})=>status({phase,...extra});
|
|
98
|
+
async function tick(){
|
|
99
|
+
if(flight||!enabled())return;
|
|
100
|
+
flight=(async()=>{
|
|
101
|
+
const sample=await inspect(),date=now(),time=date.getTime();
|
|
102
|
+
if(time-lastTickAt>120000||time<lastTickAt)lastBusyAt=time;
|
|
103
|
+
lastTickAt=time;
|
|
104
|
+
const count=sample.activity.total;
|
|
105
|
+
if(sample.busy||sample.activity.active>0||lastCount!==count){lastBusyAt=time;lastCount=count;}
|
|
106
|
+
if(!nightlyWindow(date)||attemptedDay===nightlyDay(date)||time-lastBusyAt<NIGHTLY_IDLE_MS){publish('watching');return;}
|
|
107
|
+
attemptedDay=nightlyDay(date);controller=new AbortController();save();
|
|
108
|
+
try{
|
|
109
|
+
publish('checking');const release=await lookup({signal:controller.signal});
|
|
110
|
+
if(!enabled()||controller.signal.aborted)return;
|
|
111
|
+
if(!eligiblePatch(currentVersion(),release,time)||release.version===pausedVersion){publish('watching');return;}
|
|
112
|
+
publish('preparing',{version:release.version});const candidate=await prepare(release,{signal:controller.signal});
|
|
113
|
+
const latest=await inspect();
|
|
114
|
+
if(!enabled()||controller.signal.aborted||!nightlyWindow(now())||latest.busy||latest.activity.active||latest.activity.total!==count){candidate.cleanup();publish('deferred');return;}
|
|
115
|
+
try{await apply(candidate,sample,{signal:controller.signal});publish('updated',{version:release.version});}
|
|
116
|
+
catch(error){if(!controller.signal.aborted&&!['service_busy','state_too_large','service_changed','update_cancelled','candidate_unavailable'].includes(error.message)){pausedVersion=release.version;save();}throw error;}
|
|
117
|
+
}catch(error){
|
|
118
|
+
const known=['service_busy','state_too_large','service_changed','update_cancelled','candidate_state_changed','candidate_unavailable','installation_changed','installation_restore_failed','startup_timeout','worker_exited','worker_failed','worker_timeout'];
|
|
119
|
+
onFailure(known.includes(error.message)?error.message:'update_failed');
|
|
120
|
+
publish(controller.signal.aborted?'cancelled':['service_busy','state_too_large','service_changed','update_cancelled','candidate_unavailable'].includes(error.message)?'deferred':'paused');
|
|
121
|
+
}
|
|
122
|
+
finally{controller=null;}
|
|
123
|
+
})().catch(()=>publish('unavailable')).finally(()=>{controller=null;flight=null;});
|
|
124
|
+
return flight;
|
|
125
|
+
}
|
|
126
|
+
return {tick,cancel(){controller?.abort();},wait:()=>flight,async close(){controller?.abort();await flight;},get busy(){return Boolean(flight);}};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function runServiceSupervisor({args=process.argv.slice(2),env=process.env,environment=installedUpdateEnvironment({env}),
|
|
130
|
+
now=()=>new Date(),launch=launchServiceWorker,prepare=prepareNightlyRelease,lookup,processObj=process,log=message=>console.log(message),
|
|
131
|
+
retain=retainCurrentRuntime,verify=verifyNightlyRuntime,timers={setInterval,clearInterval}}={}) {
|
|
132
|
+
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(()=>{});};
|
|
136
|
+
processObj.once('SIGINT',stop);processObj.once('SIGTERM',stop);
|
|
137
|
+
try{
|
|
138
|
+
await verify(current.target,version,{brokerRequired:fs.existsSync(path.join(current.target,'node_modules/@azure/msal-node-runtime'))});
|
|
139
|
+
if(stopping)return 0;
|
|
140
|
+
worker=start(current.target);const boot=await worker.ready;
|
|
141
|
+
if(boot.reused){await worker.exited;return 0;}
|
|
142
|
+
const stateFile=path.join(path.dirname(userSettingsPath({env})),'nightly-update-state.json');let state;
|
|
143
|
+
try{state=readNightlyState(stateFile);}catch{state=null;worker.status({phase:'unavailable'});worker.notice('update_records_unreadable');}
|
|
144
|
+
let fetchImpl;
|
|
145
|
+
scheduler=createNightlyScheduler({enabled:()=>!stopping&&retired.size===0&&state!==null&&nightlyUpdatePreference({env}),now,currentVersion:()=>version,state:state||undefined,
|
|
146
|
+
persist:value=>atomicWriteFileIfChangedSync(stateFile,JSON.stringify(value)+'\n',{mode:0o600}),
|
|
147
|
+
inspect:()=>worker.call('inspect'),status:value=>worker.status(value),
|
|
148
|
+
onFailure:code=>worker.notice(code),
|
|
149
|
+
lookup:lookup|| (async options=>{fetchImpl||=createNpmReleaseFetch(environment.npmCli,{env});return lookupNightlyRelease(fetchImpl,options);}),
|
|
150
|
+
prepare:(release,options)=>prepare(release,{environment,env,...options,fetchImpl}),
|
|
151
|
+
apply:async(candidate,baseline,options)=>{
|
|
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
|
+
},
|
|
161
|
+
});
|
|
162
|
+
timer=timers.setInterval(()=>scheduler.tick(),60000);timer.unref?.();
|
|
163
|
+
// 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){await scheduler.wait();if(worker!==observed)continue;}break;}
|
|
165
|
+
const deliberate=stopping;stop();await scheduler.close();await worker.stop();return deliberate?0:1;
|
|
166
|
+
}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();}
|
|
168
|
+
}
|