codex-copilot-dx 1.3.6 → 1.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -16
- package/bin/cli.mjs +55 -31
- package/docs/ARCHITECTURE.md +14 -2
- package/docs/REFERENCE.md +38 -5
- package/package.json +6 -2
- package/src/claude-gateway.mjs +2 -1
- package/src/cli-command-spec.mjs +3 -2
- package/src/cli-image.mjs +2 -80
- package/src/cli-options.mjs +1 -1
- package/src/client-integration.mjs +11 -4
- package/src/dashboard/connections.js +4 -0
- package/src/dashboard/console.js +12 -6
- package/src/dashboard/features.js +68 -0
- package/src/dashboard/index.html +11 -9
- package/src/dashboard/language.js +57 -14
- package/src/dashboard/status.js +2 -1
- package/src/dashboard/tools.js +4 -1
- package/src/dashboard/ui.js +1 -1
- package/src/dashboard-api.mjs +2 -2
- package/src/dashboard-tools.mjs +2 -1
- package/src/dashboard.mjs +1 -0
- package/src/doctor-compat.mjs +19 -13
- package/src/doctor.mjs +1 -1
- package/src/image-setup.mjs +110 -0
- package/src/local-privacy.mjs +1 -0
- package/src/local-tools.mjs +8 -2
- package/src/native-prediction-profile.mjs +5 -2
- package/src/native-prediction.mjs +18 -2
- package/src/optional-routes.mjs +1 -1
- package/src/prediction-control.mjs +64 -0
- package/src/prediction-operations.mjs +68 -0
- package/src/prediction-preference.mjs +75 -0
- package/src/privacy-model.mjs +6 -4
- package/src/privacy-transform.mjs +39 -25
- package/src/response-failures.mjs +8 -2
- package/src/responses-handler.mjs +2 -2
- package/src/responses-proxy.mjs +1 -1
- package/src/service-control.mjs +33 -7
- package/src/service-supervisor.mjs +39 -18
- package/src/service-worker.mjs +13 -1
- package/src/stream-performance.mjs +2 -2
package/src/doctor.mjs
CHANGED
|
@@ -295,7 +295,7 @@ export async function collectDoctorChecks({
|
|
|
295
295
|
checks.push({ kind: "err", message: "Compatibility checks require a running, version-compatible codex-copilot-dx adapter" });
|
|
296
296
|
} else {
|
|
297
297
|
checks.push(...await inspectAdapterCompatibilityFn({
|
|
298
|
-
host,
|
|
298
|
+
home, env, host,
|
|
299
299
|
port,
|
|
300
300
|
fetchImpl,
|
|
301
301
|
timeoutMs: compatTimeoutMs,
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
4
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
5
|
+
import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
6
|
+
import { computeImageMcpCodexConfig } from "./config.mjs";
|
|
7
|
+
import { updateImageSkill } from "./image-skill.mjs";
|
|
8
|
+
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
9
|
+
import { imageProviderConfigPath, inspectImageProvider, normalizeImageEndpoint, readImageProviderConfig, validateImageProviderConfig } from "./image-provider-config.mjs";
|
|
10
|
+
export function fileContent(filePath) {
|
|
11
|
+
try { return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(fs.readFileSync(filePath)); }
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error?.code === "ENOENT") return "";
|
|
14
|
+
if (error?.code === "ERR_ENCODING_INVALID_ENCODED_DATA") {
|
|
15
|
+
throw new Error("Codex configuration is not valid UTF-8 TOML; no configuration changes were written");
|
|
16
|
+
}
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function enableImageProvider(options) {
|
|
22
|
+
return withFileLockSync(`${options.codexPath}.ccdx.lock`, () => enableImageProviderUnlocked(options));
|
|
23
|
+
}
|
|
24
|
+
function enableImageProviderUnlocked({ providerConfig, providerPath, codexPath, codexContent, adapterPort, adapterHost }) {
|
|
25
|
+
const codex = computeImageMcpCodexConfig(codexContent, {
|
|
26
|
+
enabled: true,
|
|
27
|
+
adapterPort,
|
|
28
|
+
adapterHost,
|
|
29
|
+
});
|
|
30
|
+
const normalized = validateImageProviderConfig(providerConfig, { filePath: providerPath });
|
|
31
|
+
const skill = updateImageSkill({ enabled: true, codexPath, adapterPort, adapterHost });
|
|
32
|
+
try {
|
|
33
|
+
if (fileContent(codexPath) !== codexContent) {
|
|
34
|
+
throw new Error("Codex configuration changed during image setup; retry to preserve the newer settings");
|
|
35
|
+
}
|
|
36
|
+
atomicWriteFilePairSync(
|
|
37
|
+
codexPath,
|
|
38
|
+
codex.content,
|
|
39
|
+
providerPath,
|
|
40
|
+
`${JSON.stringify(normalized, null, 2)}\n`,
|
|
41
|
+
{ mode: 0o600, writeFile: atomicWriteFileIfChangedSync },
|
|
42
|
+
);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
skill.rollback();
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
return { codexChanged: codex.changed, config: normalized };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function disableImageProvider(options) {
|
|
51
|
+
if (!fs.existsSync(options.codexPath)) return disableImageProviderUnlocked(options);
|
|
52
|
+
return withFileLockSync(`${options.codexPath}.ccdx.lock`, () => disableImageProviderUnlocked(options));
|
|
53
|
+
}
|
|
54
|
+
function disableImageProviderUnlocked({ providerPath, codexPath, codexContent, adapterPort, adapterHost }) {
|
|
55
|
+
const codex = computeImageMcpCodexConfig(codexContent, {
|
|
56
|
+
enabled: false,
|
|
57
|
+
adapterPort,
|
|
58
|
+
adapterHost,
|
|
59
|
+
});
|
|
60
|
+
const providerExists = fs.existsSync(providerPath);
|
|
61
|
+
const skill = updateImageSkill({ enabled: false, codexPath, adapterPort, adapterHost });
|
|
62
|
+
try {
|
|
63
|
+
if (fs.existsSync(codexPath)) {
|
|
64
|
+
if (fileContent(codexPath) !== codexContent) {
|
|
65
|
+
throw new Error("Codex configuration changed during image cleanup; retry to preserve the newer settings");
|
|
66
|
+
}
|
|
67
|
+
atomicWriteFilePairSync(codexPath, codex.content, providerPath, null, {
|
|
68
|
+
mode: 0o600, writeFile: atomicWriteFileIfChangedSync,
|
|
69
|
+
});
|
|
70
|
+
} else if (providerExists) {
|
|
71
|
+
fs.unlinkSync(providerPath);
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
skill.rollback();
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
return { changed: providerExists || codex.changed || skill.changed, preservedGuidance: Boolean(skill.preserved) };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function syncEnabledImageSkill({ home = os.homedir(), env = process.env, codexPath = codexPaths({ env, home }).config, ...options } = {}) {
|
|
81
|
+
return updateImageSkill({ ...options, enabled: true, codexPath });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
export function imageSetupSummary(options = {}) {
|
|
86
|
+
const value = readImageProviderConfig({ ...options, strict: true });
|
|
87
|
+
if (!value) return { configured: false };
|
|
88
|
+
const endpoint = new URL(value.endpoint);
|
|
89
|
+
return { configured: true, endpoint: endpoint.origin + endpoint.pathname, model: value.model, protocol: value.protocol };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function configureImageSetup({ operation, endpoint, key, model }, options = {}) {
|
|
93
|
+
const { env = process.env, home = os.homedir(), adapterPort = 2026, adapterHost = "127.0.0.1", fetchImpl = fetch } = options;
|
|
94
|
+
const codexPath = codexPaths({ env, home }).config, providerPath = imageProviderConfigPath({ env, home });
|
|
95
|
+
if (operation === "remove") return { configured: false, ...disableImageProvider({ providerPath, codexPath, codexContent: fileContent(codexPath), adapterPort, adapterHost }) };
|
|
96
|
+
if (!["inspect", "setup"].includes(operation)) throw new Error("Choose image inspect, setup or remove");
|
|
97
|
+
const current = readImageProviderConfig({ env, home, strict: true });
|
|
98
|
+
const normalized = normalizeImageEndpoint(endpoint || current?.endpoint);
|
|
99
|
+
const sameOrigin = current && new URL(normalized).origin === new URL(current.endpoint).origin;
|
|
100
|
+
const apiKey = String(key || "").trim() || (sameOrigin ? current.api_key : "");
|
|
101
|
+
if (!apiKey) throw new Error("Enter an image API key for this address");
|
|
102
|
+
const inspected = await inspectImageProvider({ endpoint: normalized, apiKey, fetchImpl,
|
|
103
|
+
selectModel: ids => model || (ids.includes(current?.model) ? current.model : ids[0]) });
|
|
104
|
+
if (operation === "inspect") return { endpoint: inspected.endpoint, models: inspected.modelIds, protocol: inspected.protocol };
|
|
105
|
+
if (!model || !inspected.modelIds.includes(model)) throw new Error("Choose a listed image model");
|
|
106
|
+
enableImageProvider({ providerPath, codexPath, codexContent: fileContent(codexPath), adapterPort, adapterHost,
|
|
107
|
+
providerConfig: { endpoint: inspected.endpoint, api_key: apiKey, model, protocol: inspected.protocol } });
|
|
108
|
+
if (!servicePreferences({ env, home }).image_enabled) writeServicePreference("image_enabled", true, { env, home });
|
|
109
|
+
return imageSetupSummary({ env, home });
|
|
110
|
+
}
|
package/src/local-privacy.mjs
CHANGED
|
@@ -82,6 +82,7 @@ export function createLocalPrivacy(options = {}) {
|
|
|
82
82
|
current = { count: session.count, sessions,
|
|
83
83
|
restoreText: value => sessions.reduce((text, item) => item.restoreText(text), value),
|
|
84
84
|
restoreValue: value => sessions.reduce((text, item) => item.restoreValue(text), value),
|
|
85
|
+
restoreToolValue: value => sessions.reduce((text, item) => item.restoreToolValue(text), value),
|
|
85
86
|
release: () => { sessions.forEach(item => item.release());sessions.length = 0;responses.delete(res); } };
|
|
86
87
|
responses.set(res, current);sessions.push(session);protectPrivacyResponse(res, current);
|
|
87
88
|
} else current.sessions.push(session);
|
package/src/local-tools.mjs
CHANGED
|
@@ -8,10 +8,11 @@ import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
|
8
8
|
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
9
9
|
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
10
10
|
import { localPackageVersion } from "./version.mjs";
|
|
11
|
+
import { inspectAdapterCompatibility } from "./doctor-compat.mjs";
|
|
11
12
|
|
|
12
13
|
export function createLocalTools({ home = os.homedir(), env = process.env, host = "127.0.0.1", port = 2026,
|
|
13
14
|
platform = process.platform, collect = collectDoctorChecks, inspectConfig = inspectCodexConfig, repairConfig = repairCodexConfig,
|
|
14
|
-
inspectNetwork = inspectPredictionEnvironment } = {}) {
|
|
15
|
+
inspectNetwork = inspectPredictionEnvironment, inspectCompatibility = inspectAdapterCompatibility } = {}) {
|
|
15
16
|
const options = { home, env, host, port, platform };
|
|
16
17
|
let last = null, flight = null;
|
|
17
18
|
const safe = text => redactDiagnosticText(String(text || "")).split(home).join("~")
|
|
@@ -48,6 +49,11 @@ export function createLocalTools({ home = os.homedir(), env = process.env, host
|
|
|
48
49
|
const value = inspectNetwork({ env, platform });
|
|
49
50
|
return { source: "network_check", checked_at: new Date().toISOString(), summary: safe(formatPredictionEnvironment(value.summary)) };
|
|
50
51
|
}
|
|
51
|
-
|
|
52
|
+
async function compatibility() {
|
|
53
|
+
if (flight) throw new Error("A diagnostic operation is already running");
|
|
54
|
+
flight = Promise.resolve().then(async () => ({ source: "compatibility_check", checked_at: new Date().toISOString(), checks: project(await inspectCompatibility(options)) })).finally(() => { flight = null; });
|
|
55
|
+
return flight;
|
|
56
|
+
}
|
|
57
|
+
return { snapshot, check, preview, repair, network, compatibility, busy: () => Boolean(flight), report: () => ({ version: localPackageVersion(),
|
|
52
58
|
exported_at: new Date().toISOString(), scope: "local checks only; accounts and credentials omitted", ...snapshot() }) };
|
|
53
59
|
}
|
|
@@ -46,7 +46,10 @@ export function assertPredictionProxyCompatible({ env = process.env, systemProxy
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
export function assertCodexClosed({ exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
49
|
-
if (platform === "win32")
|
|
49
|
+
if (platform === "win32") {
|
|
50
|
+
try { return assertWindowsCodexClosed({ ...options, exec }); }
|
|
51
|
+
catch (error) { if (/Quit Codex/.test(error.message)) error.code = "ccdx_prediction_app_open";throw error; }
|
|
52
|
+
}
|
|
50
53
|
for (const name of ["ChatGPT", "Codex"]) {
|
|
51
54
|
try {
|
|
52
55
|
exec("/usr/bin/pgrep", ["-x", name], { stdio: "pipe", timeout: 2000 });
|
|
@@ -54,7 +57,7 @@ export function assertCodexClosed({ exec = execFileSync, platform = process.plat
|
|
|
54
57
|
if (error.status === 1) continue;
|
|
55
58
|
throw new Error("Could not check whether Codex is closed; prediction setup was skipped");
|
|
56
59
|
}
|
|
57
|
-
throw new Error("Quit Codex App before changing native prediction setup; no running App will be stopped");
|
|
60
|
+
throw Object.assign(new Error("Quit Codex App before changing native prediction setup; no running App will be stopped"), { code: "ccdx_prediction_app_open" });
|
|
58
61
|
}
|
|
59
62
|
}
|
|
60
63
|
|
|
@@ -11,6 +11,8 @@ import { updatePredictionRoute } from "./native-prediction-route.mjs";
|
|
|
11
11
|
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
12
12
|
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
13
13
|
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
14
|
+
import { predictionDisplayPreference, writePredictionDisplayPreference } from "./prediction-preference.mjs";
|
|
15
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
14
16
|
|
|
15
17
|
function certificateDirectory(settings, paths) {
|
|
16
18
|
if (!settings.credentialsDirectory) return paths.directory;
|
|
@@ -56,7 +58,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
56
58
|
return { ...result, exitCode: ["ready", "disabled"].includes(result.status) ? 0 : 1 };
|
|
57
59
|
}
|
|
58
60
|
if (action === "status") {
|
|
59
|
-
output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (
|
|
61
|
+
output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (new integrations: on)`);
|
|
60
62
|
if (settings.enabled && !servicePreferences(opts).prediction_enabled) output("Prediction configuration adaptation: paused by the WebUI preference; trust and route are retained.");
|
|
61
63
|
output("Uses the conversation's model.");
|
|
62
64
|
if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; bridge startup will recheck compatibility. Unsupported changes still require explicit setup.");
|
|
@@ -127,15 +129,19 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
127
129
|
const next = { version: 1, enabled: true, app, store: paths.store, certificateHash: certificate.hash, credentialsDirectory,
|
|
128
130
|
...(Number.isInteger(settings.bridgePort) ? { bridgePort: settings.bridgePort } : {}) };
|
|
129
131
|
let trustAdded = false;
|
|
132
|
+
const previousSettings = fs.existsSync(paths.settings) ? fs.readFileSync(paths.settings) : null;
|
|
130
133
|
try {
|
|
131
134
|
// Add the new trust before committing activation; retain the old record
|
|
132
135
|
// until the commit succeeds so a failed write cannot break an existing setup.
|
|
133
136
|
trustAdded = await updatePredictionTrust(paths.store, certificate);
|
|
134
137
|
writeSettings(next, opts);
|
|
138
|
+
writePredictionDisplayPreference(true, opts);
|
|
135
139
|
}
|
|
136
140
|
catch (error) {
|
|
137
141
|
if (trustAdded) await updatePredictionTrust(paths.store, certificate, { remove: true }).catch(() => {});
|
|
138
142
|
if (generated) fs.rmSync(credentialsDirectory, { recursive: true, force: true });
|
|
143
|
+
if (previousSettings !== null) atomicWriteFileSync(paths.settings, previousSettings);
|
|
144
|
+
else if (fs.existsSync(paths.settings)) fs.unlinkSync(paths.settings);
|
|
139
145
|
throw error;
|
|
140
146
|
}
|
|
141
147
|
if (previous && previous.hash !== certificate.hash) {
|
|
@@ -155,7 +161,17 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
155
161
|
export async function startNativePrediction({ env = process.env, platform = process.platform,
|
|
156
162
|
warning = () => {}, state, ...options } = {}) {
|
|
157
163
|
const opts = { ...options, env, platform };
|
|
158
|
-
|
|
164
|
+
if (options.autoSetup === true && ["darwin", "win32"].includes(platform)
|
|
165
|
+
&& !fs.existsSync(predictionPaths(opts).settings) && servicePreferences(opts).prediction_enabled && predictionDisplayPreference(opts).enabled) {
|
|
166
|
+
await runPredictionCommand({ ...opts, action: "on", output: warning });
|
|
167
|
+
}
|
|
168
|
+
let settings = readPredictionSettings(opts);
|
|
169
|
+
if (settings.displayPending && options.autoSetup === true) {
|
|
170
|
+
try {
|
|
171
|
+
writePredictionDisplayPreference(servicePreferences(opts).prediction_enabled, opts);
|
|
172
|
+
settings = { ...settings, displayPending: false };writePredictionSettings(settings, opts);
|
|
173
|
+
} catch (error) { if (!/Quit Codex/.test(error.message)) throw error; }
|
|
174
|
+
}
|
|
159
175
|
state?.configure(settings.enabled);
|
|
160
176
|
if (!settings.enabled) return null;
|
|
161
177
|
if (!["darwin", "win32"].includes(platform)) throw new Error("Native predictions were skipped: unsupported platform");
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/features.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
|
|
2
2
|
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections", "/_ccdx/ui/context", "/_ccdx/ui/privacy"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { readPredictionSettings, predictionPaths, writePredictionSettings } from "./native-prediction-profile.mjs";
|
|
3
|
+
import { predictionDisplayPreference } from "./prediction-preference.mjs";
|
|
4
|
+
import { servicePreferences, writeServicePreference } from "./user-settings.mjs";
|
|
5
|
+
import { openCodex } from "./launcher.mjs";
|
|
6
|
+
import { withFileLock } from "./lock.mjs";
|
|
7
|
+
import { runPredictionOperation } from "./prediction-operations.mjs";
|
|
8
|
+
|
|
9
|
+
export function predictionControlSnapshot(options = {}) {
|
|
10
|
+
const saved = readPredictionSettings(options);
|
|
11
|
+
const fresh = !fs.existsSync(predictionPaths(options).settings), display = predictionDisplayPreference(options);
|
|
12
|
+
return { configured: saved.enabled === true, enabled: servicePreferences(options).prediction_enabled && (!fresh || display.enabled),
|
|
13
|
+
default: fresh, display,
|
|
14
|
+
display_pending: saved.displayPending === true };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function controlPrediction(operation, { integration, nativeOperation = runPredictionOperation, ...options } = {}) {
|
|
18
|
+
if (!["enable", "disable", "setup", "remove", "pause", "resume", "repair", "open"].includes(operation)) throw new Error("Unknown prediction operation");
|
|
19
|
+
const settings = readPredictionSettings(options);
|
|
20
|
+
if (operation === "repair" && !settings.displayPending) return integration?.fix() || { status: "needs_service" };
|
|
21
|
+
if (operation === "open") {
|
|
22
|
+
if (!integration) throw new Error("Start CCDX before opening Codex from this control");
|
|
23
|
+
if (!settings.enabled) throw new Error("Enable predictions before opening Codex");
|
|
24
|
+
if (settings.displayPending) {
|
|
25
|
+
await nativeOperation("display", { ...options, enabled: servicePreferences(options).prediction_enabled, requireClosed: true });
|
|
26
|
+
writePredictionSettings({ ...settings, displayPending: false }, options);
|
|
27
|
+
}
|
|
28
|
+
const native = await integration.start();
|
|
29
|
+
if (!native) throw new Error("Prediction bridge is unavailable");
|
|
30
|
+
await native.prepareRoute?.();
|
|
31
|
+
return { opened: await openCodex({ predictionPacUrl: native.pacUrl, predictionApp: native.app, predictionProfile: native.profile,
|
|
32
|
+
env: { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" }, persistedPredictionRoute: false,
|
|
33
|
+
preparePredictionRoute: () => native.prepareRoute?.(), onPredictionRoute: value => integration.launched(value) }) };
|
|
34
|
+
}
|
|
35
|
+
const enabled = operation === "repair" ? servicePreferences(options).prediction_enabled : ["enable", "setup", "resume"].includes(operation);
|
|
36
|
+
let reconfigured = false;
|
|
37
|
+
if (operation === "resume" && !settings.enabled) {
|
|
38
|
+
writeServicePreference("prediction_enabled", true, options);
|
|
39
|
+
return { ...predictionControlSnapshot(options), status: "needs_setup" };
|
|
40
|
+
}
|
|
41
|
+
if (enabled && (!settings.enabled || operation === "setup")) {
|
|
42
|
+
await nativeOperation("command", { ...options, action: "on" });
|
|
43
|
+
reconfigured = true;
|
|
44
|
+
} else if (operation === "remove") {
|
|
45
|
+
integration?.setPredictionActive(false);
|
|
46
|
+
await nativeOperation("command", { ...options, action: "off" });
|
|
47
|
+
writeServicePreference("prediction_enabled", false, options);
|
|
48
|
+
}
|
|
49
|
+
const { pending } = await nativeOperation("display", { ...options, enabled });
|
|
50
|
+
writeServicePreference("prediction_enabled", enabled, options);
|
|
51
|
+
await withFileLock(`${predictionPaths(options).settings}.lock`, () => {
|
|
52
|
+
writePredictionSettings({ ...readPredictionSettings(options), displayPending: pending }, options);
|
|
53
|
+
});
|
|
54
|
+
integration?.setPredictionActive(enabled);
|
|
55
|
+
let runtime;
|
|
56
|
+
if (enabled && integration) {
|
|
57
|
+
if (reconfigured) await integration.pauseForUpdate?.();
|
|
58
|
+
await integration.start();
|
|
59
|
+
runtime = await integration.fix();
|
|
60
|
+
}
|
|
61
|
+
if (operation === "repair" && integration) return integration.fix();
|
|
62
|
+
return { ...predictionControlSnapshot(options), status: pending ? "needs_app_close" : runtime?.status || (!integration ? "next_start" : enabled ? "configured" : "disabled"),
|
|
63
|
+
...(runtime?.prediction ? { bridge: runtime.prediction.bridge } : {}) };
|
|
64
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
3
|
+
import { readPredictionSettings, writePredictionSettings, predictionPaths, assertCodexClosed, installedPredictionApp } from "./native-prediction-profile.mjs";
|
|
4
|
+
import { predictionDisplayPreference, writePredictionDisplayPreference } from "./prediction-preference.mjs";
|
|
5
|
+
import { servicePreferences } from "./user-settings.mjs";
|
|
6
|
+
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
7
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
8
|
+
|
|
9
|
+
// Native OS discovery/crypto is bounded but can block Node. Keep it out of the
|
|
10
|
+
// gateway event loop. Environment results stay private to the bridge lifecycle.
|
|
11
|
+
export async function handlePredictionOperation(operation, options = {}) {
|
|
12
|
+
if (operation === "command") {
|
|
13
|
+
const { runPredictionCommand } = await import("./native-prediction.mjs");
|
|
14
|
+
return runPredictionCommand({ ...options, output() {} });
|
|
15
|
+
}
|
|
16
|
+
if (operation === "display") {
|
|
17
|
+
try { assertCodexClosed(options); }
|
|
18
|
+
catch (error) { if (!options.requireClosed && error.code === "ccdx_prediction_app_open") return { pending: true };throw error; }
|
|
19
|
+
writePredictionDisplayPreference(options.enabled, options);return { pending: false };
|
|
20
|
+
}
|
|
21
|
+
if (operation !== "startup") throw new Error("Unknown native prediction operation");
|
|
22
|
+
let settings = readPredictionSettings(options);
|
|
23
|
+
if (options.autoSetup === true && ["darwin", "win32"].includes(options.platform || process.platform)
|
|
24
|
+
&& !fs.existsSync(predictionPaths(options).settings) && servicePreferences(options).prediction_enabled && predictionDisplayPreference(options).enabled) {
|
|
25
|
+
// Absence/incompatibility must fail before expensive trust and proxy checks.
|
|
26
|
+
const app = await installedPredictionApp(options);
|
|
27
|
+
const { runPredictionCommand } = await import("./native-prediction.mjs");
|
|
28
|
+
await runPredictionCommand({ ...options, action: "on", resolveApp: () => app, output() {} });
|
|
29
|
+
settings = readPredictionSettings(options);
|
|
30
|
+
}
|
|
31
|
+
if (settings.displayPending && options.autoSetup === true) {
|
|
32
|
+
const display = await handlePredictionOperation("display", { ...options, enabled: servicePreferences(options).prediction_enabled });
|
|
33
|
+
if (!display.pending) { settings = { ...settings, displayPending: false };writePredictionSettings(settings, options); }
|
|
34
|
+
}
|
|
35
|
+
return settings.enabled ? { configured: true, environment: inspectPredictionEnvironment(options) } : { configured: false };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function runPredictionOperation(operation, options = {}) {
|
|
39
|
+
const data = Object.fromEntries(["env", "home", "platform", "action", "enabled", "requireClosed", "autoSetup"].filter(key => options[key] !== undefined).map(key => [key, options[key]]));
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const worker = new Worker(new URL(import.meta.url), { workerData: { kind: "prediction_operation", operation, options: data }, stdout: true, stderr: true });
|
|
42
|
+
worker.stdout.resume();worker.stderr.resume();let settled = false;
|
|
43
|
+
const finish = (error, result) => { if (settled) return;settled = true;clearTimeout(timer);error ? reject(error) : resolve(result); };
|
|
44
|
+
const timer = setTimeout(() => { finish(new Error("Native prediction configuration deadline exceeded"));void worker.terminate(); }, 180000);
|
|
45
|
+
worker.once("message", message => {
|
|
46
|
+
if (message.error) finish(Object.assign(new Error(message.error.message), { code: message.error.code, predictionEnvironment: message.error.predictionEnvironment }));
|
|
47
|
+
else {
|
|
48
|
+
const plan = message.result?.environment?.network?.networkRoute;
|
|
49
|
+
if (plan) for (const key of ["http", "https"]) if (plan[key]) plan[key].url = new URL(plan[key].url);
|
|
50
|
+
finish(null, message.result);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
worker.once("error", error => finish(error));worker.once("exit", code => { if (!settled) finish(new Error(`Native prediction operation stopped (${code})`)); });
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (!isMainThread && workerData?.kind === "prediction_operation") {
|
|
58
|
+
try {
|
|
59
|
+
const result = await handlePredictionOperation(workerData.operation, workerData.options);
|
|
60
|
+
const plan = result?.environment?.network?.networkRoute;
|
|
61
|
+
// URL objects are not structured-cloneable. Credentials remain private to
|
|
62
|
+
// this IPC result, and bypass/trust data keeps its original representation.
|
|
63
|
+
if (plan) for (const key of ["http", "https"]) if (plan[key]) plan[key] = { ...plan[key], url: plan[key].url.href };
|
|
64
|
+
parentPort.postMessage({ result });
|
|
65
|
+
}
|
|
66
|
+
catch (error) { parentPort.postMessage({ error: { message: redactDiagnosticText(String(error.message)).slice(0, 600), code: error.code, predictionEnvironment: error.predictionEnvironment } }); }
|
|
67
|
+
finally { parentPort.close(); }
|
|
68
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { stringify } from "smol-toml";
|
|
4
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
5
|
+
import { parseCodexToml, codexTomlStatements, validateManagedConfigEdit } from "./config-toml.mjs";
|
|
6
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
7
|
+
import { atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
8
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
9
|
+
import { assertCodexClosed } from "./native-prediction-profile.mjs";
|
|
10
|
+
|
|
11
|
+
const KEY = "composer-predictions-enabled";
|
|
12
|
+
const ATOMS = "electron-persisted-atom-state";
|
|
13
|
+
const object = value => value && typeof value === "object" && !Array.isArray(value);
|
|
14
|
+
const read = file => {
|
|
15
|
+
try { return new TextDecoder("utf-8", { fatal: true }).decode(readBoundedFileSync(file)); }
|
|
16
|
+
catch (error) { if (error.code === "ENOENT") return "";throw error; }
|
|
17
|
+
};
|
|
18
|
+
const stateAt = text => {
|
|
19
|
+
try { return text ? JSON.parse(text) : {}; }
|
|
20
|
+
catch { throw new Error("Codex display settings are invalid; existing settings were preserved"); }
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function predictionDisplayPreference(options = {}) {
|
|
24
|
+
const { directory, config } = codexPaths(options);
|
|
25
|
+
const modern = parseCodexToml(read(config)).desktop?.[KEY];
|
|
26
|
+
if (modern !== undefined) {
|
|
27
|
+
if (typeof modern !== "boolean") throw new Error("Codex prediction display setting must be boolean");
|
|
28
|
+
return { enabled: modern, source: "desktop" };
|
|
29
|
+
}
|
|
30
|
+
const legacy = read(path.join(directory, ".codex-global-state.json"));
|
|
31
|
+
const saved = stateAt(legacy);
|
|
32
|
+
if (!object(saved) || (saved[ATOMS] !== undefined && !object(saved[ATOMS]))) throw new Error("Codex display settings are invalid; existing settings were preserved");
|
|
33
|
+
const value = modern ?? saved[ATOMS]?.[KEY];
|
|
34
|
+
if (value !== undefined && typeof value !== "boolean") throw new Error("Codex prediction display setting must be boolean");
|
|
35
|
+
return { enabled: value !== false, source: modern !== undefined ? "desktop" : value !== undefined ? "legacy" : "default" };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Codex moved this setting from persisted atoms to desktop TOML. Update both
|
|
39
|
+
// representations while closed; the App owns migration and its live state.
|
|
40
|
+
export function writePredictionDisplayPreference(enabled, options = {}) {
|
|
41
|
+
if (typeof enabled !== "boolean") throw new Error("Prediction display requires a boolean");
|
|
42
|
+
const { directory, config } = codexPaths(options);
|
|
43
|
+
const legacyFile = path.join(directory, ".codex-global-state.json");
|
|
44
|
+
return withFileLockSync(`${config}.ccdx.lock`, () => {
|
|
45
|
+
assertCodexClosed(options);
|
|
46
|
+
const content = read(config), legacy = read(legacyFile), before = parseCodexToml(content);
|
|
47
|
+
const saved = stateAt(legacy);
|
|
48
|
+
if (!object(saved) || (saved[ATOMS] !== undefined && !object(saved[ATOMS]))) throw new Error("Codex display settings are invalid; existing settings were preserved");
|
|
49
|
+
if (before.desktop !== undefined && !object(before.desktop)) throw new Error("Codex desktop settings are invalid; existing settings were preserved");
|
|
50
|
+
const statements = codexTomlStatements(content);
|
|
51
|
+
const exact = statements.find(item => item.kind === "value" && item.keys.length === 2 && item.keys[0] === "desktop" && item.keys[1] === KEY);
|
|
52
|
+
let next = content;
|
|
53
|
+
if (exact) next = content.slice(0, exact.valueStart) + enabled + content.slice(exact.valueEnd);
|
|
54
|
+
else {
|
|
55
|
+
const inline = statements.find(item => item.kind === "value" && item.keys.length === 1 && item.keys[0] === "desktop");
|
|
56
|
+
const table = statements.find(item => item.kind === "table" && item.keys.length === 1 && item.keys[0] === "desktop");
|
|
57
|
+
if (inline) next = content.slice(0, inline.start) + content.slice(inline.end) + "\n" + stringify({ desktop: { ...before.desktop, [KEY]: enabled } });
|
|
58
|
+
else if (table) next = content.slice(0, table.end) + `\n${KEY} = ${enabled}` + content.slice(table.end);
|
|
59
|
+
else {
|
|
60
|
+
const first = statements.find(item => item.kind === "table")?.start ?? content.length;
|
|
61
|
+
next = content.slice(0, first) + `\ndesktop.${KEY} = ${enabled}\n` + content.slice(first);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
validateManagedConfigEdit(before, next, [["desktop", KEY]]);
|
|
65
|
+
if (parseCodexToml(next).desktop?.[KEY] !== enabled) throw new Error("Prediction display could not be updated; existing settings were preserved");
|
|
66
|
+
saved[ATOMS] = { ...saved[ATOMS], [KEY]: enabled };
|
|
67
|
+
assertCodexClosed(options);
|
|
68
|
+
if (read(config) !== content || read(legacyFile) !== legacy) throw new Error("Codex settings changed; retry after quitting the App");
|
|
69
|
+
const data = JSON.stringify(saved) + "\n";
|
|
70
|
+
if (next === content && data === legacy) return { enabled, changed: false };
|
|
71
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
72
|
+
atomicWriteFilePairSync(config, next, legacyFile, data);
|
|
73
|
+
return { enabled, changed: true };
|
|
74
|
+
});
|
|
75
|
+
}
|
package/src/privacy-model.mjs
CHANGED
|
@@ -15,10 +15,12 @@ export const PRIVACY_MODEL_FILES = Object.freeze([
|
|
|
15
15
|
{ name: "tokenizer.json", bytes: 1502881, sha256: "0cf3b235ef125658015a6c8026a5fe6f28088bf825101a990ec18a10200feef4" },
|
|
16
16
|
]);
|
|
17
17
|
export const PRIVACY_DOWNLOAD_BYTES = PRIVACY_MODEL_FILES.reduce((n, file) => n + file.bytes, 0);
|
|
18
|
-
export
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
18
|
+
export function privacyFailure(code, phase = "check") {
|
|
19
|
+
const message = phase === "response" ? "Local privacy response restoration failed. The response was stopped; review Settings."
|
|
20
|
+
: "Local privacy check could not finish. Nothing was sent; review Settings.";
|
|
21
|
+
return Object.assign(new Error(message), { code: `ccdx_privacy_${code}`, statusCode: 503, origin: "privacy",
|
|
22
|
+
jsonBody: { error: { type: "api_error", code: `ccdx_privacy_${code}`, message } } });
|
|
23
|
+
}
|
|
22
24
|
const digest = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
23
25
|
export function privacyPaths({ home = os.homedir(), env = process.env, platform = process.platform, arch = process.arch } = {}) {
|
|
24
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");
|
|
@@ -9,12 +9,12 @@ const secretPatterns = [
|
|
|
9
9
|
];
|
|
10
10
|
const secretField = /(?:["']?\b(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password)\b["']?\s*[:=]\s*)(?:"((?:\\.|[^"\\\r\n])+)"|'((?:\\.|[^'\\\r\n])+)'|([^\s,;\r\n}]+))/gdi;
|
|
11
11
|
const personalKinds = new Set(["email", "phone", "account", "payment_card", "private_address", "private_date", "private_person"]);
|
|
12
|
-
const kept = new Set(["model", "id", "type", "role", "name", "call_id", "tool_use_id", "signature", "encrypted_content", "thought_signature", "thoughtSignature", "data", "url", "file_id"]);
|
|
12
|
+
const kept = new Set(["model", "id", "type", "role", "name", "namespace", "server_label", "server_name", "call_id", "tool_use_id", "item_id", "signature", "encrypted_content", "thought_signature", "thoughtSignature", "data", "url", "file_id", "previous_response_id", "prompt_cache_key", "media_type", "mime_type", "stop_reason", "finish_reason", "status", "object", "event"]);
|
|
13
13
|
function leaves(value, add, inArguments = false) {
|
|
14
14
|
if (typeof value === "string") return;
|
|
15
15
|
if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) typeof value[i] === "string" ? add(value, i, value[i], inArguments) : leaves(value[i], add, inArguments);return; }
|
|
16
16
|
if (!value || typeof value !== "object") return;
|
|
17
|
-
if (value.encrypted_content || ["thinking", "reasoning"].includes(value.type)) return;
|
|
17
|
+
if (!inArguments && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return;
|
|
18
18
|
for (const [key, item] of Object.entries(value)) {
|
|
19
19
|
if (!inArguments && kept.has(key)) continue;
|
|
20
20
|
if (typeof item === "string") add(value, key, item, inArguments);
|
|
@@ -50,7 +50,8 @@ function requestTexts(body, protocol) {
|
|
|
50
50
|
text(body, "instructions");
|
|
51
51
|
if (typeof body.input === "string") add(body, "input", body.input);
|
|
52
52
|
else for (const item of body.input || []) {
|
|
53
|
-
if (item.type
|
|
53
|
+
if (["additional_tools", "tool_search_output"].includes(item.type)) descriptions(item.tools);
|
|
54
|
+
else if (item.type === "function_call") args(item, "arguments");
|
|
54
55
|
else if (["function_call_output", "custom_tool_call_output"].includes(item.type)) text(item, "output");
|
|
55
56
|
else if (item.type === "custom_tool_call") text(item, "input");
|
|
56
57
|
else text(item, "content");
|
|
@@ -97,38 +98,52 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
|
|
|
97
98
|
}
|
|
98
99
|
if (total.count) for (const item of nested) item.parent[item.key] = JSON.stringify(item.value);
|
|
99
100
|
const restoreText = text => text.replace(tokenPattern, token => values.get(token) ?? token);
|
|
100
|
-
function restoreValue(value) {
|
|
101
|
+
function restoreValue(value, inToolData = false) {
|
|
101
102
|
if (typeof value === "string") return restoreText(value);
|
|
102
|
-
if (Array.isArray(value)) return value.map(restoreValue);
|
|
103
|
+
if (Array.isArray(value)) return value.map(item => restoreValue(item, inToolData));
|
|
103
104
|
if (!value || typeof value !== "object") return value;
|
|
104
|
-
if (value.encrypted_content || ["thinking", "reasoning"].includes(value.type)) return value;
|
|
105
|
-
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key,
|
|
106
|
-
: key === "arguments" && typeof item === "string" && item ? restoreArguments(item)
|
|
105
|
+
if (!inToolData && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return value;
|
|
106
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, !inToolData && kept.has(key) ? item
|
|
107
|
+
: !inToolData && key === "arguments" && typeof item === "string" && item ? restoreArguments(item)
|
|
108
|
+
: restoreValue(item, inToolData || key === "input" && ["tool_use", "server_tool_use", "mcp_tool_use"].includes(value.type))]));
|
|
107
109
|
}
|
|
108
|
-
function restoreArguments(text) { try { return JSON.stringify(restoreValue(JSON.parse(text))); } catch { return restoreText(text); } }
|
|
109
|
-
return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue,
|
|
110
|
+
function restoreArguments(text) { try { return JSON.stringify(restoreValue(JSON.parse(text), true)); } catch { return restoreText(text); } }
|
|
111
|
+
return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue,
|
|
112
|
+
restoreToolValue: value => restoreValue(value, true), release: () => values.clear() };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function rewritePrivacyFrame(wire, value, named = false) {
|
|
116
|
+
let written = false;
|
|
117
|
+
const lines = wire.split(/(?<=\n)/).map(line => {
|
|
118
|
+
if (!line.startsWith("data:")) return line;
|
|
119
|
+
if (written) return "";
|
|
120
|
+
written = true;
|
|
121
|
+
return `data: ${JSON.stringify(value)}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : ""}`;
|
|
122
|
+
}).join("");
|
|
123
|
+
return named && !/^event:/m.test(wire) ? `event: ${value.type}\n${lines}` : lines;
|
|
110
124
|
}
|
|
111
125
|
|
|
112
126
|
export function createPrivacyStream(session) {
|
|
127
|
+
const fail = code => privacyFailure(code, "response");
|
|
113
128
|
let pending = "", bytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
|
|
114
|
-
const frame = value => `data: ${JSON.stringify(value)}\n\n`;
|
|
115
129
|
function transform(wire) {
|
|
116
130
|
const data = wire.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
117
131
|
if (!data || data === "[DONE]") return wire;
|
|
118
|
-
let event;try { event = JSON.parse(data); } catch { throw
|
|
132
|
+
let event;try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
|
|
133
|
+
if (["error", "response.failed", "response.incomplete"].includes(event.type)) { channels.clear();return rewritePrivacyFrame(wire, session.restoreValue(event)); }
|
|
119
134
|
if (["thinking_delta", "signature_delta"].includes(event.delta?.type) || /\.reasoning(?:_|\.)/.test(event.type || "")) return wire;
|
|
120
135
|
const isMessages = event.type === "content_block_delta", delta = isMessages ? event.delta : event;
|
|
121
136
|
const tool = delta?.type === "input_json_delta" || event.type === "response.function_call_arguments.delta";
|
|
122
|
-
const text = delta?.type === "text_delta" ||
|
|
137
|
+
const text = delta?.type === "text_delta" || ["response.output_text.delta", "response.custom_tool_call_input.delta"].includes(event.type);
|
|
123
138
|
let before = "";
|
|
124
139
|
const key = isMessages ? `m:${event.index}` : `r:${event.item_id || event.item?.id || event.output_index}:${event.content_index || 0}`;
|
|
125
140
|
if (tool || text) {
|
|
126
141
|
const field = tool ? isMessages ? "partial_json" : "delta" : isMessages ? "text" : "delta";
|
|
127
|
-
if (typeof delta[field] !== "string") throw
|
|
128
|
-
const channel = channels.get(key) || { tail: "", tool, field
|
|
142
|
+
if (typeof delta[field] !== "string") throw fail("stream_invalid");
|
|
143
|
+
const channel = channels.get(key) || { tail: "", tool, field };channel.template = event;channel.wire = wire;
|
|
129
144
|
let value = channel.tail + delta[field];
|
|
130
|
-
if (Buffer.byteLength(value) > 8 * 1024 * 1024) throw
|
|
131
|
-
if (tool) { channel.tail = value;
|
|
145
|
+
if (Buffer.byteLength(value) > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
146
|
+
if (tool) { channel.tail = value;channels.set(key, channel);return ""; }
|
|
132
147
|
else {
|
|
133
148
|
let cut = value.length;
|
|
134
149
|
const at = value.lastIndexOf("{{CCDX_");
|
|
@@ -143,24 +158,23 @@ export function createPrivacyStream(session) {
|
|
|
143
158
|
for (const [id, channel] of channels) if (terminal || id === stopKey) {
|
|
144
159
|
if (channel.tail) {
|
|
145
160
|
const value = structuredClone(channel.template), target = value.type === "content_block_delta" ? value.delta : value;
|
|
146
|
-
target[channel.field] = channel.tool ? JSON.stringify(session.
|
|
147
|
-
|
|
161
|
+
try { target[channel.field] = channel.tool ? JSON.stringify(session.restoreToolValue(JSON.parse(channel.tail))) : session.restoreText(channel.tail); }
|
|
162
|
+
catch { throw fail("stream_invalid"); }
|
|
163
|
+
before += rewritePrivacyFrame(channel.wire, value, true);
|
|
148
164
|
}
|
|
149
165
|
channels.delete(id);
|
|
150
166
|
}
|
|
151
167
|
event = session.restoreValue(event);
|
|
152
|
-
|
|
153
|
-
const changed = lines.map(line => { if (!line.startsWith("data:")) return line;if (written) return null;written = true;return `data: ${JSON.stringify(event)}`; }).filter(line => line !== null).join("\n");
|
|
154
|
-
return before + changed;
|
|
168
|
+
return before + rewritePrivacyFrame(wire, event);
|
|
155
169
|
}
|
|
156
170
|
return {
|
|
157
171
|
push(chunk) {
|
|
158
|
-
pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw
|
|
172
|
+
pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
159
173
|
let output = "", match;
|
|
160
174
|
while ((match = /\r?\n\r?\n/.exec(pending))) { const end = match.index + match[0].length;output += transform(pending.slice(0, end));pending = pending.slice(end);bytes = Buffer.byteLength(pending); }
|
|
161
175
|
return output;
|
|
162
176
|
},
|
|
163
|
-
finish() { pending += decoder.end();if (pending) { const output = transform(pending + "\n\n");pending = "";return output; }if (channels.size) throw
|
|
177
|
+
finish() { pending += decoder.end();if (pending) { const output = transform(pending + "\n\n");pending = "";return output; }if (channels.size) throw fail("stream_incomplete");return ""; },
|
|
164
178
|
};
|
|
165
179
|
}
|
|
166
180
|
|
|
@@ -178,7 +192,7 @@ export function protectPrivacyResponse(res, session) {
|
|
|
178
192
|
res.write = (value, encoding, callback) => {
|
|
179
193
|
const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value, typeof encoding === "string" ? encoding : undefined);
|
|
180
194
|
if (mode === "stream") { try { const output = stream.push(bytes);return output ? write(output, typeof encoding === "function" ? encoding : callback) : true; }catch (error) { detach();throw error; } }
|
|
181
|
-
size += bytes.length;if (size > 16 * 1024 * 1024) throw privacyFailure("response_limit");parts.push(bytes);return true;
|
|
195
|
+
size += bytes.length;if (size > 16 * 1024 * 1024) throw privacyFailure("response_limit", "response");parts.push(bytes);return true;
|
|
182
196
|
};
|
|
183
197
|
res.end = (value, encoding, callback) => {
|
|
184
198
|
if (value !== undefined && value !== null) res.write(value, encoding);
|