codex-copilot-dx 1.3.7 → 1.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -16
- package/bin/cli.mjs +55 -31
- package/docs/ARCHITECTURE.md +25 -1
- package/docs/REFERENCE.md +45 -10
- package/package.json +3 -3
- package/src/claude-gateway.mjs +21 -18
- package/src/cli-command-spec.mjs +3 -2
- package/src/cli-image.mjs +2 -80
- package/src/cli-options.mjs +1 -1
- package/src/client-integration.mjs +11 -4
- package/src/connection-runtime.mjs +1 -0
- package/src/dashboard/connections.js +5 -1
- package/src/dashboard/console.js +12 -6
- package/src/dashboard/features.js +73 -0
- package/src/dashboard/index.html +15 -14
- package/src/dashboard/language.js +60 -16
- package/src/dashboard/tools.js +4 -1
- package/src/dashboard/ui.js +1 -1
- package/src/dashboard/usage.js +2 -2
- package/src/dashboard-api.mjs +7 -2
- package/src/dashboard-tools.mjs +2 -1
- package/src/dashboard.mjs +1 -0
- package/src/doctor-compat.mjs +19 -13
- package/src/doctor.mjs +1 -1
- package/src/image-setup.mjs +110 -0
- package/src/local-privacy.mjs +15 -11
- package/src/local-tools.mjs +8 -2
- package/src/messages-history-transfer.mjs +12 -2
- package/src/messages-system-policy.mjs +20 -0
- package/src/model-capabilities.mjs +2 -2
- package/src/native-prediction-profile.mjs +5 -2
- package/src/native-prediction.mjs +18 -2
- package/src/optional-routes.mjs +1 -1
- package/src/prediction-control.mjs +64 -0
- package/src/prediction-operations.mjs +68 -0
- package/src/prediction-preference.mjs +75 -0
- package/src/privacy-model.mjs +35 -21
- package/src/privacy-transform.mjs +35 -4
- package/src/providers/m365.mjs +5 -2
- package/src/service-control.mjs +33 -7
- package/src/service-supervisor.mjs +39 -18
- package/src/service-worker.mjs +13 -1
- package/src/terminal-console.mjs +2 -2
- package/src/usage-analytics.mjs +6 -1
- package/src/usage-store.mjs +21 -8
- package/src/usage.mjs +18 -5
package/src/local-tools.mjs
CHANGED
|
@@ -8,10 +8,11 @@ import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
|
8
8
|
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
9
9
|
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
10
10
|
import { localPackageVersion } from "./version.mjs";
|
|
11
|
+
import { inspectAdapterCompatibility } from "./doctor-compat.mjs";
|
|
11
12
|
|
|
12
13
|
export function createLocalTools({ home = os.homedir(), env = process.env, host = "127.0.0.1", port = 2026,
|
|
13
14
|
platform = process.platform, collect = collectDoctorChecks, inspectConfig = inspectCodexConfig, repairConfig = repairCodexConfig,
|
|
14
|
-
inspectNetwork = inspectPredictionEnvironment } = {}) {
|
|
15
|
+
inspectNetwork = inspectPredictionEnvironment, inspectCompatibility = inspectAdapterCompatibility } = {}) {
|
|
15
16
|
const options = { home, env, host, port, platform };
|
|
16
17
|
let last = null, flight = null;
|
|
17
18
|
const safe = text => redactDiagnosticText(String(text || "")).split(home).join("~")
|
|
@@ -48,6 +49,11 @@ export function createLocalTools({ home = os.homedir(), env = process.env, host
|
|
|
48
49
|
const value = inspectNetwork({ env, platform });
|
|
49
50
|
return { source: "network_check", checked_at: new Date().toISOString(), summary: safe(formatPredictionEnvironment(value.summary)) };
|
|
50
51
|
}
|
|
51
|
-
|
|
52
|
+
async function compatibility() {
|
|
53
|
+
if (flight) throw new Error("A diagnostic operation is already running");
|
|
54
|
+
flight = Promise.resolve().then(async () => ({ source: "compatibility_check", checked_at: new Date().toISOString(), checks: project(await inspectCompatibility(options)) })).finally(() => { flight = null; });
|
|
55
|
+
return flight;
|
|
56
|
+
}
|
|
57
|
+
return { snapshot, check, preview, repair, network, compatibility, busy: () => Boolean(flight), report: () => ({ version: localPackageVersion(),
|
|
52
58
|
exported_at: new Date().toISOString(), scope: "local checks only; accounts and credentials omitted", ...snapshot() }) };
|
|
53
59
|
}
|
|
@@ -11,6 +11,7 @@ const digest = value => createHash("sha256").update(JSON.stringify(value, (key,
|
|
|
11
11
|
const semanticDigest = value => createHash("sha256").update(JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry)
|
|
12
12
|
? Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]])) : entry)).digest("hex");
|
|
13
13
|
const parts = message => Array.isArray(message?.content) ? message.content : [];
|
|
14
|
+
const historyMessages = messages => messages.filter(message => message?.role !== "system");
|
|
14
15
|
const thinking = part => ["thinking", "redacted_thinking", "reasoning"].includes(part?.type);
|
|
15
16
|
const history = body => body.messages.some(message => message?.role === "assistant" || parts(message).some(part => part?.type === "tool_result"))
|
|
16
17
|
|| body.messages.filter(message => message?.role === "user").length > 1;
|
|
@@ -44,21 +45,29 @@ function canonicalBlock(block) {
|
|
|
44
45
|
function canonicalItems(messages) {
|
|
45
46
|
const out = [];
|
|
46
47
|
for (const message of messages) {
|
|
47
|
-
if (!message || typeof message !== "object" || !["user", "assistant"].includes(message.role)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
|
|
48
|
+
if (!message || typeof message !== "object" || !["user", "assistant", "system"].includes(message.role)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
|
|
48
49
|
const { content, cache_control, ...fields } = message;
|
|
49
50
|
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
|
|
50
51
|
if (!Array.isArray(blocks)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
|
|
52
|
+
// Instructions have the same ownership semantics as top-level system text.
|
|
53
|
+
// Keep them on the wire without shifting an existing signed tool prefix.
|
|
54
|
+
if (message.role === "system") {
|
|
55
|
+
if (!blocks.every(block => block?.type === "text" && typeof block.text === "string")) fail("ccdx_history_transfer_content_unsupported", "Inline system instructions must contain text.");
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
51
58
|
for (const block of blocks.length ? blocks : [null]) out.push({ ...fields, block: canonicalBlock(block) });
|
|
52
59
|
}
|
|
53
60
|
return out;
|
|
54
61
|
}
|
|
55
62
|
function checkpoint(owner, messages) {
|
|
63
|
+
messages = historyMessages(messages);
|
|
56
64
|
const items = canonicalItems(messages), raw = { owner, count: messages.length, prefix: digest(messages) };
|
|
57
65
|
return { raw, canonical: { owner, count: items.length, prefix: semanticDigest(items), raw_count: raw.count, raw_prefix: raw.prefix } };
|
|
58
66
|
}
|
|
59
67
|
function knownPrefix(entry, messages, items) {
|
|
60
68
|
if (entry.canonical) return items.length >= entry.canonical.count
|
|
61
69
|
&& semanticDigest(items.slice(0, entry.canonical.count)) === entry.canonical.prefix ? { count: entry.canonical.count } : null;
|
|
70
|
+
messages = historyMessages(messages);
|
|
62
71
|
if (messages.length < entry.count) return null;
|
|
63
72
|
const prefix = messages.slice(0, entry.count);
|
|
64
73
|
const forms = [prefix,
|
|
@@ -93,7 +102,7 @@ function checkHistory(body, counting) {
|
|
|
93
102
|
}
|
|
94
103
|
const pending = new Set();
|
|
95
104
|
for (const message of body.messages) {
|
|
96
|
-
if (!message || !["user", "assistant"].includes(message.role) || !(typeof message.content === "string" || Array.isArray(message.content))) {
|
|
105
|
+
if (!message || !["user", "assistant", "system"].includes(message.role) || !(typeof message.content === "string" || Array.isArray(message.content))) {
|
|
97
106
|
fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid. The original conversation was kept.");
|
|
98
107
|
}
|
|
99
108
|
if (message.role === "assistant" && pending.size) fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.", "tool_call_pending");
|
|
@@ -115,6 +124,7 @@ function checkHistory(body, counting) {
|
|
|
115
124
|
function project(body, count) {
|
|
116
125
|
let removed = 0, index = 0;
|
|
117
126
|
body.messages = body.messages.map(message => {
|
|
127
|
+
if (message.role === "system") return message;
|
|
118
128
|
const start = index;index += Array.isArray(message.content) ? Math.max(1, message.content.length) : 1;
|
|
119
129
|
if (start >= count || message.role !== "assistant") return message;
|
|
120
130
|
const out = { ...message };delete out.reasoning_content;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const invalid = () => Object.assign(new Error("System instructions must contain text"), { code: "ccdx_messages_system_invalid", statusCode: 400 });
|
|
2
|
+
const textBlocks = content => {
|
|
3
|
+
if (typeof content === "string") return [{ type: "text", text: content }];
|
|
4
|
+
if (Array.isArray(content) && content.every(block => block?.type === "text" && typeof block.text === "string")) return content;
|
|
5
|
+
throw invalid();
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
// Alias mapping never selects a content transformation. The resolved endpoint's
|
|
9
|
+
// protocol policy owns it; a model can explicitly override inline-role support.
|
|
10
|
+
export function applyMessagesSystemPolicy(body, mode = "passthrough") {
|
|
11
|
+
if (mode === "passthrough") return body;
|
|
12
|
+
if (!["native", "legacy"].includes(mode)) throw invalid();
|
|
13
|
+
const messages = [], instructions = [];
|
|
14
|
+
let leading = true;
|
|
15
|
+
for (const message of body.messages) {
|
|
16
|
+
if (message?.role === "system" && (mode === "legacy" || leading)) instructions.push(...textBlocks(message.content));
|
|
17
|
+
else { messages.push(message);leading = false; }
|
|
18
|
+
}
|
|
19
|
+
return instructions.length ? { ...body, system: [...(body.system === undefined ? [] : textBlocks(body.system)), ...instructions], messages } : body;
|
|
20
|
+
}
|
|
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
export const MODEL_PROTOCOLS = Object.freeze(["messages", "responses", "chat"]);
|
|
4
4
|
export const REASONING_EFFORTS = Object.freeze(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
5
5
|
const limits = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max"];
|
|
6
|
-
const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output"];
|
|
6
|
+
const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output", "mid_conversation_system"];
|
|
7
7
|
export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "thinking_modes", "input_modalities", "web_search"]);
|
|
8
8
|
const object = value => value && typeof value === "object" && !Array.isArray(value);
|
|
9
9
|
export function validCapabilities(value) {
|
|
@@ -39,7 +39,7 @@ export function catalogCapabilities(model) {
|
|
|
39
39
|
reasoning: first(typeof caps.reasoning === "boolean" ? caps.reasoning : undefined, supports.reasoning),
|
|
40
40
|
reasoning_efforts: first(model.reasoning_efforts, supports.reasoning_effort),
|
|
41
41
|
input_modalities: first(model.input_modalities, caps.input_modalities, supports.vision === true ? ["text", "image"] : undefined),
|
|
42
|
-
tools: first(supports.tools, supports.tool_calls), parallel_tools: supports.parallel_tool_calls, streaming: supports.streaming,
|
|
42
|
+
tools: first(supports.tools, supports.tool_calls), parallel_tools: supports.parallel_tool_calls, streaming: supports.streaming, mid_conversation_system: supports.mid_conversation_system,
|
|
43
43
|
structured_output: first(supports.structured_output, supports.structured_outputs), web_search: first(model.web_search, caps.web_search), thinking_modes: first(model.thinking_modes, caps.thinking_modes),
|
|
44
44
|
...Object.fromEntries(["reasoning_required", "reasoning_adaptive", "reasoning_budget_min", "reasoning_budget_max", "reasoning_format"].map(key => [key, first(model[key], caps[key])])),
|
|
45
45
|
};
|
|
@@ -46,7 +46,10 @@ export function assertPredictionProxyCompatible({ env = process.env, systemProxy
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
export function assertCodexClosed({ exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
49
|
-
if (platform === "win32")
|
|
49
|
+
if (platform === "win32") {
|
|
50
|
+
try { return assertWindowsCodexClosed({ ...options, exec }); }
|
|
51
|
+
catch (error) { if (/Quit Codex/.test(error.message)) error.code = "ccdx_prediction_app_open";throw error; }
|
|
52
|
+
}
|
|
50
53
|
for (const name of ["ChatGPT", "Codex"]) {
|
|
51
54
|
try {
|
|
52
55
|
exec("/usr/bin/pgrep", ["-x", name], { stdio: "pipe", timeout: 2000 });
|
|
@@ -54,7 +57,7 @@ export function assertCodexClosed({ exec = execFileSync, platform = process.plat
|
|
|
54
57
|
if (error.status === 1) continue;
|
|
55
58
|
throw new Error("Could not check whether Codex is closed; prediction setup was skipped");
|
|
56
59
|
}
|
|
57
|
-
throw new Error("Quit Codex App before changing native prediction setup; no running App will be stopped");
|
|
60
|
+
throw Object.assign(new Error("Quit Codex App before changing native prediction setup; no running App will be stopped"), { code: "ccdx_prediction_app_open" });
|
|
58
61
|
}
|
|
59
62
|
}
|
|
60
63
|
|
|
@@ -11,6 +11,8 @@ import { updatePredictionRoute } from "./native-prediction-route.mjs";
|
|
|
11
11
|
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
12
12
|
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
13
13
|
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
14
|
+
import { predictionDisplayPreference, writePredictionDisplayPreference } from "./prediction-preference.mjs";
|
|
15
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
14
16
|
|
|
15
17
|
function certificateDirectory(settings, paths) {
|
|
16
18
|
if (!settings.credentialsDirectory) return paths.directory;
|
|
@@ -56,7 +58,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
56
58
|
return { ...result, exitCode: ["ready", "disabled"].includes(result.status) ? 0 : 1 };
|
|
57
59
|
}
|
|
58
60
|
if (action === "status") {
|
|
59
|
-
output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (
|
|
61
|
+
output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (new integrations: on)`);
|
|
60
62
|
if (settings.enabled && !servicePreferences(opts).prediction_enabled) output("Prediction configuration adaptation: paused by the WebUI preference; trust and route are retained.");
|
|
61
63
|
output("Uses the conversation's model.");
|
|
62
64
|
if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; bridge startup will recheck compatibility. Unsupported changes still require explicit setup.");
|
|
@@ -127,15 +129,19 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
127
129
|
const next = { version: 1, enabled: true, app, store: paths.store, certificateHash: certificate.hash, credentialsDirectory,
|
|
128
130
|
...(Number.isInteger(settings.bridgePort) ? { bridgePort: settings.bridgePort } : {}) };
|
|
129
131
|
let trustAdded = false;
|
|
132
|
+
const previousSettings = fs.existsSync(paths.settings) ? fs.readFileSync(paths.settings) : null;
|
|
130
133
|
try {
|
|
131
134
|
// Add the new trust before committing activation; retain the old record
|
|
132
135
|
// until the commit succeeds so a failed write cannot break an existing setup.
|
|
133
136
|
trustAdded = await updatePredictionTrust(paths.store, certificate);
|
|
134
137
|
writeSettings(next, opts);
|
|
138
|
+
writePredictionDisplayPreference(true, opts);
|
|
135
139
|
}
|
|
136
140
|
catch (error) {
|
|
137
141
|
if (trustAdded) await updatePredictionTrust(paths.store, certificate, { remove: true }).catch(() => {});
|
|
138
142
|
if (generated) fs.rmSync(credentialsDirectory, { recursive: true, force: true });
|
|
143
|
+
if (previousSettings !== null) atomicWriteFileSync(paths.settings, previousSettings);
|
|
144
|
+
else if (fs.existsSync(paths.settings)) fs.unlinkSync(paths.settings);
|
|
139
145
|
throw error;
|
|
140
146
|
}
|
|
141
147
|
if (previous && previous.hash !== certificate.hash) {
|
|
@@ -155,7 +161,17 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
155
161
|
export async function startNativePrediction({ env = process.env, platform = process.platform,
|
|
156
162
|
warning = () => {}, state, ...options } = {}) {
|
|
157
163
|
const opts = { ...options, env, platform };
|
|
158
|
-
|
|
164
|
+
if (options.autoSetup === true && ["darwin", "win32"].includes(platform)
|
|
165
|
+
&& !fs.existsSync(predictionPaths(opts).settings) && servicePreferences(opts).prediction_enabled && predictionDisplayPreference(opts).enabled) {
|
|
166
|
+
await runPredictionCommand({ ...opts, action: "on", output: warning });
|
|
167
|
+
}
|
|
168
|
+
let settings = readPredictionSettings(opts);
|
|
169
|
+
if (settings.displayPending && options.autoSetup === true) {
|
|
170
|
+
try {
|
|
171
|
+
writePredictionDisplayPreference(servicePreferences(opts).prediction_enabled, opts);
|
|
172
|
+
settings = { ...settings, displayPending: false };writePredictionSettings(settings, opts);
|
|
173
|
+
} catch (error) { if (!/Quit Codex/.test(error.message)) throw error; }
|
|
174
|
+
}
|
|
159
175
|
state?.configure(settings.enabled);
|
|
160
176
|
if (!settings.enabled) return null;
|
|
161
177
|
if (!["darwin", "win32"].includes(platform)) throw new Error("Native predictions were skipped: unsupported platform");
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/features.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
|
|
2
2
|
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections", "/_ccdx/ui/context", "/_ccdx/ui/privacy"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { readPredictionSettings, predictionPaths, writePredictionSettings } from "./native-prediction-profile.mjs";
|
|
3
|
+
import { predictionDisplayPreference } from "./prediction-preference.mjs";
|
|
4
|
+
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
5
|
+
import { openCodex } from "./launcher.mjs";
|
|
6
|
+
import { withFileLock } from "./lock.mjs";
|
|
7
|
+
import { runPredictionOperation } from "./prediction-operations.mjs";
|
|
8
|
+
|
|
9
|
+
export function predictionControlSnapshot(options = {}) {
|
|
10
|
+
const saved = readPredictionSettings(options);
|
|
11
|
+
const fresh = !fs.existsSync(predictionPaths(options).settings), display = predictionDisplayPreference(options);
|
|
12
|
+
return { configured: saved.enabled === true, enabled: servicePreferences(options).prediction_enabled && (!fresh || display.enabled),
|
|
13
|
+
default: fresh, display,
|
|
14
|
+
display_pending: saved.displayPending === true };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function controlPrediction(operation, { integration, nativeOperation = runPredictionOperation, ...options } = {}) {
|
|
18
|
+
if (!["enable", "disable", "setup", "remove", "pause", "resume", "repair", "open"].includes(operation)) throw new Error("Unknown prediction operation");
|
|
19
|
+
const settings = readPredictionSettings(options);
|
|
20
|
+
if (operation === "repair" && !settings.displayPending) return integration?.fix() || { status: "needs_service" };
|
|
21
|
+
if (operation === "open") {
|
|
22
|
+
if (!integration) throw new Error("Start CCDX before opening Codex from this control");
|
|
23
|
+
if (!settings.enabled) throw new Error("Enable predictions before opening Codex");
|
|
24
|
+
if (settings.displayPending) {
|
|
25
|
+
await nativeOperation("display", { ...options, enabled: servicePreferences(options).prediction_enabled, requireClosed: true });
|
|
26
|
+
writePredictionSettings({ ...settings, displayPending: false }, options);
|
|
27
|
+
}
|
|
28
|
+
const native = await integration.start();
|
|
29
|
+
if (!native) throw new Error("Prediction bridge is unavailable");
|
|
30
|
+
await native.prepareRoute?.();
|
|
31
|
+
return { opened: await openCodex({ predictionPacUrl: native.pacUrl, predictionApp: native.app, predictionProfile: native.profile,
|
|
32
|
+
env: { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" }, persistedPredictionRoute: false,
|
|
33
|
+
preparePredictionRoute: () => native.prepareRoute?.(), onPredictionRoute: value => integration.launched(value) }) };
|
|
34
|
+
}
|
|
35
|
+
const enabled = operation === "repair" ? servicePreferences(options).prediction_enabled : ["enable", "setup", "resume"].includes(operation);
|
|
36
|
+
let reconfigured = false;
|
|
37
|
+
if (operation === "resume" && !settings.enabled) {
|
|
38
|
+
writeServicePreference("prediction_enabled", true, options);
|
|
39
|
+
return { ...predictionControlSnapshot(options), status: "needs_setup" };
|
|
40
|
+
}
|
|
41
|
+
if (enabled && (!settings.enabled || operation === "setup")) {
|
|
42
|
+
await nativeOperation("command", { ...options, action: "on" });
|
|
43
|
+
reconfigured = true;
|
|
44
|
+
} else if (operation === "remove") {
|
|
45
|
+
integration?.setPredictionActive(false);
|
|
46
|
+
await nativeOperation("command", { ...options, action: "off" });
|
|
47
|
+
writeServicePreference("prediction_enabled", false, options);
|
|
48
|
+
}
|
|
49
|
+
const { pending } = await nativeOperation("display", { ...options, enabled });
|
|
50
|
+
writeServicePreference("prediction_enabled", enabled, options);
|
|
51
|
+
await withFileLock(`${predictionPaths(options).settings}.lock`, () => {
|
|
52
|
+
writePredictionSettings({ ...readPredictionSettings(options), displayPending: pending }, options);
|
|
53
|
+
});
|
|
54
|
+
integration?.setPredictionActive(enabled);
|
|
55
|
+
let runtime;
|
|
56
|
+
if (enabled && integration) {
|
|
57
|
+
if (reconfigured) await integration.pauseForUpdate?.();
|
|
58
|
+
await integration.start();
|
|
59
|
+
runtime = await integration.fix();
|
|
60
|
+
}
|
|
61
|
+
if (operation === "repair" && integration) return integration.fix();
|
|
62
|
+
return { ...predictionControlSnapshot(options), status: pending ? "needs_app_close" : runtime?.status || (!integration ? "next_start" : enabled ? "configured" : "disabled"),
|
|
63
|
+
...(runtime?.prediction ? { bridge: runtime.prediction.bridge } : {}) };
|
|
64
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
3
|
+
import { readPredictionSettings, writePredictionSettings, predictionPaths, assertCodexClosed, installedPredictionApp } from "./native-prediction-profile.mjs";
|
|
4
|
+
import { predictionDisplayPreference, writePredictionDisplayPreference } from "./prediction-preference.mjs";
|
|
5
|
+
import { servicePreferences } from "./user-settings.mjs";
|
|
6
|
+
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
7
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
8
|
+
|
|
9
|
+
// Native OS discovery/crypto is bounded but can block Node. Keep it out of the
|
|
10
|
+
// gateway event loop. Environment results stay private to the bridge lifecycle.
|
|
11
|
+
export async function handlePredictionOperation(operation, options = {}) {
|
|
12
|
+
if (operation === "command") {
|
|
13
|
+
const { runPredictionCommand } = await import("./native-prediction.mjs");
|
|
14
|
+
return runPredictionCommand({ ...options, output() {} });
|
|
15
|
+
}
|
|
16
|
+
if (operation === "display") {
|
|
17
|
+
try { assertCodexClosed(options); }
|
|
18
|
+
catch (error) { if (!options.requireClosed && error.code === "ccdx_prediction_app_open") return { pending: true };throw error; }
|
|
19
|
+
writePredictionDisplayPreference(options.enabled, options);return { pending: false };
|
|
20
|
+
}
|
|
21
|
+
if (operation !== "startup") throw new Error("Unknown native prediction operation");
|
|
22
|
+
let settings = readPredictionSettings(options);
|
|
23
|
+
if (options.autoSetup === true && ["darwin", "win32"].includes(options.platform || process.platform)
|
|
24
|
+
&& !fs.existsSync(predictionPaths(options).settings) && servicePreferences(options).prediction_enabled && predictionDisplayPreference(options).enabled) {
|
|
25
|
+
// Absence/incompatibility must fail before expensive trust and proxy checks.
|
|
26
|
+
const app = await installedPredictionApp(options);
|
|
27
|
+
const { runPredictionCommand } = await import("./native-prediction.mjs");
|
|
28
|
+
await runPredictionCommand({ ...options, action: "on", resolveApp: () => app, output() {} });
|
|
29
|
+
settings = readPredictionSettings(options);
|
|
30
|
+
}
|
|
31
|
+
if (settings.displayPending && options.autoSetup === true) {
|
|
32
|
+
const display = await handlePredictionOperation("display", { ...options, enabled: servicePreferences(options).prediction_enabled });
|
|
33
|
+
if (!display.pending) { settings = { ...settings, displayPending: false };writePredictionSettings(settings, options); }
|
|
34
|
+
}
|
|
35
|
+
return settings.enabled ? { configured: true, environment: inspectPredictionEnvironment(options) } : { configured: false };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function runPredictionOperation(operation, options = {}) {
|
|
39
|
+
const data = Object.fromEntries(["env", "home", "platform", "action", "enabled", "requireClosed", "autoSetup"].filter(key => options[key] !== undefined).map(key => [key, options[key]]));
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const worker = new Worker(new URL(import.meta.url), { workerData: { kind: "prediction_operation", operation, options: data }, stdout: true, stderr: true });
|
|
42
|
+
worker.stdout.resume();worker.stderr.resume();let settled = false;
|
|
43
|
+
const finish = (error, result) => { if (settled) return;settled = true;clearTimeout(timer);error ? reject(error) : resolve(result); };
|
|
44
|
+
const timer = setTimeout(() => { finish(new Error("Native prediction configuration deadline exceeded"));void worker.terminate(); }, 180000);
|
|
45
|
+
worker.once("message", message => {
|
|
46
|
+
if (message.error) finish(Object.assign(new Error(message.error.message), { code: message.error.code, predictionEnvironment: message.error.predictionEnvironment }));
|
|
47
|
+
else {
|
|
48
|
+
const plan = message.result?.environment?.network?.networkRoute;
|
|
49
|
+
if (plan) for (const key of ["http", "https"]) if (plan[key]) plan[key].url = new URL(plan[key].url);
|
|
50
|
+
finish(null, message.result);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
worker.once("error", error => finish(error));worker.once("exit", code => { if (!settled) finish(new Error(`Native prediction operation stopped (${code})`)); });
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (!isMainThread && workerData?.kind === "prediction_operation") {
|
|
58
|
+
try {
|
|
59
|
+
const result = await handlePredictionOperation(workerData.operation, workerData.options);
|
|
60
|
+
const plan = result?.environment?.network?.networkRoute;
|
|
61
|
+
// URL objects are not structured-cloneable. Credentials remain private to
|
|
62
|
+
// this IPC result, and bypass/trust data keeps its original representation.
|
|
63
|
+
if (plan) for (const key of ["http", "https"]) if (plan[key]) plan[key] = { ...plan[key], url: plan[key].url.href };
|
|
64
|
+
parentPort.postMessage({ result });
|
|
65
|
+
}
|
|
66
|
+
catch (error) { parentPort.postMessage({ error: { message: redactDiagnosticText(String(error.message)).slice(0, 600), code: error.code, predictionEnvironment: error.predictionEnvironment } }); }
|
|
67
|
+
finally { parentPort.close(); }
|
|
68
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { stringify } from "smol-toml";
|
|
4
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
5
|
+
import { parseCodexToml, codexTomlStatements, validateManagedConfigEdit } from "./config-toml.mjs";
|
|
6
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
7
|
+
import { atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
8
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
9
|
+
import { assertCodexClosed } from "./native-prediction-profile.mjs";
|
|
10
|
+
|
|
11
|
+
const KEY = "composer-predictions-enabled";
|
|
12
|
+
const ATOMS = "electron-persisted-atom-state";
|
|
13
|
+
const object = value => value && typeof value === "object" && !Array.isArray(value);
|
|
14
|
+
const read = file => {
|
|
15
|
+
try { return new TextDecoder("utf-8", { fatal: true }).decode(readBoundedFileSync(file)); }
|
|
16
|
+
catch (error) { if (error.code === "ENOENT") return "";throw error; }
|
|
17
|
+
};
|
|
18
|
+
const stateAt = text => {
|
|
19
|
+
try { return text ? JSON.parse(text) : {}; }
|
|
20
|
+
catch { throw new Error("Codex display settings are invalid; existing settings were preserved"); }
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function predictionDisplayPreference(options = {}) {
|
|
24
|
+
const { directory, config } = codexPaths(options);
|
|
25
|
+
const modern = parseCodexToml(read(config)).desktop?.[KEY];
|
|
26
|
+
if (modern !== undefined) {
|
|
27
|
+
if (typeof modern !== "boolean") throw new Error("Codex prediction display setting must be boolean");
|
|
28
|
+
return { enabled: modern, source: "desktop" };
|
|
29
|
+
}
|
|
30
|
+
const legacy = read(path.join(directory, ".codex-global-state.json"));
|
|
31
|
+
const saved = stateAt(legacy);
|
|
32
|
+
if (!object(saved) || (saved[ATOMS] !== undefined && !object(saved[ATOMS]))) throw new Error("Codex display settings are invalid; existing settings were preserved");
|
|
33
|
+
const value = modern ?? saved[ATOMS]?.[KEY];
|
|
34
|
+
if (value !== undefined && typeof value !== "boolean") throw new Error("Codex prediction display setting must be boolean");
|
|
35
|
+
return { enabled: value !== false, source: modern !== undefined ? "desktop" : value !== undefined ? "legacy" : "default" };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Codex moved this setting from persisted atoms to desktop TOML. Update both
|
|
39
|
+
// representations while closed; the App owns migration and its live state.
|
|
40
|
+
export function writePredictionDisplayPreference(enabled, options = {}) {
|
|
41
|
+
if (typeof enabled !== "boolean") throw new Error("Prediction display requires a boolean");
|
|
42
|
+
const { directory, config } = codexPaths(options);
|
|
43
|
+
const legacyFile = path.join(directory, ".codex-global-state.json");
|
|
44
|
+
return withFileLockSync(`${config}.ccdx.lock`, () => {
|
|
45
|
+
assertCodexClosed(options);
|
|
46
|
+
const content = read(config), legacy = read(legacyFile), before = parseCodexToml(content);
|
|
47
|
+
const saved = stateAt(legacy);
|
|
48
|
+
if (!object(saved) || (saved[ATOMS] !== undefined && !object(saved[ATOMS]))) throw new Error("Codex display settings are invalid; existing settings were preserved");
|
|
49
|
+
if (before.desktop !== undefined && !object(before.desktop)) throw new Error("Codex desktop settings are invalid; existing settings were preserved");
|
|
50
|
+
const statements = codexTomlStatements(content);
|
|
51
|
+
const exact = statements.find(item => item.kind === "value" && item.keys.length === 2 && item.keys[0] === "desktop" && item.keys[1] === KEY);
|
|
52
|
+
let next = content;
|
|
53
|
+
if (exact) next = content.slice(0, exact.valueStart) + enabled + content.slice(exact.valueEnd);
|
|
54
|
+
else {
|
|
55
|
+
const inline = statements.find(item => item.kind === "value" && item.keys.length === 1 && item.keys[0] === "desktop");
|
|
56
|
+
const table = statements.find(item => item.kind === "table" && item.keys.length === 1 && item.keys[0] === "desktop");
|
|
57
|
+
if (inline) next = content.slice(0, inline.start) + content.slice(inline.end) + "\n" + stringify({ desktop: { ...before.desktop, [KEY]: enabled } });
|
|
58
|
+
else if (table) next = content.slice(0, table.end) + `\n${KEY} = ${enabled}` + content.slice(table.end);
|
|
59
|
+
else {
|
|
60
|
+
const first = statements.find(item => item.kind === "table")?.start ?? content.length;
|
|
61
|
+
next = content.slice(0, first) + `\ndesktop.${KEY} = ${enabled}\n` + content.slice(first);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
validateManagedConfigEdit(before, next, [["desktop", KEY]]);
|
|
65
|
+
if (parseCodexToml(next).desktop?.[KEY] !== enabled) throw new Error("Prediction display could not be updated; existing settings were preserved");
|
|
66
|
+
saved[ATOMS] = { ...saved[ATOMS], [KEY]: enabled };
|
|
67
|
+
assertCodexClosed(options);
|
|
68
|
+
if (read(config) !== content || read(legacyFile) !== legacy) throw new Error("Codex settings changed; retry after quitting the App");
|
|
69
|
+
const data = JSON.stringify(saved) + "\n";
|
|
70
|
+
if (next === content && data === legacy) return { enabled, changed: false };
|
|
71
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
72
|
+
atomicWriteFilePairSync(config, next, legacyFile, data);
|
|
73
|
+
return { enabled, changed: true };
|
|
74
|
+
});
|
|
75
|
+
}
|
package/src/privacy-model.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { promisify } from "node:util";
|
|
|
8
8
|
import { createNpmReleaseFetch, releaseBytes, releaseChecksum, RELEASE_BASE } from "./release-install.mjs";
|
|
9
9
|
|
|
10
10
|
export const PRIVACY_MODEL_REVISION = "7216b6a3b897ef903d4b1ba367ae6fb95b0fa5e4";
|
|
11
|
-
export const PRIVACY_COMPONENT_RELEASE = "1.3.
|
|
11
|
+
export const PRIVACY_COMPONENT_RELEASE = "1.3.9";
|
|
12
12
|
export const PRIVACY_MODEL_FILES = Object.freeze([
|
|
13
13
|
{ name: "model_int8.onnx", bytes: 330781, sha256: "0a070d3113615e33ba3b84d6bd486f663a377c04c4b056e7381732179f51832a" },
|
|
14
14
|
{ name: "model_int8.onnx_data", bytes: 37124608, sha256: "0ba34216ceead01e0ae2dfd8e46d52b67e7aee80b04f722d9b758613a91c0067" },
|
|
@@ -25,7 +25,8 @@ const digest = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
|
25
25
|
export function privacyPaths({ home = os.homedir(), env = process.env, platform = process.platform, arch = process.arch } = {}) {
|
|
26
26
|
const root = path.join(env.XDG_CACHE_HOME || (platform === "win32" ? env.LOCALAPPDATA || path.join(home, "AppData", "Local") : path.join(home, ".cache")), "codex-copilot-dx", "privacy");
|
|
27
27
|
const name = `ccdx-privacy-guard-1-${platform}-${arch}${platform === "win32" ? ".exe" : ""}`;
|
|
28
|
-
|
|
28
|
+
const component = path.join(root, "components", PRIVACY_COMPONENT_RELEASE);
|
|
29
|
+
return { root, model: path.join(root, PRIVACY_MODEL_REVISION), name, runner: path.join(component, name), receipt: path.join(component, name + ".json"), legacyRunner: path.join(root, name), legacyReceipt: path.join(root, name + ".json") };
|
|
29
30
|
}
|
|
30
31
|
async function downloader(env) {
|
|
31
32
|
const names = [env.npm_execpath];
|
|
@@ -45,26 +46,36 @@ async function downloader(env) {
|
|
|
45
46
|
}
|
|
46
47
|
export function createPrivacyModel(options = {}) {
|
|
47
48
|
const env = options.env || process.env, paths = privacyPaths(options), changed = options.changed || (() => {});
|
|
49
|
+
const modelFiles = options.modelFiles || PRIVACY_MODEL_FILES;
|
|
50
|
+
let activeRunner = paths.runner, componentRelease = null, upgradeAttempted = false;
|
|
48
51
|
let child, serial = 0, ready = null, install = null, downloadAbort, line = "", stopped = false;
|
|
49
52
|
let state = { state: "not_downloaded", downloaded_bytes: 0, download_bytes: PRIVACY_DOWNLOAD_BYTES, backend: null, device: null, error: null };
|
|
50
53
|
const jobs = new Map();
|
|
51
54
|
const set = next => { state = { ...state, ...next };changed(); };
|
|
52
|
-
async function installed() {
|
|
55
|
+
async function installed({ current = false } = {}) {
|
|
53
56
|
try {
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
57
|
+
for (const file of modelFiles) if (digest(await fs.readFile(path.join(paths.model, file.name))) !== file.sha256) return false;
|
|
58
|
+
const candidates = [[paths.runner, paths.receipt, PRIVACY_COMPONENT_RELEASE], ...(!current ? [[paths.legacyRunner, paths.legacyReceipt, "1.3.6"]] : [])];
|
|
59
|
+
for (const [runner, receiptFile, release] of candidates) {
|
|
60
|
+
try {
|
|
61
|
+
const receipt = JSON.parse(await fs.readFile(receiptFile, "utf8"));
|
|
62
|
+
if (!/^[a-f0-9]{64}$/.test(receipt.sha256) || receipt.release !== release || digest(await fs.readFile(runner)) !== receipt.sha256) continue;
|
|
63
|
+
if (!child) { activeRunner = runner;componentRelease = release; }
|
|
64
|
+
return true;
|
|
65
|
+
} catch { /* Missing targets never hide a verified ABI-compatible legacy component. */ }
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
59
68
|
} catch { return false; }
|
|
60
69
|
}
|
|
61
|
-
async function download() {
|
|
70
|
+
async function download({ background = false } = {}) {
|
|
62
71
|
if (install) return install;
|
|
63
72
|
stopped = false;downloadAbort = new AbortController();const signal = downloadAbort.signal;
|
|
73
|
+
const report = next => background && child ? set({ component_update: next.state, component_update_error: next.error || null }) : set(next);
|
|
64
74
|
install = (async () => {
|
|
65
|
-
|
|
75
|
+
report({ state: "downloading", error: null, downloaded_bytes: 0 });
|
|
66
76
|
const fetchImpl = options.fetchImpl || await downloader(env);
|
|
67
77
|
await fs.mkdir(paths.model, { recursive: true, mode: 0o700 });
|
|
78
|
+
await fs.mkdir(path.dirname(paths.runner), { recursive: true, mode: 0o700 });
|
|
68
79
|
const base = `${RELEASE_BASE}/v${PRIVACY_COMPONENT_RELEASE}`;
|
|
69
80
|
const sums = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536, signal });
|
|
70
81
|
const expected = releaseChecksum(sums, paths.name);
|
|
@@ -74,9 +85,9 @@ export function createPrivacyModel(options = {}) {
|
|
|
74
85
|
try { await fs.writeFile(tempRunner, runner, { mode: 0o700, flag: "wx" });await fs.rename(tempRunner, paths.runner); }
|
|
75
86
|
finally { await fs.rm(tempRunner, { force: true }); }
|
|
76
87
|
await fs.writeFile(paths.receipt, JSON.stringify({ release: PRIVACY_COMPONENT_RELEASE, sha256: expected }) + "\n", { mode: 0o600 });
|
|
77
|
-
for (const file of
|
|
88
|
+
for (const file of modelFiles) {
|
|
78
89
|
const target = path.join(paths.model, file.name);
|
|
79
|
-
try { if (digest(await fs.readFile(target)) === file.sha256) {
|
|
90
|
+
try { if (digest(await fs.readFile(target)) === file.sha256) { report({ downloaded_bytes: state.downloaded_bytes + file.bytes });continue; } } catch {}
|
|
80
91
|
const response = await fetchImpl(`https://huggingface.co/QuantumNous/astrlink-guard/resolve/${PRIVACY_MODEL_REVISION}/int8/${file.name}`, { signal: AbortSignal.any([signal, AbortSignal.timeout(180000)]), redirect: "follow" });
|
|
81
92
|
const host = response.url && new URL(response.url);
|
|
82
93
|
if (!response.ok || host && (host.protocol !== "https:" || !/^(?:huggingface\.co|[a-z0-9.-]+\.(?:huggingface\.co|hf\.co))$/.test(host.hostname))) { await response.body?.cancel();throw privacyFailure("download_unavailable"); }
|
|
@@ -85,15 +96,15 @@ export function createPrivacyModel(options = {}) {
|
|
|
85
96
|
for await (const bytes of response.body || []) {
|
|
86
97
|
if (signal.aborted) throw signal.reason;
|
|
87
98
|
total += bytes.length;if (total > file.bytes) throw privacyFailure("download_invalid");
|
|
88
|
-
hash.update(bytes);await output.write(bytes);
|
|
99
|
+
hash.update(bytes);await output.write(bytes);report({ downloaded_bytes: state.downloaded_bytes + bytes.length });
|
|
89
100
|
}
|
|
90
101
|
if (total !== file.bytes || hash.digest("hex") !== file.sha256) throw privacyFailure("download_invalid");
|
|
91
102
|
await output.sync();await output.close();await fs.rename(temp, target);
|
|
92
103
|
} finally { await output.close().catch(() => {});await fs.rm(temp, { force: true }); }
|
|
93
104
|
}
|
|
94
105
|
if (signal.aborted || stopped) throw privacyFailure("cancelled");
|
|
95
|
-
|
|
96
|
-
})().catch(error => { if (signal.aborted || stopped) {
|
|
106
|
+
report({ state: background ? "staged" : "installed", error: null });
|
|
107
|
+
})().catch(error => { if (signal.aborted || stopped) { report({ state: "not_downloaded", error: null });throw privacyFailure("cancelled"); }report({ state: "error", error: error.code?.startsWith("ccdx_privacy_") ? error.code : "ccdx_privacy_download_unavailable" });throw privacyFailure("download_unavailable"); })
|
|
97
108
|
.finally(() => { install = null;downloadAbort = null; });
|
|
98
109
|
return install;
|
|
99
110
|
}
|
|
@@ -112,7 +123,7 @@ export function createPrivacyModel(options = {}) {
|
|
|
112
123
|
return new Promise((resolve, reject) => {
|
|
113
124
|
const timer = setTimeout(() => { reject(privacyFailure("load_timeout"));fail(); }, 60000);
|
|
114
125
|
const workerEnv = Object.fromEntries(["PATH", "SystemRoot", "WINDIR", "TMP", "TEMP", "TMPDIR", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "GOMAXPROCS"].filter(key => typeof env[key] === "string").map(key => [key, env[key]]));
|
|
115
|
-
const current = child = (options.spawnImpl || spawn)(
|
|
126
|
+
const current = child = (options.spawnImpl || spawn)(activeRunner, [paths.model], { env: workerEnv, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
|
|
116
127
|
current.stdout.on("data", bytes => {
|
|
117
128
|
if (current !== child) return;
|
|
118
129
|
line += bytes.toString("utf8");if (Buffer.byteLength(line) > 8 * 1024 * 1024) { fail();return; }
|
|
@@ -121,7 +132,7 @@ export function createPrivacyModel(options = {}) {
|
|
|
121
132
|
const part = line.slice(0, end);line = line.slice(end + 1);
|
|
122
133
|
try {
|
|
123
134
|
const value = JSON.parse(part);
|
|
124
|
-
if (value.ready === true) { clearTimeout(timer);set({ state: "ready", backend: value.backend === "CoreML" ? "CoreML" : "CPU", device: ["CPU", "GPU", "Neural Engine"].includes(value.device) ? value.device : null });resolve(); }
|
|
135
|
+
if (value.ready === true) { clearTimeout(timer);set({ state: "ready", backend: value.backend === "CoreML" ? "CoreML" : "CPU", device: ["CPU", "GPU", "Neural Engine"].includes(value.device) ? value.device : null });resolve();if (componentRelease !== PRIVACY_COMPONENT_RELEASE && !upgradeAttempted) { upgradeAttempted = true;void download({ background: true }).catch(() => {}); } }
|
|
125
136
|
else if (jobs.has(value.id)) { const job = jobs.get(value.id);jobs.delete(value.id);clearTimeout(job.timer);job.resolve(value.found);changed();if (stopped && !jobs.size) stop(); }
|
|
126
137
|
} catch { fail(); }
|
|
127
138
|
}
|
|
@@ -139,7 +150,10 @@ export function createPrivacyModel(options = {}) {
|
|
|
139
150
|
if (Buffer.byteLength(input) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
140
151
|
if ([...jobs.values()].reduce((n, job) => n + job.bytes, Buffer.byteLength(input)) > 16 * 1024 * 1024) throw privacyFailure("busy");
|
|
141
152
|
return new Promise((resolve, reject) => {
|
|
142
|
-
|
|
153
|
+
// The helper may still be executing after a waiter leaves. Keep its slot
|
|
154
|
+
// and byte budget until its actual reply or deadline, never admit an
|
|
155
|
+
// unbounded queue by reporting cancelled native work as already idle.
|
|
156
|
+
const cancelled = () => { if (jobs.has(id)) { jobs.get(id).cancelled = true;signal?.removeEventListener("abort", cancelled);reject(signal?.reason || privacyFailure("cancelled"));changed(); } };
|
|
143
157
|
const finish = fn => value => { signal?.removeEventListener("abort", cancelled);fn(value); };
|
|
144
158
|
const timer = setTimeout(() => { reject(privacyFailure("check_timeout"));fail(); }, 300000);
|
|
145
159
|
jobs.set(id, { resolve: finish(resolve), reject: finish(reject), timer, bytes: Buffer.byteLength(input) });signal?.addEventListener("abort", cancelled, { once: true });changed();
|
|
@@ -150,12 +164,12 @@ export function createPrivacyModel(options = {}) {
|
|
|
150
164
|
function snapshot() {
|
|
151
165
|
if (!child && !install && ["installed", "not_downloaded"].includes(state.state)) {
|
|
152
166
|
try {
|
|
153
|
-
const stat = fsSync.lstatSync(paths.runner);
|
|
154
|
-
const cached = stat.isFile() && stat.size > 0 && stat.size <= 16 * 1024 * 1024 &&
|
|
167
|
+
const stat = fsSync.lstatSync(fsSync.existsSync(paths.runner) ? paths.runner : paths.legacyRunner);
|
|
168
|
+
const cached = stat.isFile() && stat.size > 0 && stat.size <= 16 * 1024 * 1024 && modelFiles.every(file => fsSync.lstatSync(path.join(paths.model, file.name)).size === file.bytes);
|
|
155
169
|
state = { ...state, state: cached ? "installed" : "not_downloaded" };
|
|
156
170
|
} catch { state = { ...state, state: "not_downloaded" }; }
|
|
157
171
|
}
|
|
158
|
-
return { ...state, pending_checks: jobs.size };
|
|
172
|
+
return { ...state, component_release: componentRelease, target_component_release: PRIVACY_COMPONENT_RELEASE, pending_checks: jobs.size, cancelled_checks: [...jobs.values()].filter(job => job.cancelled).length };
|
|
159
173
|
}
|
|
160
174
|
return { paths, snapshot, installed, download, load, find, stop,
|
|
161
175
|
async remove() { stop();await install?.catch(() => {});if (jobs.size) throw privacyFailure("busy");await fs.rm(paths.root, { recursive: true, force: true });set({ state: "not_downloaded", downloaded_bytes: 0 }); },
|