codex-copilot-dx 1.3.8 → 1.3.10
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 +3 -2
- package/docs/ARCHITECTURE.md +24 -4
- package/docs/REFERENCE.md +20 -6
- package/package.json +3 -3
- package/src/adapter.mjs +2 -0
- package/src/claude-gateway.mjs +22 -18
- package/src/cli-command-spec.mjs +3 -0
- package/src/cli-management.mjs +14 -1
- package/src/connection-runtime.mjs +1 -0
- package/src/dashboard/connections.js +1 -1
- package/src/dashboard/features.js +9 -4
- package/src/dashboard/index.html +5 -6
- package/src/dashboard/language.js +7 -2
- package/src/dashboard/privacy.js +6 -4
- package/src/dashboard/usage.js +2 -2
- package/src/dashboard-api.mjs +5 -0
- package/src/http-transport.mjs +1 -0
- package/src/local-privacy.mjs +63 -23
- 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/privacy-model.mjs +61 -25
- package/src/privacy-transform.mjs +80 -13
- package/src/providers/m365.mjs +5 -2
- package/src/service-control.mjs +7 -1
- package/src/stream-performance.mjs +2 -1
- package/src/terminal-console.mjs +2 -2
- package/src/terminal-state.mjs +2 -1
- package/src/usage-analytics.mjs +10 -4
- package/src/usage-store.mjs +43 -18
- package/src/usage.mjs +18 -5
package/src/local-privacy.mjs
CHANGED
|
@@ -6,20 +6,24 @@ import { withFileLockSync } from "./lock.mjs";
|
|
|
6
6
|
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
7
7
|
import { createChangeSignal } from "./activity-events.mjs";
|
|
8
8
|
import { createPrivacyModel, privacyFailure } from "./privacy-model.mjs";
|
|
9
|
-
import { maskPrivacyRequest, protectPrivacyResponse } from "./privacy-transform.mjs";
|
|
9
|
+
import { maskPrivacyRequest, protectPrivacyResponse, createPrivacyRuleCache, validatePrivacyFindings } from "./privacy-transform.mjs";
|
|
10
10
|
import { markRequestObservation } from "./stream-performance.mjs";
|
|
11
11
|
|
|
12
12
|
export function createLocalPrivacy(options = {}) {
|
|
13
13
|
const changes = createChangeSignal(), secret = randomBytes(32), cache = new Map(), flights = new Map(), responses = new WeakMap(), policies = new WeakMap();
|
|
14
14
|
const model = options.model || createPrivacyModel({ ...options, changed: changes.changed });
|
|
15
|
+
const rules = createPrivacyRuleCache();
|
|
15
16
|
let cacheBytes = 0, generation = 0, pending = null, disposed = false;
|
|
16
|
-
let keyLoaded = false, actionError = null;
|
|
17
|
+
let keyLoaded = false, actionError = null, lastCheck = null;
|
|
17
18
|
const settings = () => {
|
|
18
19
|
const saved = readUserSettings({ ...options, strict: true });
|
|
19
20
|
return { enabled: saved.privacy_enabled === true, personal: saved.privacy_personal === true };
|
|
20
21
|
};
|
|
21
22
|
const revision = saved => createHash("sha256").update(JSON.stringify(saved)).digest("hex");
|
|
22
|
-
const snapshot = () => { const saved = settings()
|
|
23
|
+
const snapshot = () => { const saved = settings(), detector = model.snapshot();return { ...detector, ...saved,
|
|
24
|
+
effective_enabled: saved.enabled && detector.state === "ready", last_check: lastCheck && { ...lastCheck,
|
|
25
|
+
...(lastCheck.continuing ? { continuing: flights.size > 0 || detector.pending_checks > 0 } : {}) }, rule_cache: rules.stats(),
|
|
26
|
+
...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
|
|
23
27
|
function loadKey() {
|
|
24
28
|
if (keyLoaded) return;
|
|
25
29
|
const file = path.join(path.dirname(userSettingsPath(options)), "privacy-key");fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
@@ -37,44 +41,80 @@ export function createLocalPrivacy(options = {}) {
|
|
|
37
41
|
});changes.changed();
|
|
38
42
|
}
|
|
39
43
|
async function find(texts, { signal } = {}) {
|
|
44
|
+
if (signal?.aborted) throw signal.reason;
|
|
40
45
|
const waiting = [], fresh = [], entries = [];
|
|
41
46
|
for (const text of texts) {
|
|
42
47
|
const key = createHash("sha256").update(text).digest("hex");
|
|
43
48
|
if (cache.has(key)) {
|
|
44
49
|
const saved = cache.get(key);cache.delete(key);cache.set(key, saved);waiting.push(Promise.resolve(saved.found));
|
|
45
|
-
} else
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
} else {
|
|
51
|
+
let entry = flights.get(key);
|
|
52
|
+
if (!entry) {
|
|
53
|
+
entry = Promise.withResolvers();Object.assign(entry, { key, text, waiters: 0, done: false });
|
|
54
|
+
flights.set(key, entry);fresh.push(entry);
|
|
55
|
+
}
|
|
56
|
+
entry.waiters++;entries.push(entry);waiting.push(entry.promise);
|
|
49
57
|
}
|
|
50
58
|
}
|
|
51
|
-
|
|
52
|
-
if (
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
+
const finish = (entry, value, error) => {
|
|
60
|
+
if (entry.done) return;
|
|
61
|
+
entry.done = true;entry.text = null;
|
|
62
|
+
if (flights.get(entry.key) === entry) flights.delete(entry.key);
|
|
63
|
+
if (error) entry.reject(error);else entry.resolve(value);
|
|
64
|
+
};
|
|
65
|
+
const run = async () => {
|
|
66
|
+
let at = 0;
|
|
67
|
+
try {
|
|
68
|
+
while (at < fresh.length) {
|
|
69
|
+
const batch = [];let bytes = 0;
|
|
70
|
+
while (at < fresh.length && batch.length < 64) {
|
|
71
|
+
const entry = fresh[at];
|
|
72
|
+
if (!entry.waiters) { finish(entry, null, privacyFailure("cancelled"));at++;continue; }
|
|
73
|
+
const size = Buffer.byteLength(entry.text);
|
|
74
|
+
if (batch.length && bytes + size > (options.batchBytes ?? 16 * 1024)) break;
|
|
75
|
+
batch.push(entry);bytes += size;at++;
|
|
76
|
+
}
|
|
77
|
+
if (!batch.length) continue;
|
|
78
|
+
// A submitted batch finishes even if its callers leave. Whole text
|
|
79
|
+
// entries keep their context; later batches can yield unused work.
|
|
80
|
+
const input = batch.map(entry => entry.text), found = validatePrivacyFindings(input, await model.find(input));
|
|
81
|
+
for (let i = 0; i < found.length; i++) {
|
|
82
|
+
const cost = Buffer.byteLength(JSON.stringify(found[i])) + 128, entry = batch[i];
|
|
83
|
+
if (cost <= 1024 * 1024) {
|
|
84
|
+
const previous = cache.get(entry.key);if (previous) cacheBytes -= previous.bytes;
|
|
85
|
+
cache.set(entry.key, { found: found[i], bytes: cost });cacheBytes += cost;
|
|
86
|
+
while (cache.size > 5000 || cacheBytes > 4 * 1024 * 1024) { const oldest = cache.keys().next().value;cacheBytes -= cache.get(oldest).bytes;cache.delete(oldest); }
|
|
87
|
+
}
|
|
88
|
+
finish(entry, found[i]);
|
|
89
|
+
}
|
|
59
90
|
}
|
|
60
|
-
|
|
91
|
+
} catch (error) {
|
|
92
|
+
for (const entry of fresh) finish(entry, null, error);
|
|
61
93
|
}
|
|
62
|
-
}
|
|
94
|
+
};
|
|
95
|
+
if (fresh.length) void run();
|
|
63
96
|
let listener;
|
|
64
97
|
const aborted = new Promise((_, reject) => { listener = () => reject(signal.reason);if (signal?.aborted) listener();else signal?.addEventListener("abort", listener, { once: true }); });
|
|
65
98
|
try { return await (signal ? Promise.race([Promise.all(waiting), aborted]) : Promise.all(waiting)); }
|
|
66
|
-
finally { signal?.removeEventListener("abort", listener); }
|
|
99
|
+
finally { signal?.removeEventListener("abort", listener);for (const entry of entries) entry.waiters--; }
|
|
67
100
|
}
|
|
68
101
|
async function prepare(body, { protocol, client, signal, res, policy } = {}) {
|
|
69
102
|
const saved = policy || settings();if (!saved.enabled) return body;
|
|
70
103
|
if (disposed) throw privacyFailure("engine_unavailable");
|
|
71
104
|
loadKey();
|
|
72
105
|
const start = performance.now();
|
|
73
|
-
const deadline = AbortSignal.timeout(15000);let session;
|
|
74
|
-
try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
|
|
75
|
-
catch (error) {
|
|
106
|
+
const deadline = AbortSignal.timeout(options.checkTimeoutMs ?? 15000);let session;
|
|
107
|
+
try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, rules: rules.find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
|
|
108
|
+
catch (error) {
|
|
109
|
+
const failure = deadline.aborted && !signal?.aborted ? privacyFailure("check_timeout", "waiting") : error;
|
|
110
|
+
const elapsed = Math.round(performance.now() - start), cancelled = signal?.aborted === true;
|
|
111
|
+
lastCheck = { state: cancelled ? "cancelled" : "failed", at: new Date().toISOString(), elapsed_ms: elapsed,
|
|
112
|
+
code: /^ccdx_privacy_[a-z_]+$/.test(failure?.code || "") ? failure.code : cancelled ? "ccdx_privacy_cancelled" : "ccdx_privacy_unavailable", continuing: !cancelled && failure?.retryAfter === 5 };
|
|
113
|
+
markRequestObservation({ privacy_ms: elapsed, privacy_state: cancelled ? "cancelled" : "failed" });changes.changed();throw failure;
|
|
114
|
+
}
|
|
76
115
|
if (signal?.aborted) { session.release();throw signal.reason; }
|
|
77
116
|
markRequestObservation({ privacy_count: session.count, privacy_ms: Math.round(performance.now() - start), privacy_state: "checked" });
|
|
117
|
+
actionError = null;lastCheck = { state: "checked", at: new Date().toISOString(), elapsed_ms: Math.round(performance.now() - start), count: session.count };changes.changed();
|
|
78
118
|
if (res && session.count) {
|
|
79
119
|
let current = responses.get(res);
|
|
80
120
|
if (!current) {
|
|
@@ -107,7 +147,7 @@ export function createLocalPrivacy(options = {}) {
|
|
|
107
147
|
const current = ++generation;
|
|
108
148
|
const work = (async () => {
|
|
109
149
|
actionError = null;loadKey();
|
|
110
|
-
if (!await model.installed()) await model.download();
|
|
150
|
+
if (!await model.installed({ current: true })) await model.download({ background: model.snapshot().state === "ready" });
|
|
111
151
|
if (current !== generation) return;
|
|
112
152
|
await model.load();if (current !== generation) return;
|
|
113
153
|
save({ privacy_enabled: true }, input.revision);
|
|
@@ -132,5 +172,5 @@ export function createLocalPrivacy(options = {}) {
|
|
|
132
172
|
},
|
|
133
173
|
restoreResponse: (res, value) => responses.get(res)?.restoreValue(value) || value,
|
|
134
174
|
settingsChanged() { actionError = null;if (!settings().enabled) { generation++;model.stop(); }else warm();changes.changed(); },
|
|
135
|
-
close() { disposed = true;generation++;model.close();cache.clear();cacheBytes = 0;secret.fill(0); } };
|
|
175
|
+
close() { disposed = true;generation++;model.close();cache.clear();rules.clear();cacheBytes = 0;secret.fill(0); } };
|
|
136
176
|
}
|
|
@@ -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
|
};
|
package/src/privacy-model.mjs
CHANGED
|
@@ -5,10 +5,11 @@ import os from "node:os";
|
|
|
5
5
|
import { createHash, randomUUID } from "node:crypto";
|
|
6
6
|
import { spawn, execFile } from "node:child_process";
|
|
7
7
|
import { promisify } from "node:util";
|
|
8
|
-
import { createNpmReleaseFetch, releaseBytes, releaseChecksum, RELEASE_BASE } from "./release-install.mjs";
|
|
8
|
+
import { createNpmReleaseFetch, releaseBytes, releaseChecksum, RELEASE_BASE, stableVersion } 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.10";
|
|
12
|
+
export const PRIVACY_COMPONENT_ABI = 1;
|
|
12
13
|
export const PRIVACY_MODEL_FILES = Object.freeze([
|
|
13
14
|
{ name: "model_int8.onnx", bytes: 330781, sha256: "0a070d3113615e33ba3b84d6bd486f663a377c04c4b056e7381732179f51832a" },
|
|
14
15
|
{ name: "model_int8.onnx_data", bytes: 37124608, sha256: "0ba34216ceead01e0ae2dfd8e46d52b67e7aee80b04f722d9b758613a91c0067" },
|
|
@@ -17,15 +18,21 @@ export const PRIVACY_MODEL_FILES = Object.freeze([
|
|
|
17
18
|
export const PRIVACY_DOWNLOAD_BYTES = PRIVACY_MODEL_FILES.reduce((n, file) => n + file.bytes, 0);
|
|
18
19
|
export function privacyFailure(code, phase = "check") {
|
|
19
20
|
const message = phase === "response" ? "Local privacy response restoration failed. The response was stopped; review Settings."
|
|
21
|
+
: phase === "waiting" ? "Local privacy detection is still running. Nothing was sent; retry shortly to reuse its results."
|
|
22
|
+
: code === "busy" ? "Local privacy detection is busy. Nothing was sent; retry shortly."
|
|
23
|
+
: code === "engine_invalid" ? "The local privacy detector returned an invalid result. Nothing was sent; retry or check Settings."
|
|
24
|
+
: code === "check_timeout" ? "The local privacy detector reached its processing deadline. Nothing was sent; check Settings."
|
|
20
25
|
: "Local privacy check could not finish. Nothing was sent; review Settings.";
|
|
21
26
|
return Object.assign(new Error(message), { code: `ccdx_privacy_${code}`, statusCode: 503, origin: "privacy",
|
|
27
|
+
...(phase === "waiting" || code === "busy" ? { retryAfter: 5 } : {}),
|
|
22
28
|
jsonBody: { error: { type: "api_error", code: `ccdx_privacy_${code}`, message } } });
|
|
23
29
|
}
|
|
24
30
|
const digest = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
25
31
|
export function privacyPaths({ home = os.homedir(), env = process.env, platform = process.platform, arch = process.arch } = {}) {
|
|
26
32
|
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
|
-
const name = `ccdx-privacy-guard
|
|
28
|
-
|
|
33
|
+
const name = `ccdx-privacy-guard-${PRIVACY_COMPONENT_ABI}-${platform}-${arch}${platform === "win32" ? ".exe" : ""}`;
|
|
34
|
+
const components = path.join(root, "components"), component = path.join(components, PRIVACY_COMPONENT_RELEASE);
|
|
35
|
+
return { root, components, 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
36
|
}
|
|
30
37
|
async function downloader(env) {
|
|
31
38
|
const names = [env.npm_execpath];
|
|
@@ -45,26 +52,49 @@ async function downloader(env) {
|
|
|
45
52
|
}
|
|
46
53
|
export function createPrivacyModel(options = {}) {
|
|
47
54
|
const env = options.env || process.env, paths = privacyPaths(options), changed = options.changed || (() => {});
|
|
55
|
+
const modelFiles = options.modelFiles || PRIVACY_MODEL_FILES;
|
|
56
|
+
let activeRunner = paths.runner, componentRelease = null, upgradeAttempted = false;
|
|
48
57
|
let child, serial = 0, ready = null, install = null, downloadAbort, line = "", stopped = false;
|
|
49
58
|
let state = { state: "not_downloaded", downloaded_bytes: 0, download_bytes: PRIVACY_DOWNLOAD_BYTES, backend: null, device: null, error: null };
|
|
50
59
|
const jobs = new Map();
|
|
51
60
|
const set = next => { state = { ...state, ...next };changed(); };
|
|
52
|
-
|
|
61
|
+
const compareVersions = (a, b) => { const x = a.split(".").map(Number), y = b.split(".").map(Number);return x[0] - y[0] || x[1] - y[1] || x[2] - y[2]; };
|
|
62
|
+
function candidates(current = false) {
|
|
63
|
+
const result = [[paths.runner, paths.receipt, PRIVACY_COMPONENT_RELEASE]];
|
|
64
|
+
if (current) return result;
|
|
53
65
|
try {
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
for (const
|
|
58
|
-
|
|
66
|
+
const versions = fsSync.readdirSync(paths.components, { withFileTypes: true }).filter(entry => (entry.isDirectory() || entry.isSymbolicLink())
|
|
67
|
+
&& stableVersion(entry.name) === entry.name && compareVersions(entry.name, PRIVACY_COMPONENT_RELEASE) < 0)
|
|
68
|
+
.map(entry => entry.name).sort((a, b) => compareVersions(b, a)).slice(0, 16);
|
|
69
|
+
for (const version of versions) { const runner = path.join(paths.components, version, paths.name);result.push([runner, runner + ".json", version]); }
|
|
70
|
+
} catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
71
|
+
result.push([paths.legacyRunner, paths.legacyReceipt, "1.3.6"]);return result;
|
|
72
|
+
}
|
|
73
|
+
async function installed({ current = false } = {}) {
|
|
74
|
+
try {
|
|
75
|
+
for (const file of modelFiles) if (digest(await fs.readFile(path.join(paths.model, file.name))) !== file.sha256) return false;
|
|
76
|
+
for (const [runner, receiptFile, release] of candidates(current)) {
|
|
77
|
+
try {
|
|
78
|
+
const receipt = JSON.parse(await fs.readFile(receiptFile, "utf8"));
|
|
79
|
+
if (!/^[a-f0-9]{64}$/.test(receipt.sha256) || receipt.release !== release || digest(await fs.readFile(runner)) !== receipt.sha256) continue;
|
|
80
|
+
const legacy = PRIVACY_COMPONENT_ABI === 1 && ["1.3.6", "1.3.9"].includes(release) && receipt.abi === undefined && receipt.model_revision === undefined;
|
|
81
|
+
if (!legacy && (receipt.abi !== PRIVACY_COMPONENT_ABI || receipt.model_revision !== PRIVACY_MODEL_REVISION)) continue;
|
|
82
|
+
if (!child) { activeRunner = runner;componentRelease = release; }
|
|
83
|
+
return true;
|
|
84
|
+
} catch { /* Missing targets never hide a verified ABI-compatible legacy component. */ }
|
|
85
|
+
}
|
|
86
|
+
return false;
|
|
59
87
|
} catch { return false; }
|
|
60
88
|
}
|
|
61
|
-
async function download() {
|
|
89
|
+
async function download({ background = false } = {}) {
|
|
62
90
|
if (install) return install;
|
|
63
91
|
stopped = false;downloadAbort = new AbortController();const signal = downloadAbort.signal;
|
|
92
|
+
const report = next => background && child ? set({ component_update: next.state, component_update_error: next.error || null }) : set(next);
|
|
64
93
|
install = (async () => {
|
|
65
|
-
|
|
94
|
+
report({ state: "downloading", error: null, downloaded_bytes: 0 });
|
|
66
95
|
const fetchImpl = options.fetchImpl || await downloader(env);
|
|
67
96
|
await fs.mkdir(paths.model, { recursive: true, mode: 0o700 });
|
|
97
|
+
await fs.mkdir(path.dirname(paths.runner), { recursive: true, mode: 0o700 });
|
|
68
98
|
const base = `${RELEASE_BASE}/v${PRIVACY_COMPONENT_RELEASE}`;
|
|
69
99
|
const sums = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536, signal });
|
|
70
100
|
const expected = releaseChecksum(sums, paths.name);
|
|
@@ -73,10 +103,11 @@ export function createPrivacyModel(options = {}) {
|
|
|
73
103
|
const tempRunner = paths.runner + "." + randomUUID();
|
|
74
104
|
try { await fs.writeFile(tempRunner, runner, { mode: 0o700, flag: "wx" });await fs.rename(tempRunner, paths.runner); }
|
|
75
105
|
finally { await fs.rm(tempRunner, { force: true }); }
|
|
76
|
-
await fs.writeFile(paths.receipt, JSON.stringify({ release: PRIVACY_COMPONENT_RELEASE,
|
|
77
|
-
|
|
106
|
+
await fs.writeFile(paths.receipt, JSON.stringify({ release: PRIVACY_COMPONENT_RELEASE, abi: PRIVACY_COMPONENT_ABI,
|
|
107
|
+
model_revision: PRIVACY_MODEL_REVISION, sha256: expected }) + "\n", { mode: 0o600 });
|
|
108
|
+
for (const file of modelFiles) {
|
|
78
109
|
const target = path.join(paths.model, file.name);
|
|
79
|
-
try { if (digest(await fs.readFile(target)) === file.sha256) {
|
|
110
|
+
try { if (digest(await fs.readFile(target)) === file.sha256) { report({ downloaded_bytes: state.downloaded_bytes + file.bytes });continue; } } catch {}
|
|
80
111
|
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
112
|
const host = response.url && new URL(response.url);
|
|
82
113
|
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 +116,15 @@ export function createPrivacyModel(options = {}) {
|
|
|
85
116
|
for await (const bytes of response.body || []) {
|
|
86
117
|
if (signal.aborted) throw signal.reason;
|
|
87
118
|
total += bytes.length;if (total > file.bytes) throw privacyFailure("download_invalid");
|
|
88
|
-
hash.update(bytes);await output.write(bytes);
|
|
119
|
+
hash.update(bytes);await output.write(bytes);report({ downloaded_bytes: state.downloaded_bytes + bytes.length });
|
|
89
120
|
}
|
|
90
121
|
if (total !== file.bytes || hash.digest("hex") !== file.sha256) throw privacyFailure("download_invalid");
|
|
91
122
|
await output.sync();await output.close();await fs.rename(temp, target);
|
|
92
123
|
} finally { await output.close().catch(() => {});await fs.rm(temp, { force: true }); }
|
|
93
124
|
}
|
|
94
125
|
if (signal.aborted || stopped) throw privacyFailure("cancelled");
|
|
95
|
-
|
|
96
|
-
})().catch(error => { if (signal.aborted || stopped) {
|
|
126
|
+
report({ state: background ? "staged" : "installed", error: null });
|
|
127
|
+
})().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
128
|
.finally(() => { install = null;downloadAbort = null; });
|
|
98
129
|
return install;
|
|
99
130
|
}
|
|
@@ -103,16 +134,17 @@ export function createPrivacyModel(options = {}) {
|
|
|
103
134
|
jobs.clear();set({ state: stopped ? "installed" : "error", error: stopped ? null : "ccdx_privacy_engine_unavailable" });
|
|
104
135
|
}
|
|
105
136
|
function load() {
|
|
137
|
+
if (child && state.state === "ready" && !install && !jobs.size && componentRelease !== PRIVACY_COMPONENT_RELEASE && state.component_update === "staged") stop();
|
|
106
138
|
stopped = false;
|
|
107
139
|
if (ready) return ready;
|
|
108
140
|
ready = (async () => {
|
|
109
141
|
if (!await installed()) { set({ state: "not_downloaded" });throw privacyFailure("not_downloaded"); }
|
|
110
142
|
if (stopped) throw privacyFailure("cancelled");
|
|
111
|
-
set({ state: "loading", error: null });
|
|
143
|
+
set({ state: "loading", error: null, ...(componentRelease === PRIVACY_COMPONENT_RELEASE ? { component_update: null, component_update_error: null } : {}) });
|
|
112
144
|
return new Promise((resolve, reject) => {
|
|
113
145
|
const timer = setTimeout(() => { reject(privacyFailure("load_timeout"));fail(); }, 60000);
|
|
114
146
|
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)(
|
|
147
|
+
const current = child = (options.spawnImpl || spawn)(activeRunner, [paths.model], { env: workerEnv, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
|
|
116
148
|
current.stdout.on("data", bytes => {
|
|
117
149
|
if (current !== child) return;
|
|
118
150
|
line += bytes.toString("utf8");if (Buffer.byteLength(line) > 8 * 1024 * 1024) { fail();return; }
|
|
@@ -121,7 +153,7 @@ export function createPrivacyModel(options = {}) {
|
|
|
121
153
|
const part = line.slice(0, end);line = line.slice(end + 1);
|
|
122
154
|
try {
|
|
123
155
|
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(); }
|
|
156
|
+
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
157
|
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
158
|
} catch { fail(); }
|
|
127
159
|
}
|
|
@@ -139,7 +171,10 @@ export function createPrivacyModel(options = {}) {
|
|
|
139
171
|
if (Buffer.byteLength(input) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
140
172
|
if ([...jobs.values()].reduce((n, job) => n + job.bytes, Buffer.byteLength(input)) > 16 * 1024 * 1024) throw privacyFailure("busy");
|
|
141
173
|
return new Promise((resolve, reject) => {
|
|
142
|
-
|
|
174
|
+
// The helper may still be executing after a waiter leaves. Keep its slot
|
|
175
|
+
// and byte budget until its actual reply or deadline, never admit an
|
|
176
|
+
// unbounded queue by reporting cancelled native work as already idle.
|
|
177
|
+
const cancelled = () => { if (jobs.has(id)) { jobs.get(id).cancelled = true;signal?.removeEventListener("abort", cancelled);reject(signal?.reason || privacyFailure("cancelled"));changed(); } };
|
|
143
178
|
const finish = fn => value => { signal?.removeEventListener("abort", cancelled);fn(value); };
|
|
144
179
|
const timer = setTimeout(() => { reject(privacyFailure("check_timeout"));fail(); }, 300000);
|
|
145
180
|
jobs.set(id, { resolve: finish(resolve), reject: finish(reject), timer, bytes: Buffer.byteLength(input) });signal?.addEventListener("abort", cancelled, { once: true });changed();
|
|
@@ -150,12 +185,13 @@ export function createPrivacyModel(options = {}) {
|
|
|
150
185
|
function snapshot() {
|
|
151
186
|
if (!child && !install && ["installed", "not_downloaded"].includes(state.state)) {
|
|
152
187
|
try {
|
|
153
|
-
const
|
|
154
|
-
const
|
|
188
|
+
const runner = candidates().find(([file]) => fsSync.existsSync(file))?.[0];
|
|
189
|
+
const stat = fsSync.lstatSync(runner || paths.runner);
|
|
190
|
+
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
191
|
state = { ...state, state: cached ? "installed" : "not_downloaded" };
|
|
156
192
|
} catch { state = { ...state, state: "not_downloaded" }; }
|
|
157
193
|
}
|
|
158
|
-
return { ...state, pending_checks: jobs.size };
|
|
194
|
+
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
195
|
}
|
|
160
196
|
return { paths, snapshot, installed, download, load, find, stop,
|
|
161
197
|
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 }); },
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHmac } from "node:crypto";
|
|
1
|
+
import { createHash, createHmac } from "node:crypto";
|
|
2
2
|
import { StringDecoder } from "node:string_decoder";
|
|
3
3
|
import { privacyFailure } from "./privacy-model.mjs";
|
|
4
4
|
|
|
@@ -23,7 +23,7 @@ function leaves(value, add, inArguments = false) {
|
|
|
23
23
|
}
|
|
24
24
|
function requestTexts(body, protocol) {
|
|
25
25
|
const items = [], nested = [];
|
|
26
|
-
const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|token)$/i.test(String(key)) }); };
|
|
26
|
+
const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|secret|token)$/i.test(String(key)) }); };
|
|
27
27
|
const text = (parent, key) => { if (typeof parent?.[key] === "string") add(parent, key, parent[key]);else if (Array.isArray(parent?.[key])) for (const block of parent[key]) if (["text", "input_text", "output_text"].includes(block?.type)) add(block, "text", block.text); };
|
|
28
28
|
const args = (parent, key) => {
|
|
29
29
|
if (typeof parent[key] === "string") {
|
|
@@ -69,18 +69,63 @@ function ruleSpans(text, personal) {
|
|
|
69
69
|
}
|
|
70
70
|
return spans;
|
|
71
71
|
}
|
|
72
|
-
export
|
|
72
|
+
export function createPrivacyRuleCache({ maxBytes = 1024 * 1024, maxEntries = 2048 } = {}) {
|
|
73
|
+
const entries = new Map();let bytes = 0, hits = 0, scans = 0;
|
|
74
|
+
return {
|
|
75
|
+
find(text, personal) {
|
|
76
|
+
if (text.length < 256) { scans++;return ruleSpans(text, personal); }
|
|
77
|
+
const key = `${personal ? 1 : 0}:` + createHash("sha256").update(text).digest("hex");
|
|
78
|
+
if (entries.has(key)) {
|
|
79
|
+
const entry = entries.get(key);entries.delete(key);entries.set(key, entry);hits++;
|
|
80
|
+
return entry.spans.map(span => ({ ...span }));
|
|
81
|
+
}
|
|
82
|
+
scans++;const spans = ruleSpans(text, personal), cost = Buffer.byteLength(JSON.stringify(spans)) + 128;
|
|
83
|
+
if (cost <= maxBytes) {
|
|
84
|
+
entries.set(key, { spans: spans.map(span => ({ ...span })), cost });bytes += cost;
|
|
85
|
+
while (entries.size > maxEntries || bytes > maxBytes) { const oldest = entries.keys().next().value;bytes -= entries.get(oldest).cost;entries.delete(oldest); }
|
|
86
|
+
}
|
|
87
|
+
return spans;
|
|
88
|
+
},
|
|
89
|
+
clear() { entries.clear();bytes = 0; },
|
|
90
|
+
stats: () => ({ entries: entries.size, bytes, hits, scans, max_bytes: maxBytes }),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function modelSpanFits(text, start, end, label) {
|
|
94
|
+
const value = text.slice(start, end);
|
|
95
|
+
if (label === "common_secret" && /^\d+$/.test(value)) {
|
|
96
|
+
return /(?:\b(?:api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|password|passwd|passcode|secret|token|pin)|密钥|密码|令牌|口令)["'`]?[\s:=:]*(?:(?:is|was|是|为|為)\s*)?["'`]?$/i.test(text.slice(Math.max(0, start - 96), start));
|
|
97
|
+
}
|
|
98
|
+
if (label === "private_person" && /^[A-Za-z_$][\w$]*$/.test(value)
|
|
99
|
+
&& /\b(?:function|class|const|let|var)\s+$/.test(text.slice(Math.max(0, start - 32), start))) return false;
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
export function validatePrivacyFindings(texts, found) {
|
|
103
|
+
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
104
|
+
return found.map((items, index) => {
|
|
105
|
+
if (items === null) return [];
|
|
106
|
+
if (!Array.isArray(items)) throw privacyFailure("engine_invalid");
|
|
107
|
+
const bytes = Buffer.byteLength(texts[index]);
|
|
108
|
+
for (const span of items) {
|
|
109
|
+
if (!span || !Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start
|
|
110
|
+
|| span.end > bytes || !Number.isFinite(span.score) || span.score < 0 || span.score > 1 || typeof span.label !== "string") throw privacyFailure("engine_invalid");
|
|
111
|
+
}
|
|
112
|
+
return items;
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, rules = ruleSpans }) {
|
|
73
117
|
const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
|
|
74
118
|
if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
75
119
|
const found = texts.length ? await find(texts, { signal }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
|
|
76
120
|
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
77
121
|
for (let i = 0; i < items.length; i++) {
|
|
78
|
-
const item = items[i], bytes = Buffer.from(item.text), spans =
|
|
122
|
+
const item = items[i], bytes = Buffer.from(item.text), spans = rules(item.text, personal);
|
|
79
123
|
if (item.secret) spans.push({ start: 0, end: item.text.length, kind: "secret" });
|
|
80
124
|
for (const span of found[i] || []) {
|
|
81
125
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start || span.end > bytes.length || !Number.isFinite(span.score)) throw privacyFailure("engine_invalid");
|
|
82
126
|
if (span.score < 0.8 || span.label !== "common_secret" && !(personal && personalKinds.has(span.label))) continue;
|
|
83
127
|
const start = bytes.subarray(0, span.start).toString("utf8").length, end = bytes.subarray(0, span.end).toString("utf8").length;
|
|
128
|
+
if (!modelSpanFits(item.text, start, end, span.label)) continue;
|
|
84
129
|
spans.push({ start, end, kind: span.label === "common_secret" ? "secret" : span.label });
|
|
85
130
|
}
|
|
86
131
|
spans.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
@@ -123,14 +168,16 @@ function rewritePrivacyFrame(wire, value, named = false) {
|
|
|
123
168
|
return named && !/^event:/m.test(wire) ? `event: ${value.type}\n${lines}` : lines;
|
|
124
169
|
}
|
|
125
170
|
|
|
126
|
-
export function createPrivacyStream(session) {
|
|
171
|
+
export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 1024, maxChannels = 1024 } = {}) {
|
|
127
172
|
const fail = code => privacyFailure(code, "response");
|
|
128
|
-
let pending = "", bytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
|
|
173
|
+
let pending = "", bytes = 0, bufferedBytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
|
|
174
|
+
const forget = id => { bufferedBytes -= channels.get(id)?.bytes || 0;channels.delete(id); };
|
|
175
|
+
const clear = () => { channels.clear();bufferedBytes = 0; };
|
|
129
176
|
function transform(wire) {
|
|
130
177
|
const data = wire.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
131
178
|
if (!data || data === "[DONE]") return wire;
|
|
132
179
|
let event;try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
|
|
133
|
-
if (["error", "response.failed", "response.incomplete"].includes(event.type)) {
|
|
180
|
+
if (["error", "response.failed", "response.incomplete"].includes(event.type)) { clear();return rewritePrivacyFrame(wire, session.restoreValue(event)); }
|
|
134
181
|
if (["thinking_delta", "signature_delta"].includes(event.delta?.type) || /\.reasoning(?:_|\.)/.test(event.type || "")) return wire;
|
|
135
182
|
const isMessages = event.type === "content_block_delta", delta = isMessages ? event.delta : event;
|
|
136
183
|
const tool = delta?.type === "input_json_delta" || event.type === "response.function_call_arguments.delta";
|
|
@@ -140,18 +187,31 @@ export function createPrivacyStream(session) {
|
|
|
140
187
|
if (tool || text) {
|
|
141
188
|
const field = tool ? isMessages ? "partial_json" : "delta" : isMessages ? "text" : "delta";
|
|
142
189
|
if (typeof delta[field] !== "string") throw fail("stream_invalid");
|
|
143
|
-
const channel = channels.get(key) || { tail: "", tool, field };
|
|
190
|
+
const channel = channels.get(key) || { tail: "", tool, field };
|
|
191
|
+
const last = channel.tail.charCodeAt(channel.tail.length - 1), first = delta[field].charCodeAt(0);
|
|
192
|
+
const joinsPair = last >= 0xD800 && last <= 0xDBFF && first >= 0xDC00 && first <= 0xDFFF;
|
|
193
|
+
const valueBytes = (channel.tailBytes || 0) + Buffer.byteLength(delta[field]) - (joinsPair ? 2 : 0);
|
|
144
194
|
let value = channel.tail + delta[field];
|
|
145
|
-
if (
|
|
146
|
-
if (tool) { channel.tail = value;
|
|
195
|
+
if (valueBytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
196
|
+
if (tool) { channel.tail = value;channel.tailBytes = valueBytes; }
|
|
147
197
|
else {
|
|
148
198
|
let cut = value.length;
|
|
149
199
|
const at = value.lastIndexOf("{{CCDX_");
|
|
150
200
|
if (at >= 0 && !value.slice(at).includes("}}")) cut = at;
|
|
151
201
|
else for (let n = 1; n < TOKEN_START.length; n++) if (value.endsWith(TOKEN_START.slice(0, n))) cut = value.length - n;
|
|
152
202
|
channel.tail = value.slice(cut);delta[field] = session.restoreText(value.slice(0, cut));
|
|
203
|
+
channel.tailBytes = cut === 0 ? valueBytes : Buffer.byteLength(channel.tail);
|
|
153
204
|
}
|
|
154
|
-
|
|
205
|
+
if (tool || channel.tail) {
|
|
206
|
+
// Retain metadata and the unfinished value once, rather than retaining
|
|
207
|
+
// the full latest delta in both the template and its original frame.
|
|
208
|
+
channel.template = isMessages ? { ...event, delta: { ...delta, [field]: "" } } : { ...event, [field]: "" };
|
|
209
|
+
channel.wire = rewritePrivacyFrame(wire, channel.template);
|
|
210
|
+
const cost = channel.tailBytes + Buffer.byteLength(channel.wire) + Buffer.byteLength(JSON.stringify(channel.template));
|
|
211
|
+
bufferedBytes += cost - (channel.bytes || 0);channel.bytes = cost;channels.set(key, channel);
|
|
212
|
+
if (bufferedBytes > maxBufferedBytes || channels.size > maxChannels) throw fail("stream_limit");
|
|
213
|
+
} else forget(key);
|
|
214
|
+
if (tool) return "";
|
|
155
215
|
}
|
|
156
216
|
const stopKey = event.type === "content_block_stop" ? `m:${event.index}` : /\.done$/.test(event.type || "") ? key : null;
|
|
157
217
|
const terminal = ["message_stop", "response.completed", "response.incomplete", "error", "response.failed"].includes(event.type);
|
|
@@ -162,19 +222,26 @@ export function createPrivacyStream(session) {
|
|
|
162
222
|
catch { throw fail("stream_invalid"); }
|
|
163
223
|
before += rewritePrivacyFrame(channel.wire, value, true);
|
|
164
224
|
}
|
|
165
|
-
|
|
225
|
+
forget(id);
|
|
166
226
|
}
|
|
167
227
|
event = session.restoreValue(event);
|
|
168
228
|
return before + rewritePrivacyFrame(wire, event);
|
|
169
229
|
}
|
|
170
230
|
return {
|
|
171
231
|
push(chunk) {
|
|
232
|
+
try {
|
|
172
233
|
pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
173
234
|
let output = "", match;
|
|
174
235
|
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); }
|
|
175
236
|
return output;
|
|
237
|
+
} catch (error) { clear();pending = "";bytes = 0;throw error; }
|
|
238
|
+
},
|
|
239
|
+
finish() {
|
|
240
|
+
try {
|
|
241
|
+
pending += decoder.end();const output = pending ? transform(pending + "\n\n") : "";pending = "";
|
|
242
|
+
if (channels.size) throw fail("stream_incomplete");return output;
|
|
243
|
+
} finally { clear();pending = "";bytes = 0; }
|
|
176
244
|
},
|
|
177
|
-
finish() { pending += decoder.end();if (pending) { const output = transform(pending + "\n\n");pending = "";return output; }if (channels.size) throw fail("stream_incomplete");return ""; },
|
|
178
245
|
};
|
|
179
246
|
}
|
|
180
247
|
|