codex-copilot-dx 1.3.11 → 1.3.13
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 +2 -2
- package/docs/ARCHITECTURE.md +13 -7
- package/docs/REFERENCE.md +10 -6
- package/package.json +1 -1
- package/src/cli-command-spec.mjs +1 -1
- package/src/dashboard/console.js +1 -1
- package/src/dashboard/features.js +2 -1
- package/src/dashboard/index.html +6 -7
- package/src/dashboard/language.js +4 -3
- package/src/dashboard/privacy.js +2 -0
- package/src/dashboard/ui.css +4 -4
- package/src/http-transport.mjs +2 -1
- package/src/local-privacy.mjs +32 -72
- package/src/privacy-detection.mjs +130 -0
- package/src/privacy-findings.mjs +16 -0
- package/src/privacy-model.mjs +37 -8
- package/src/privacy-stream.mjs +287 -0
- package/src/privacy-transform.mjs +44 -112
- package/src/stream-performance.mjs +6 -2
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { privacyFailure } from "./privacy-model.mjs";
|
|
3
|
+
import { validatePrivacyFindings } from "./privacy-findings.mjs";
|
|
4
|
+
|
|
5
|
+
export const PRIVACY_BATCH_BYTES = 16 * 1024;
|
|
6
|
+
|
|
7
|
+
// Whole-text memoization remains compatible with older components. The new
|
|
8
|
+
// component reuses its natural token windows, without extra text overlaps.
|
|
9
|
+
export function createPrivacyDetection(model, {
|
|
10
|
+
batchBytes = PRIVACY_BATCH_BYTES, maxCacheBytes = 4 * 1024 * 1024, maxCacheEntries = 5000,
|
|
11
|
+
maxPendingBytes = 16 * 1024 * 1024, maxPendingEntries = 8192, maxConcurrent = 2,
|
|
12
|
+
} = {}) {
|
|
13
|
+
if (!Number.isSafeInteger(batchBytes) || batchBytes < 1) throw new Error("Invalid privacy batch budget");
|
|
14
|
+
if (!Number.isSafeInteger(maxConcurrent) || maxConcurrent < 1 || maxConcurrent > 8) throw new Error("Invalid privacy concurrency budget");
|
|
15
|
+
const cache = new Map(), flights = new Map(), turns = [];
|
|
16
|
+
let cacheBytes = 0, pendingBytes = 0, running = 0, closed = false;
|
|
17
|
+
const stats = { submitted_batches: 0, submitted_bytes: 0, cache_hits: 0, shared_hits: 0, skipped_texts: 0, window_evaluations: 0, window_hits: 0, window_shared: 0, cpu_batch_groups: 0, cpu_batch_windows: 0 };
|
|
18
|
+
const copy = value => value.map(span => ({ ...span }));
|
|
19
|
+
function get(key) {
|
|
20
|
+
const entry = cache.get(key);if (!entry) return undefined;
|
|
21
|
+
cache.delete(key);cache.set(key, entry);stats.cache_hits++;return copy(entry.found);
|
|
22
|
+
}
|
|
23
|
+
function put(key, found) {
|
|
24
|
+
if (closed) return;
|
|
25
|
+
const bytes = Buffer.byteLength(JSON.stringify(found)) + 128;
|
|
26
|
+
if (bytes > 1024 * 1024 || bytes > maxCacheBytes) return;
|
|
27
|
+
const before = cache.get(key);if (before) cacheBytes -= before.bytes;
|
|
28
|
+
cache.delete(key);cache.set(key, { found: copy(found), bytes });cacheBytes += bytes;
|
|
29
|
+
while (cache.size > maxCacheEntries || cacheBytes > maxCacheBytes) {
|
|
30
|
+
const oldest = cache.keys().next().value;cacheBytes -= cache.get(oldest).bytes;cache.delete(oldest);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function finish(entry, found, error) {
|
|
34
|
+
if (entry.done) return;
|
|
35
|
+
entry.done = true;entry.text = null;entry.batch = null;entry.plans.clear();
|
|
36
|
+
if (flights.get(entry.key) === entry) { flights.delete(entry.key);pendingBytes -= entry.bytes; }
|
|
37
|
+
if (error) entry.reject(error);else entry.resolve(found);
|
|
38
|
+
}
|
|
39
|
+
async function pump() {
|
|
40
|
+
if (running >= maxConcurrent || closed || !turns.length) return;
|
|
41
|
+
running++;const turn = turns.shift(), batch = [];let bytes = 0;
|
|
42
|
+
const lease = { controller: new AbortController(), entries: batch };
|
|
43
|
+
try {
|
|
44
|
+
while (turn.at < turn.entries.length && batch.length < 64) {
|
|
45
|
+
const entry = turn.entries[turn.at];
|
|
46
|
+
if (entry.done) { turn.at++;continue; }
|
|
47
|
+
if (!entry.waiters) { stats.skipped_texts++;finish(entry, null, privacyFailure("cancelled"));turn.at++;continue; }
|
|
48
|
+
if (batch.length && bytes + entry.bytes > batchBytes) break;
|
|
49
|
+
batch.push(entry);bytes += entry.bytes;entry.submitted = true;entry.batch = lease;turn.at++;
|
|
50
|
+
}
|
|
51
|
+
if (batch.length) {
|
|
52
|
+
let submitted = false;
|
|
53
|
+
const onSubmitted = () => { if (!submitted) { submitted = true;stats.submitted_batches++;stats.submitted_bytes += bytes; } };
|
|
54
|
+
const input = batch.map(entry => entry.text), result = await model.find(input, {
|
|
55
|
+
isNeeded: () => batch.some(entry => entry.waiters > 0), workSignal: lease.controller.signal, onSubmitted,
|
|
56
|
+
onWindowWork(work) { stats.window_evaluations += work.evaluated || 0;stats.window_hits += work.hits || 0;stats.window_shared += work.shared || 0;stats.cpu_batch_groups += work.cpu_batch_groups || 0;stats.cpu_batch_windows += work.cpu_batch_windows || 0; },
|
|
57
|
+
onPlan(plan) {
|
|
58
|
+
const entry = batch[plan.text_index];if (!entry || entry.done) return;
|
|
59
|
+
entry.nativePlan = { pending_windows: plan.pending_windows, total_windows: plan.total_windows };
|
|
60
|
+
for (const notify of entry.plans) notify(entry.nativePlan);
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
onSubmitted();const found = validatePrivacyFindings(input, result);
|
|
64
|
+
for (let index = 0; index < batch.length; index++) { put(batch[index].key, found[index]);finish(batch[index], found[index]); }
|
|
65
|
+
}
|
|
66
|
+
} catch (error) {
|
|
67
|
+
for (const entry of batch.length ? batch : turn.entries) {
|
|
68
|
+
// A new waiter that joined a canceling native job resumes only after
|
|
69
|
+
// physical acknowledgement; completed native windows remain reusable.
|
|
70
|
+
if (!closed && error.code === "ccdx_privacy_cancelled" && entry.waiters > 0) {
|
|
71
|
+
entry.submitted = false;entry.batch = null;turn.entries.push(entry);
|
|
72
|
+
} else finish(entry, null, error);
|
|
73
|
+
}
|
|
74
|
+
} finally {
|
|
75
|
+
running--;
|
|
76
|
+
if (!closed && turn.at < turn.entries.length) turns.push(turn);
|
|
77
|
+
if (!closed && turns.length) setImmediate(() => { for (let worker = running; worker < maxConcurrent && turns.length; worker++) void pump(); });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async function find(texts, { signal, onPlan } = {}) {
|
|
81
|
+
if (closed) throw privacyFailure("engine_unavailable");if (signal?.aborted) throw signal.reason;
|
|
82
|
+
const staged = new Map(), waiters = new Set(), results = [];let newBytes = 0, waitingBytes = 0;
|
|
83
|
+
for (const text of texts) {
|
|
84
|
+
const key = createHash("sha256").update(text).digest("hex"), known = get(key);
|
|
85
|
+
if (known !== undefined) { results.push(Promise.resolve(known));continue; }
|
|
86
|
+
let entry = flights.get(key) || staged.get(key);
|
|
87
|
+
if (!entry) {
|
|
88
|
+
entry = Promise.withResolvers();Object.assign(entry, { key, text, bytes: Buffer.byteLength(text), waiters: 0, done: false, submitted: false, batch: null, plans: new Set(), nativePlan: null });
|
|
89
|
+
staged.set(key, entry);newBytes += entry.bytes;
|
|
90
|
+
} else stats.shared_hits++;
|
|
91
|
+
if (!waiters.has(entry)) waitingBytes += entry.bytes;
|
|
92
|
+
waiters.add(entry);results.push(entry.promise);
|
|
93
|
+
}
|
|
94
|
+
if (pendingBytes + newBytes > maxPendingBytes || flights.size + staged.size > maxPendingEntries) throw privacyFailure("busy");
|
|
95
|
+
onPlan?.({ pending_bytes: waitingBytes, new_bytes: newBytes, texts: waiters.size });
|
|
96
|
+
if (!waiters.size) {
|
|
97
|
+
const found = await Promise.all(results);
|
|
98
|
+
if (signal?.aborted) throw signal.reason;
|
|
99
|
+
return found;
|
|
100
|
+
}
|
|
101
|
+
for (const entry of staged.values()) { flights.set(entry.key, entry);pendingBytes += entry.bytes; }
|
|
102
|
+
for (const entry of waiters) {
|
|
103
|
+
entry.waiters++;
|
|
104
|
+
if (onPlan) { entry.plans.add(onPlan);if (entry.nativePlan) onPlan(entry.nativePlan); }
|
|
105
|
+
}
|
|
106
|
+
const work = Promise.all(results);
|
|
107
|
+
if (staged.size) { turns.push({ entries: [...staged.values()], at: 0 });void pump(); }
|
|
108
|
+
let listener;
|
|
109
|
+
const aborted = new Promise((_, reject) => { listener = () => reject(signal.reason);if (signal?.aborted) listener();else signal?.addEventListener("abort", listener, { once: true }); });
|
|
110
|
+
try { return await (signal ? Promise.race([work, aborted]) : work); }
|
|
111
|
+
finally {
|
|
112
|
+
signal?.removeEventListener("abort", listener);
|
|
113
|
+
for (const entry of waiters) {
|
|
114
|
+
if (onPlan) entry.plans.delete(onPlan);
|
|
115
|
+
entry.waiters--;const lease = entry.batch;
|
|
116
|
+
if (lease && lease.entries.every(item => !item.waiters)) lease.controller.abort(privacyFailure("cancelled"));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function cancelQueued() {
|
|
121
|
+
for (const entry of flights.values()) if (!entry.submitted) finish(entry, null, privacyFailure("cancelled"));turns.length = 0;
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
find, cancelQueued,
|
|
125
|
+
snapshot: () => ({ ...stats, cache_entries: cache.size, cache_bytes: cacheBytes, pending_texts: flights.size, pending_bytes: pendingBytes,
|
|
126
|
+
max_cache_bytes: maxCacheBytes, max_pending_bytes: maxPendingBytes, batch_bytes: batchBytes, max_concurrent: maxConcurrent }),
|
|
127
|
+
busy: () => running > 0 || flights.size > 0,
|
|
128
|
+
close() { closed = true;cancelQueued();for (const entry of flights.values()) finish(entry, null, privacyFailure("engine_unavailable"));cache.clear();cacheBytes = 0; },
|
|
129
|
+
};
|
|
130
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { privacyFailure } from "./privacy-model.mjs";
|
|
2
|
+
|
|
3
|
+
export function validatePrivacyFindings(texts, found) {
|
|
4
|
+
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
5
|
+
return found.map((items, index) => {
|
|
6
|
+
if (items === null) return [];
|
|
7
|
+
if (!Array.isArray(items)) throw privacyFailure("engine_invalid");
|
|
8
|
+
const bytes = Buffer.from(texts[index]);
|
|
9
|
+
for (const span of items) {
|
|
10
|
+
if (!span || !Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start
|
|
11
|
+
|| span.end > bytes.length || !Number.isFinite(span.score) || span.score < 0 || span.score > 1 || typeof span.label !== "string"
|
|
12
|
+
|| (bytes[span.start] & 0xC0) === 0x80 || span.end < bytes.length && (bytes[span.end] & 0xC0) === 0x80) throw privacyFailure("engine_invalid");
|
|
13
|
+
}
|
|
14
|
+
return items;
|
|
15
|
+
});
|
|
16
|
+
}
|
package/src/privacy-model.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { promisify } from "node:util";
|
|
|
8
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.13";
|
|
12
12
|
export const PRIVACY_COMPONENT_ABI = 1;
|
|
13
13
|
export const PRIVACY_MODEL_FILES = Object.freeze([
|
|
14
14
|
{ name: "model_int8.onnx", bytes: 330781, sha256: "0a070d3113615e33ba3b84d6bd486f663a377c04c4b056e7381732179f51832a" },
|
|
@@ -153,8 +153,27 @@ export function createPrivacyModel(options = {}) {
|
|
|
153
153
|
const part = line.slice(0, end);line = line.slice(end + 1);
|
|
154
154
|
try {
|
|
155
155
|
const value = JSON.parse(part);
|
|
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(() => {}); } }
|
|
157
|
-
else if (jobs.has(value.id)) {
|
|
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, window_cache: value.window_cache === true, window_plan: value.window_plan === true, cancel_between_windows: value.cancel_between_windows === true, cpu_short_batch: value.cpu_short_batch === true, window_cache_entries: Number.isSafeInteger(value.window_cache_entries) ? value.window_cache_entries : null, window_cache_bytes: Number.isSafeInteger(value.window_cache_bytes) ? value.window_cache_bytes : null });resolve();if (componentRelease !== PRIVACY_COMPONENT_RELEASE && !upgradeAttempted) { upgradeAttempted = true;void download({ background: true }).catch(() => {}); } }
|
|
157
|
+
else if (jobs.has(value.id)) {
|
|
158
|
+
const job = jobs.get(value.id);
|
|
159
|
+
if (value.phase === "plan") {
|
|
160
|
+
if (!state.window_plan || !Number.isSafeInteger(value.text_index) || value.text_index < 0 || value.text_index >= job.texts
|
|
161
|
+
|| !Number.isSafeInteger(value.pending_windows) || value.pending_windows < 0 || !Number.isSafeInteger(value.total_windows)
|
|
162
|
+
|| value.total_windows < value.pending_windows) throw privacyFailure("engine_invalid");
|
|
163
|
+
try { job.onPlan?.({ text_index: value.text_index, pending_windows: value.pending_windows, total_windows: value.total_windows }); } catch { /* Planning observations do not own native completion. */ }
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
jobs.delete(value.id);clearTimeout(job.timer);
|
|
167
|
+
if (value.window_work && typeof value.window_work === "object") {
|
|
168
|
+
const work = Object.fromEntries(["evaluated", "hits", "shared", "total", "cpu_batch_groups", "cpu_batch_windows"].filter(key => Number.isSafeInteger(value.window_work[key]) && value.window_work[key] >= 0).map(key => [key, value.window_work[key]]));
|
|
169
|
+
set({ last_window_work: work, window_cache_entries: Number.isSafeInteger(value.window_cache_entries) ? value.window_cache_entries : null,
|
|
170
|
+
window_cache_bytes: Number.isSafeInteger(value.window_cache_bytes) ? value.window_cache_bytes : null });
|
|
171
|
+
job.onWindowWork?.(work);
|
|
172
|
+
}
|
|
173
|
+
if (value.error || value.complete === false) job.reject(privacyFailure(value.error === "cancelled" ? "cancelled" : "engine_invalid"));
|
|
174
|
+
else job.resolve(value.found);
|
|
175
|
+
changed();if (stopped && !jobs.size) stop();
|
|
176
|
+
}
|
|
158
177
|
} catch { fail(); }
|
|
159
178
|
}
|
|
160
179
|
});
|
|
@@ -164,10 +183,12 @@ export function createPrivacyModel(options = {}) {
|
|
|
164
183
|
})().catch(error => { ready = null;throw error; });
|
|
165
184
|
return ready;
|
|
166
185
|
}
|
|
167
|
-
async function find(texts, { signal } = {}) {
|
|
186
|
+
async function find(texts, { signal, isNeeded, onSubmitted, workSignal, cacheWindows, onWindowWork, onPlan } = {}) {
|
|
168
187
|
if (signal?.aborted) throw signal.reason;await load();if (signal?.aborted) throw signal.reason;
|
|
188
|
+
if (isNeeded && !isNeeded()) throw privacyFailure("cancelled");
|
|
169
189
|
if (jobs.size >= 8) throw privacyFailure("busy");
|
|
170
|
-
const id = ++serial, input = JSON.stringify({ id, texts }
|
|
190
|
+
const id = ++serial, input = JSON.stringify({ id, texts, ...(cacheWindows === false ? { cache_windows: false } : {}),
|
|
191
|
+
...(state.window_plan && onPlan ? { plan_windows: true } : {}) }) + "\n";
|
|
171
192
|
if (Buffer.byteLength(input) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
172
193
|
if ([...jobs.values()].reduce((n, job) => n + job.bytes, Buffer.byteLength(input)) > 16 * 1024 * 1024) throw privacyFailure("busy");
|
|
173
194
|
return new Promise((resolve, reject) => {
|
|
@@ -175,10 +196,18 @@ export function createPrivacyModel(options = {}) {
|
|
|
175
196
|
// and byte budget until its actual reply or deadline, never admit an
|
|
176
197
|
// unbounded queue by reporting cancelled native work as already idle.
|
|
177
198
|
const cancelled = () => { if (jobs.has(id)) { jobs.get(id).cancelled = true;signal?.removeEventListener("abort", cancelled);reject(signal?.reason || privacyFailure("cancelled"));changed(); } };
|
|
178
|
-
const
|
|
199
|
+
const cancelWork = () => {
|
|
200
|
+
const job = jobs.get(id);
|
|
201
|
+
if (!job || !state.cancel_between_windows || job.cancelRequested) return;
|
|
202
|
+
job.cancelRequested = true;changed();
|
|
203
|
+
child.stdin.write(JSON.stringify({ cancel_id: id }) + "\n", error => { if (error) fail(); });
|
|
204
|
+
};
|
|
205
|
+
const finish = fn => value => { signal?.removeEventListener("abort", cancelled);workSignal?.removeEventListener("abort", cancelWork);fn(value); };
|
|
179
206
|
const timer = setTimeout(() => { reject(privacyFailure("check_timeout"));fail(); }, 300000);
|
|
180
|
-
jobs.set(id, { resolve: finish(resolve), reject: finish(reject), timer, bytes: Buffer.byteLength(input) });signal?.addEventListener("abort", cancelled, { once: true });changed();
|
|
207
|
+
jobs.set(id, { resolve: finish(resolve), reject: finish(reject), timer, bytes: Buffer.byteLength(input), texts: texts.length, onWindowWork, onPlan });signal?.addEventListener("abort", cancelled, { once: true });changed();
|
|
208
|
+
try { onSubmitted?.(); } catch { /* Submission diagnostics do not own the native job. */ }
|
|
181
209
|
child.stdin.write(input, error => { if (error) fail(); });
|
|
210
|
+
workSignal?.addEventListener("abort", cancelWork, { once: true });if (workSignal?.aborted) cancelWork();
|
|
182
211
|
});
|
|
183
212
|
}
|
|
184
213
|
function stop() { stopped = true;downloadAbort?.abort();if (!jobs.size) { child?.kill();child = null;ready = null;line = "";set({ state: "installed", error: null }); } }
|
|
@@ -191,7 +220,7 @@ export function createPrivacyModel(options = {}) {
|
|
|
191
220
|
state = { ...state, state: cached ? "installed" : "not_downloaded" };
|
|
192
221
|
} catch { state = { ...state, state: "not_downloaded" }; }
|
|
193
222
|
}
|
|
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 };
|
|
223
|
+
return { ...state, component_release: componentRelease, target_component_release: PRIVACY_COMPONENT_RELEASE, pending_checks: jobs.size, cancelled_checks: [...jobs.values()].filter(job => job.cancelled || job.cancelRequested).length };
|
|
195
224
|
}
|
|
196
225
|
return { paths, snapshot, installed, download, load, find, stop,
|
|
197
226
|
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 }); },
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2
|
+
import { privacyFailure } from "./privacy-model.mjs";
|
|
3
|
+
|
|
4
|
+
const START = "{{CCDX_", token = /^\{\{CCDX_[a-f0-9]{24}\}\}/;
|
|
5
|
+
const possible = value => START.startsWith(value)
|
|
6
|
+
|| value.startsWith(START) && /^[a-f0-9]{0,24}\}?$/.test(value.slice(START.length));
|
|
7
|
+
|
|
8
|
+
// Validate streamed JSON without retaining its values. Only container states,
|
|
9
|
+
// a literal position and a number state survive between deltas.
|
|
10
|
+
function jsonState(onRetained) {
|
|
11
|
+
const stack = [];let root = "value", quoted = false, role = "", escape = false, unicode = 0, literal = "", at = 0, number = "", invalid = false;
|
|
12
|
+
const state = () => stack.at(-1)?.state || root;
|
|
13
|
+
const consumeValue = () => {
|
|
14
|
+
const top = stack.at(-1), current = state();
|
|
15
|
+
if (!["value", "array-first", "array-value", "object-value"].includes(current)) { invalid = true;return; }
|
|
16
|
+
if (top) top.state = top.type === "object" ? "object-comma" : "array-comma";else root = "end";
|
|
17
|
+
};
|
|
18
|
+
const numberComplete = () => ["zero", "integer", "fraction", "exponent"].includes(number);
|
|
19
|
+
function read(c) {
|
|
20
|
+
if (invalid) return;
|
|
21
|
+
if (quoted) {
|
|
22
|
+
if (unicode) { if (!/[a-fA-F0-9]/.test(c)) invalid = true;unicode--;return; }
|
|
23
|
+
if (escape) {
|
|
24
|
+
escape = false;if (c === "u") unicode = 4;
|
|
25
|
+
else if (!'"\\/bfnrt'.includes(c)) invalid = true;
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (c === "\\") { escape = true;return; }
|
|
29
|
+
if (c === '"') { quoted = false;if (role === "key") stack.at(-1).state = "object-colon";return; }
|
|
30
|
+
if (c.charCodeAt(0) < 32) invalid = true;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (literal) {
|
|
34
|
+
if (c !== literal[at++]) invalid = true;
|
|
35
|
+
if (at === literal.length) { literal = "";at = 0; }
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (number) {
|
|
39
|
+
if (/\d/.test(c)) {
|
|
40
|
+
if (number === "zero") invalid = true;
|
|
41
|
+
else if (number === "minus") number = c === "0" ? "zero" : "integer";
|
|
42
|
+
else if (number === "dot") number = "fraction";
|
|
43
|
+
else if (number === "e" || number === "sign") number = "exponent";
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (c === "." && ["zero", "integer"].includes(number)) { number = "dot";return; }
|
|
47
|
+
if (/[eE]/.test(c) && ["zero", "integer", "fraction"].includes(number)) { number = "e";return; }
|
|
48
|
+
if (/[+-]/.test(c) && number === "e") { number = "sign";return; }
|
|
49
|
+
if (!numberComplete()) invalid = true;
|
|
50
|
+
number = "";if (invalid) return;
|
|
51
|
+
}
|
|
52
|
+
if (/\s/.test(c)) { if (!" \t\r\n".includes(c)) invalid = true;return; }
|
|
53
|
+
const current = state(), top = stack.at(-1);
|
|
54
|
+
if (c === '"') {
|
|
55
|
+
role = current === "object-first" || current === "object-key" ? "key" : "value";
|
|
56
|
+
if (role === "value") consumeValue();quoted = true;return;
|
|
57
|
+
}
|
|
58
|
+
if (c === "{" || c === "[") {
|
|
59
|
+
consumeValue();onRetained((stack.length + 1) * 64);
|
|
60
|
+
stack.push({ type: c === "{" ? "object" : "array", state: c === "{" ? "object-first" : "array-first" });return;
|
|
61
|
+
}
|
|
62
|
+
if (c === "}" || c === "]") {
|
|
63
|
+
if (!top || top.type !== (c === "}" ? "object" : "array")
|
|
64
|
+
|| ![top.type + "-first", top.type + "-comma"].includes(current)) invalid = true;
|
|
65
|
+
else { stack.pop();onRetained(stack.length * 64); }
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (c === ":") { if (current !== "object-colon") invalid = true;else top.state = "object-value";return; }
|
|
69
|
+
if (c === ",") {
|
|
70
|
+
if (current === "object-comma") top.state = "object-key";
|
|
71
|
+
else if (current === "array-comma") top.state = "array-value";
|
|
72
|
+
else invalid = true;
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (c === "-" || /\d/.test(c)) { consumeValue();number = c === "-" ? "minus" : c === "0" ? "zero" : "integer";return; }
|
|
76
|
+
if ("tfn".includes(c)) { consumeValue();literal = c === "t" ? "true" : c === "f" ? "false" : "null";at = 1;return; }
|
|
77
|
+
invalid = true;
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
read,
|
|
81
|
+
valueString: () => quoted && role === "value" && !escape && !unicode,
|
|
82
|
+
complete: () => !invalid && !quoted && !literal && (!number || numberComplete()) && !stack.length && root === "end",
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// A JSON delta is deliberately not a complete JSON document. Track string
|
|
87
|
+
// boundaries so restored values are escaped once, without buffering arguments.
|
|
88
|
+
function fragments(session, json, onRetained) {
|
|
89
|
+
let tail = "";const parser = json ? jsonState(onRetained) : null;
|
|
90
|
+
return {
|
|
91
|
+
push(delta) {
|
|
92
|
+
const value = tail + delta;tail = "";let output = "";
|
|
93
|
+
for (let at = 0; at < value.length;) {
|
|
94
|
+
const c = value[at];
|
|
95
|
+
if ((!json || parser.valueString()) && c === "{") {
|
|
96
|
+
const rest = value.slice(at), match = token.exec(rest);
|
|
97
|
+
if (match) {
|
|
98
|
+
const restored = session.restoreText ? session.restoreText(match[0]) : match[0];
|
|
99
|
+
output += json ? JSON.stringify(restored).slice(1, -1) : restored;
|
|
100
|
+
at += match[0].length;continue;
|
|
101
|
+
}
|
|
102
|
+
if (possible(rest)) { tail = rest;break; }
|
|
103
|
+
}
|
|
104
|
+
output += c;at++;
|
|
105
|
+
parser?.read(c);
|
|
106
|
+
}
|
|
107
|
+
return output;
|
|
108
|
+
},
|
|
109
|
+
finish() { const value = tail;tail = "";return value; },
|
|
110
|
+
held: () => Boolean(tail),
|
|
111
|
+
complete: () => !json || parser.complete(),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function rewrite(wire, event, named = false) {
|
|
116
|
+
let written = false;
|
|
117
|
+
const output = wire.split(/(?<=\n)/).map(line => {
|
|
118
|
+
if (!line.startsWith("data:")) return line;
|
|
119
|
+
if (written) return "";written = true;
|
|
120
|
+
return "data: " + JSON.stringify(event) + (line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : "");
|
|
121
|
+
}).join("");
|
|
122
|
+
return named && !/^event:/m.test(output) ? "event: " + event.type + "\n" + output : output;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 1024, maxChannels = 1024 } = {}) {
|
|
126
|
+
const decoder = new StringDecoder("utf8"), channels = new Map(), aliases = new Map();
|
|
127
|
+
let pending = "", pendingBytes = 0, bufferedBytes = 0, ended = false, completed = false, lastSequence = -1;
|
|
128
|
+
let eventType = "", channelType = null;
|
|
129
|
+
function fail(code) {
|
|
130
|
+
return Object.assign(privacyFailure(code, "response"), { privacyDiagnostic: {
|
|
131
|
+
privacy_error: "ccdx_privacy_" + code,
|
|
132
|
+
privacy_event_type: /^[a-z0-9_.]{1,80}$/.test(eventType) ? eventType : "unknown",
|
|
133
|
+
privacy_channel_type: channelType || "event",
|
|
134
|
+
privacy_buffered_bytes: bufferedBytes + pendingBytes,
|
|
135
|
+
privacy_terminal_seen: ended ? 1 : 0,
|
|
136
|
+
} });
|
|
137
|
+
}
|
|
138
|
+
function clear() { channels.clear();aliases.clear();bufferedBytes = 0; }
|
|
139
|
+
function baseKey(event) {
|
|
140
|
+
const id = event.item_id ?? event.item?.id;
|
|
141
|
+
if (Number.isSafeInteger(event.output_index) && event.output_index >= 0) {
|
|
142
|
+
const value = "r:i:" + event.output_index;
|
|
143
|
+
if (eventType === "response.output_item.added" && typeof id === "string" && !aliases.has(id)) {
|
|
144
|
+
const bytes = Buffer.byteLength(id) + 128;bufferedBytes += bytes;aliases.set(id, { key: value, bytes });
|
|
145
|
+
if (aliases.size > maxChannels || bufferedBytes > maxBufferedBytes) throw fail("stream_limit");
|
|
146
|
+
}
|
|
147
|
+
return value;
|
|
148
|
+
}
|
|
149
|
+
return aliases.get(id)?.key || "r:id:" + (id || event.call_id || "unknown");
|
|
150
|
+
}
|
|
151
|
+
function key(event) {
|
|
152
|
+
return baseKey(event) + ":c:" + (Number.isSafeInteger(event.content_index) && event.content_index >= 0 ? event.content_index : 0);
|
|
153
|
+
}
|
|
154
|
+
function releaseAliases(base) {
|
|
155
|
+
for (const [alias, entry] of aliases) if (entry.key === base) { bufferedBytes -= entry.bytes;aliases.delete(alias); }
|
|
156
|
+
}
|
|
157
|
+
function forget(id) {
|
|
158
|
+
const channel = channels.get(id);bufferedBytes -= (channel?.bytes || 0) + (channel?.stateBytes || 0);channels.delete(id);
|
|
159
|
+
}
|
|
160
|
+
function emit(wire, event, changed = false, named = false) {
|
|
161
|
+
// Added tail deltas must not repeat a prior sequence number. Without an
|
|
162
|
+
// inserted event the upstream's numbers and frame bytes remain unchanged.
|
|
163
|
+
if (Number.isSafeInteger(event.sequence_number) && event.sequence_number >= 0) {
|
|
164
|
+
const sequence = Math.max(lastSequence + 1, event.sequence_number);
|
|
165
|
+
if (sequence !== event.sequence_number) { event.sequence_number = sequence;changed = true; }
|
|
166
|
+
lastSequence = sequence;
|
|
167
|
+
}
|
|
168
|
+
return changed ? rewrite(wire, event, named) : wire;
|
|
169
|
+
}
|
|
170
|
+
function release(id, snapshot) {
|
|
171
|
+
const channel = channels.get(id);if (!channel) return "";
|
|
172
|
+
channelType = channel.kind;
|
|
173
|
+
if (channel.kind === "json") {
|
|
174
|
+
if (typeof snapshot === "string") {
|
|
175
|
+
try { JSON.parse(snapshot); } catch { throw fail("stream_arguments_invalid"); }
|
|
176
|
+
} else if (!channel.reader.complete()) throw fail("stream_arguments_incomplete");
|
|
177
|
+
}
|
|
178
|
+
let output = "";
|
|
179
|
+
if (channel.template) {
|
|
180
|
+
const event = structuredClone(channel.template), target = event.type === "content_block_delta" ? event.delta : event.item || event;
|
|
181
|
+
target[channel.field] = channel.reader.finish();
|
|
182
|
+
output = emit(channel.wire, event, true, true);
|
|
183
|
+
}
|
|
184
|
+
forget(id);return output;
|
|
185
|
+
}
|
|
186
|
+
function transform(wire) {
|
|
187
|
+
const lines = wire.split(/\r?\n/), data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
188
|
+
if (!data || data === "[DONE]") return wire;
|
|
189
|
+
let event;
|
|
190
|
+
try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
|
|
191
|
+
eventType = typeof event.type === "string" ? event.type : lines.find(line => line.startsWith("event:"))?.slice(6).trim() || "";
|
|
192
|
+
channelType = null;
|
|
193
|
+
if (["thinking_delta", "signature_delta"].includes(event.delta?.type) || /\.reasoning(?:_|\.)/.test(eventType)) return emit(wire, event);
|
|
194
|
+
if (["error", "response.failed", "response.incomplete"].includes(eventType)) {
|
|
195
|
+
ended = true;clear();
|
|
196
|
+
return data.includes(START) ? emit(wire, session.restoreValue(event), true) : emit(wire, event);
|
|
197
|
+
}
|
|
198
|
+
const id = eventType.startsWith("content_block_") ? "m:" + event.index : key(event);
|
|
199
|
+
let target, field, kind, changed = false, before = "";
|
|
200
|
+
if (eventType === "content_block_delta" && event.delta?.type === "input_json_delta") { target = event.delta;field = "partial_json";kind = "json"; }
|
|
201
|
+
else if (eventType === "response.function_call_arguments.delta") { target = event;field = "delta";kind = "json"; }
|
|
202
|
+
else if (eventType === "content_block_delta" && event.delta?.type === "text_delta") { target = event.delta;field = "text";kind = "text"; }
|
|
203
|
+
else if (eventType === "response.output_text.delta" || eventType === "response.custom_tool_call_input.delta") { target = event;field = "delta";kind = "text"; }
|
|
204
|
+
else if (eventType === "response.output_item.added" && event.item?.type === "function_call" && typeof event.item.arguments === "string") { target = event.item;field = "arguments";kind = "json"; }
|
|
205
|
+
else if (eventType === "response.output_item.added" && event.item?.type === "custom_tool_call" && typeof event.item.input === "string") { target = event.item;field = "input";kind = "text"; }
|
|
206
|
+
if (target) {
|
|
207
|
+
channelType = kind;
|
|
208
|
+
if (typeof target[field] !== "string") throw fail("stream_invalid");
|
|
209
|
+
let channel = channels.get(id);
|
|
210
|
+
if (!channel) {
|
|
211
|
+
channel = { kind, rawBytes: 0, last: 0, stateBytes: 0 };
|
|
212
|
+
channel.reader = fragments(session, kind === "json", retained => {
|
|
213
|
+
bufferedBytes += retained - channel.stateBytes;channel.stateBytes = retained;
|
|
214
|
+
if (bufferedBytes > maxBufferedBytes) throw fail("stream_limit");
|
|
215
|
+
});
|
|
216
|
+
channels.set(id, channel);
|
|
217
|
+
if (channels.size > maxChannels) throw fail("stream_limit");
|
|
218
|
+
}
|
|
219
|
+
if (channel.kind !== kind) throw fail("stream_channel_invalid");
|
|
220
|
+
const original = target[field], first = original.charCodeAt(0);
|
|
221
|
+
const joins = channel.last >= 0xD800 && channel.last <= 0xDBFF && first >= 0xDC00 && first <= 0xDFFF;
|
|
222
|
+
channel.rawBytes += Buffer.byteLength(original) - (joins ? 2 : 0);
|
|
223
|
+
if (original.length) channel.last = original.charCodeAt(original.length - 1);
|
|
224
|
+
if (kind === "json" && channel.rawBytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
225
|
+
target[field] = channel.reader.push(original);changed = target[field] !== original;
|
|
226
|
+
bufferedBytes -= channel.bytes || 0;channel.bytes = 0;channel.template = null;
|
|
227
|
+
if (channel.reader.held()) {
|
|
228
|
+
let template = eventType === "content_block_delta" ? { ...event, delta: { ...target, [field]: "" } }
|
|
229
|
+
: target === event.item ? { ...event, item: { ...target, [field]: "" } } : { ...event, [field]: "" };
|
|
230
|
+
if (target === event.item) {
|
|
231
|
+
template = { type: kind === "json" ? "response.function_call_arguments.delta" : "response.custom_tool_call_input.delta",
|
|
232
|
+
item_id: event.item.id, output_index: event.output_index, sequence_number: event.sequence_number, delta: "" };
|
|
233
|
+
field = "delta";
|
|
234
|
+
}
|
|
235
|
+
if (!template.type) template.type = eventType;
|
|
236
|
+
channel.template = template;channel.field = field;
|
|
237
|
+
channel.wire = rewrite(wire.replace(/^event:[^\r\n]*/m, "event: " + template.type), template);
|
|
238
|
+
channel.bytes = 128 + Buffer.byteLength(channel.wire) + Buffer.byteLength(JSON.stringify(template));
|
|
239
|
+
bufferedBytes += channel.bytes;if (bufferedBytes > maxBufferedBytes) throw fail("stream_limit");
|
|
240
|
+
} else if (kind === "text") forget(id);
|
|
241
|
+
} else {
|
|
242
|
+
if (eventType === "response.function_call_arguments.done") before += release(id, event.arguments);
|
|
243
|
+
else if (eventType === "response.output_item.done") {
|
|
244
|
+
const base = baseKey(event);
|
|
245
|
+
for (const [activeId] of channels) if (activeId.startsWith(base + ":c:")) before += release(activeId, event.item?.arguments);
|
|
246
|
+
releaseAliases(base);
|
|
247
|
+
} else if (eventType === "content_block_stop" || eventType === "response.content_part.done"
|
|
248
|
+
|| eventType === "response.output_text.done" || eventType === "response.custom_tool_call_input.done") before += release(id, undefined);
|
|
249
|
+
if (["message_stop", "response.completed"].includes(eventType)) {
|
|
250
|
+
ended = true;completed = true;
|
|
251
|
+
for (const [activeId] of channels) {
|
|
252
|
+
const match = /^r:i:(\d+):c:/.exec(activeId), index = match ? Number(match[1]) : null;
|
|
253
|
+
const item = index !== null ? event.response?.output?.[index] : event.response?.output?.find(value => activeId.startsWith("r:id:" + value.id + ":c:"));
|
|
254
|
+
before += release(activeId, item?.type === "function_call" ? item.arguments : undefined);
|
|
255
|
+
}
|
|
256
|
+
for (const entry of aliases.values()) bufferedBytes -= entry.bytes;aliases.clear();
|
|
257
|
+
}
|
|
258
|
+
if (data.includes(START)) {
|
|
259
|
+
const restored = session.restoreValue(event);
|
|
260
|
+
if (JSON.stringify(restored) !== JSON.stringify(event)) { event = restored;changed = true; }
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return before + emit(wire, event, changed);
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
completed: () => completed,
|
|
267
|
+
push(chunk) {
|
|
268
|
+
try {
|
|
269
|
+
pending += decoder.write(chunk);pendingBytes += chunk.length;
|
|
270
|
+
if (pendingBytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
271
|
+
let output = "", match;
|
|
272
|
+
while ((match = /\r?\n\r?\n/.exec(pending))) {
|
|
273
|
+
const end = match.index + match[0].length, wire = pending.slice(0, end);pending = pending.slice(end);
|
|
274
|
+
pendingBytes = Buffer.byteLength(pending);output += transform(wire);
|
|
275
|
+
}
|
|
276
|
+
return output;
|
|
277
|
+
} catch (error) { completed = false;clear();pending = "";pendingBytes = 0;throw error; }
|
|
278
|
+
},
|
|
279
|
+
finish() {
|
|
280
|
+
try {
|
|
281
|
+
pending += decoder.end();const output = pending ? transform(pending + "\n\n") : "";pending = "";
|
|
282
|
+
if (channels.size) throw fail("stream_incomplete");return output;
|
|
283
|
+
} catch (error) { completed = false;throw error; }
|
|
284
|
+
finally { clear();pending = "";pendingBytes = 0; }
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
}
|