codex-copilot-dx 1.2.20 → 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 +7 -7
- package/bin/cli.mjs +85 -15
- package/docs/ARCHITECTURE.md +95 -3
- package/docs/REFERENCE.md +148 -13
- package/package.json +2 -1
- package/src/access-settings.mjs +1 -0
- 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/client-model-plan.mjs +11 -4
- package/src/clients/codex-models.mjs +2 -2
- package/src/codex-api-config.mjs +94 -26
- package/src/codex-client-doctor.mjs +19 -5
- package/src/codex-config-doctor.mjs +6 -4
- package/src/config.mjs +8 -5
- package/src/connection-runtime.mjs +28 -11
- 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
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
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { serialize } from 'node:v8';
|
|
4
|
+
import { codexPaths } from './codex-paths.mjs';
|
|
5
|
+
import { claudeClientPaths } from './claude-client-config.mjs';
|
|
6
|
+
import { accessSettingsPath } from './access-settings.mjs';
|
|
7
|
+
import { userSettingsPath } from './user-settings.mjs';
|
|
8
|
+
import { readBoundedFileSync } from './bounded-file.mjs';
|
|
9
|
+
import { authProfilePaths, readAuthProfileCredentials } from './auth-profile.mjs';
|
|
10
|
+
import { m365Paths } from './m365-settings.mjs';
|
|
11
|
+
|
|
12
|
+
export const HANDOFF_MAX_BYTES = 64 * 1024 * 1024;
|
|
13
|
+
export function clientStateFingerprint(options = {}) {
|
|
14
|
+
const codex = codexPaths(options), connections = accessSettingsPath(options);
|
|
15
|
+
const github = authProfilePaths('codex', options);
|
|
16
|
+
const files = [codex.config, path.join(codex.directory, 'auth.json'), connections, userSettingsPath(options),
|
|
17
|
+
github.tokenPath, m365Paths(options).settings, m365Paths(options).gateway,
|
|
18
|
+
path.join(path.dirname(connections), 'client-gateway-keys.json'), path.join(path.dirname(connections), 'codex-gateway-owner.json'), ...Object.values(claudeClientPaths(options))];
|
|
19
|
+
const hash = createHash('sha256');
|
|
20
|
+
const credentials = readAuthProfileCredentials('codex', options);
|
|
21
|
+
hash.update(JSON.stringify([credentials.valid, credentials.identity?.id ?? null, credentials.identity?.login ?? null]));
|
|
22
|
+
for (const file of files) {
|
|
23
|
+
hash.update(file);try { hash.update(readBoundedFileSync(file, { maxBytes: 8 * 1024 * 1024 })); }
|
|
24
|
+
catch (error) { if (error.code !== 'ENOENT') throw error;hash.update('missing'); }
|
|
25
|
+
}
|
|
26
|
+
return hash.digest('hex');
|
|
27
|
+
}
|
|
28
|
+
export function serviceBusinessState(runtime) {
|
|
29
|
+
const graph = runtime.connections();
|
|
30
|
+
return graph.clients.map(client => ({ id: client.id, enabled: client.enabled, source: client.source, default_model: client.default_model ?? client.model ?? null,
|
|
31
|
+
scopes: runtime.privateScopes?.(client.id) || [],
|
|
32
|
+
models: client.model_plan?.models.map(model => [model.source, model.public_id]).sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) || [],
|
|
33
|
+
default_unavailable: client.model_plan?.default_unavailable === true }));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function createServiceWorker({ processObj = process } = {}) {
|
|
37
|
+
let preserving = false, draining = false, warming = false, handlers, stopRequested = false, updateStatus = { phase: 'watching' };
|
|
38
|
+
const boot = await new Promise((resolve, reject) => {
|
|
39
|
+
const timer = setTimeout(() => { processObj.off('message', receive);reject(new Error('Supervisor initialization timed out')); }, 15000);
|
|
40
|
+
function receive(message) {
|
|
41
|
+
if (message?.type !== 'ccdx:init' || message.protocol !== 1) return;
|
|
42
|
+
clearTimeout(timer);processObj.off('message', receive);resolve(message);
|
|
43
|
+
}
|
|
44
|
+
processObj.on('message', receive);processObj.send({ type: 'ccdx:boot', protocol: 1 });
|
|
45
|
+
});
|
|
46
|
+
preserving = boot.preserve === true;
|
|
47
|
+
warming = boot.warm === true;
|
|
48
|
+
draining = preserving;
|
|
49
|
+
const stop = () => { stopRequested = true;void handlers?.stop(); };
|
|
50
|
+
processObj.once('disconnect', stop);
|
|
51
|
+
processObj.on('message', async message => {
|
|
52
|
+
if (message?.type === 'ccdx:stop') { stop();return; }
|
|
53
|
+
if (!message || !handlers) return;
|
|
54
|
+
if (message.type === 'ccdx:notice' && /^[a-z_]{1,64}$/.test(message.code || '')) { handlers.notice?.(message.code);return; }
|
|
55
|
+
if (message.type === 'ccdx:update-status') { updateStatus = message.value;return; }
|
|
56
|
+
if (message.type !== 'ccdx:call' || !Number.isSafeInteger(message.id)) return;
|
|
57
|
+
try {
|
|
58
|
+
let value;
|
|
59
|
+
if (message.action === 'inspect') value = handlers.inspect();
|
|
60
|
+
else if (message.action === 'commit') { value = handlers.inspect();await handlers.activate?.();preserving = false;draining = false; }
|
|
61
|
+
else if (message.action === 'resume') { await handlers.resume?.();draining = false;value = handlers.inspect(); }
|
|
62
|
+
else if (message.action === 'release') { if (!draining) throw new Error('service_busy');await handlers.release();value = handlers.inspect(); }
|
|
63
|
+
else if (message.action === 'import') { if (!warming) throw new Error('service_busy');await handlers.importState(message.value);value = handlers.inspect(); }
|
|
64
|
+
else if (message.action === 'promote') { if (!warming) throw new Error('service_busy');await handlers.promote();warming = false;value = handlers.inspect(); }
|
|
65
|
+
else if (message.action === 'quiesce') {
|
|
66
|
+
if (handlers.inspect().busy) throw new Error('service_busy');
|
|
67
|
+
draining = true;
|
|
68
|
+
const state = await handlers.exportState();
|
|
69
|
+
if (state.history.bytes + state.optional.bytes + (state.providers?.bytes || 0) > HANDOFF_MAX_BYTES || serialize(state).byteLength > HANDOFF_MAX_BYTES) { draining = false;throw new Error('state_too_large'); }
|
|
70
|
+
value = { ...handlers.inspect(), state };
|
|
71
|
+
} else throw new Error('unknown_action');
|
|
72
|
+
processObj.send({ type: 'ccdx:reply', id: message.id, value });
|
|
73
|
+
} catch (error) {
|
|
74
|
+
const code = ['service_busy', 'state_too_large', 'unknown_action'].includes(error.message) ? error.message : 'handoff_unavailable';
|
|
75
|
+
processObj.send({ type: 'ccdx:reply', id: message.id, error: code });
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
return {
|
|
79
|
+
get preserving() { return preserving; }, get draining() { return draining; }, get warming() { return warming; },
|
|
80
|
+
get needsGithub() { return warming && Array.isArray(boot.sources) && boot.sources.includes('github'); },
|
|
81
|
+
takeState() { const state = boot.state;boot.state = undefined;return state; },
|
|
82
|
+
status: () => updateStatus,
|
|
83
|
+
preferenceChanged(enabled) { if (processObj.connected !== false) processObj.send({ type: 'ccdx:preference', enabled }, () => {}); },
|
|
84
|
+
reused() { processObj.send({ type: 'ccdx:ready', protocol: 1, value: { reused: true } }); },
|
|
85
|
+
async ready(value) { handlers = value;if (stopRequested) { await handlers.stop();return; }processObj.send({ type: 'ccdx:ready', protocol: 1, value: handlers.inspect() }); },
|
|
86
|
+
};
|
|
87
|
+
}
|
package/src/terminal-console.mjs
CHANGED
|
@@ -132,6 +132,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
|
|
|
132
132
|
return {
|
|
133
133
|
get enabled() { return supported() && fits && !verbose; },
|
|
134
134
|
start() { if (running) return;running = true;tick(); },
|
|
135
|
+
pause() { running = false;if (timer) timers.clearTimeout(timer);timer = null;if (lines) output.write("\n");lines = 0;previous = [];dirty = true; },
|
|
135
136
|
beginRequest() { active++;dirty = true;let done = false;return () => { if (!done) { done = true;active = Math.max(0, active - 1);dirty = true; } }; },
|
|
136
137
|
log(method, args) {
|
|
137
138
|
const message = redactDiagnosticText(format(...args));
|
package/src/user-settings.mjs
CHANGED
|
@@ -51,6 +51,10 @@ export function readUserSettings({ env = process.env, home = os.homedir(), stric
|
|
|
51
51
|
delete parsed[key];
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
|
+
if (Object.hasOwn(parsed, "nightly_updates") && typeof parsed.nightly_updates !== "boolean") {
|
|
55
|
+
if (strict) throw invalidSettings(filePath, "nightly_updates must be a boolean");
|
|
56
|
+
delete parsed.nightly_updates;
|
|
57
|
+
}
|
|
54
58
|
if (Object.hasOwn(parsed, "terminal_color_theme") && !isColorTheme(parsed.terminal_color_theme)) {
|
|
55
59
|
if (strict) throw invalidSettings(filePath, "terminal_color_theme must be green, klein or pink");
|
|
56
60
|
delete parsed.terminal_color_theme;
|
|
@@ -123,6 +127,17 @@ export function servicePreferences(options = {}) {
|
|
|
123
127
|
const settings = readUserSettings({ ...options, strict: true });
|
|
124
128
|
return serviceFlags(settings);
|
|
125
129
|
}
|
|
130
|
+
export function nightlyUpdatePreference(options = {}) {
|
|
131
|
+
return readUserSettings({ ...options, strict: true }).nightly_updates === true;
|
|
132
|
+
}
|
|
133
|
+
export function writeNightlyUpdatePreference(enabled, options = {}) {
|
|
134
|
+
if (typeof enabled !== "boolean") throw new Error("Nightly updates require a boolean");
|
|
135
|
+
return withFileLockSync(`${userSettingsPath(options)}.lock`, () => {
|
|
136
|
+
const settings = readUserSettings({ ...options, strict: true });
|
|
137
|
+
atomicWriteFileIfChangedSync(userSettingsPath(options), `${JSON.stringify({ ...settings, nightly_updates: enabled }, null, 2)}\n`, { mode: 0o600 });
|
|
138
|
+
return enabled;
|
|
139
|
+
});
|
|
140
|
+
}
|
|
126
141
|
const serviceFlags = settings => Object.fromEntries(SERVICE_FLAGS.map(key => [key, settings[key] !== false]));
|
|
127
142
|
|
|
128
143
|
// One strict read gives each status update a coherent view; no stale cache.
|