codex-copilot-dx 1.3.4 → 1.3.6
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 +4 -2
- package/docs/ARCHITECTURE.md +42 -5
- package/docs/README.md +2 -0
- package/docs/REFERENCE.md +31 -2
- package/package.json +1 -1
- package/src/adapter.mjs +13 -8
- package/src/claude-capability-config.mjs +5 -6
- package/src/claude-client-config.mjs +8 -5
- package/src/claude-gateway.mjs +10 -9
- package/src/cli-management.mjs +3 -2
- package/src/client-integration.mjs +1 -1
- package/src/client-model-plan.mjs +10 -0
- package/src/connection-runtime.mjs +31 -9
- package/src/dashboard/connections.js +2 -2
- package/src/dashboard/console.js +2 -0
- package/src/dashboard/index.html +15 -2
- package/src/dashboard/language.js +15 -0
- package/src/dashboard/preferences.js +2 -2
- package/src/dashboard/privacy.js +67 -0
- package/src/dashboard/status.js +3 -1
- package/src/dashboard/ui.css +11 -0
- package/src/dashboard/ui.js +6 -0
- package/src/dashboard-api.mjs +19 -0
- package/src/dashboard.mjs +1 -0
- package/src/local-privacy.mjs +135 -0
- package/src/native-prediction-app.mjs +67 -0
- package/src/native-prediction-fix.mjs +1 -1
- package/src/native-prediction-profile.mjs +2 -36
- package/src/native-prediction-state.mjs +4 -1
- package/src/native-prediction-transport.mjs +21 -7
- package/src/native-prediction-windows.mjs +28 -11
- package/src/native-prediction.mjs +5 -3
- package/src/optional-routes.mjs +2 -2
- package/src/privacy-model.mjs +161 -0
- package/src/privacy-notices.txt +104 -0
- package/src/privacy-transform.mjs +192 -0
- package/src/provider-runtime.mjs +4 -3
- package/src/response-failures.mjs +12 -1
- package/src/responses-handler.mjs +11 -2
- package/src/responses-proxy.mjs +3 -3
- package/src/service-control.mjs +2 -1
- package/src/settings-preferences.mjs +3 -2
- package/src/startup-ui.mjs +1 -1
- package/src/stream-performance.mjs +1 -1
- package/src/terminal-colors.mjs +9 -5
- package/src/usage-analysis.mjs +79 -36
- package/src/usage-analytics.mjs +1 -0
- package/src/usage-store.mjs +21 -11
- package/src/usage.mjs +2 -0
- package/src/user-settings.mjs +3 -3
- package/src/native-prediction-protocol.mjs +0 -45
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
|
+
import { privacyFailure } from "./privacy-model.mjs";
|
|
4
|
+
|
|
5
|
+
const TOKEN_START = "{{CCDX_", tokenPattern = /\{\{CCDX_[a-f0-9]{24}\}\}/g;
|
|
6
|
+
const secretPatterns = [
|
|
7
|
+
/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|AIza[A-Za-z0-9_-]{25,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[A-Z0-9]{16}|hf_[A-Za-z0-9]{20,}|npm_[A-Za-z0-9]{20,})\b/g,
|
|
8
|
+
/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g,
|
|
9
|
+
];
|
|
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
|
+
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"]);
|
|
13
|
+
function leaves(value, add, inArguments = false) {
|
|
14
|
+
if (typeof value === "string") return;
|
|
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
|
+
if (!value || typeof value !== "object") return;
|
|
17
|
+
if (value.encrypted_content || ["thinking", "reasoning"].includes(value.type)) return;
|
|
18
|
+
for (const [key, item] of Object.entries(value)) {
|
|
19
|
+
if (!inArguments && kept.has(key)) continue;
|
|
20
|
+
if (typeof item === "string") add(value, key, item, inArguments);
|
|
21
|
+
else leaves(item, add, inArguments);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function requestTexts(body, protocol) {
|
|
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)) }); };
|
|
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
|
+
const args = (parent, key) => {
|
|
29
|
+
if (typeof parent[key] === "string") {
|
|
30
|
+
try { const value = JSON.parse(parent[key]);leaves(value, add, true);nested.push({ parent, key, value }); }
|
|
31
|
+
catch { throw privacyFailure("arguments_invalid"); }
|
|
32
|
+
} else leaves(parent[key], add, true);
|
|
33
|
+
};
|
|
34
|
+
const descriptions = value => {
|
|
35
|
+
if (!value || typeof value !== "object") return;
|
|
36
|
+
for (const [key, item] of Object.entries(value)) { if (key === "description" && typeof item === "string") add(value, key, item);else if (item && typeof item === "object") descriptions(item); }
|
|
37
|
+
};
|
|
38
|
+
descriptions(body.tools);
|
|
39
|
+
if (protocol === "messages" || protocol === "chat") {
|
|
40
|
+
text(body, "system");
|
|
41
|
+
for (const message of body.messages || []) {
|
|
42
|
+
text(message, "content");
|
|
43
|
+
for (const call of message.tool_calls || []) if (call?.function?.arguments) args(call.function, "arguments");
|
|
44
|
+
if (Array.isArray(message.content)) for (const block of message.content) {
|
|
45
|
+
if (block?.type === "tool_use") args(block, "input");
|
|
46
|
+
if (block?.type === "tool_result") text(block, "content");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
} else {
|
|
50
|
+
text(body, "instructions");
|
|
51
|
+
if (typeof body.input === "string") add(body, "input", body.input);
|
|
52
|
+
else for (const item of body.input || []) {
|
|
53
|
+
if (item.type === "function_call") args(item, "arguments");
|
|
54
|
+
else if (["function_call_output", "custom_tool_call_output"].includes(item.type)) text(item, "output");
|
|
55
|
+
else if (item.type === "custom_tool_call") text(item, "input");
|
|
56
|
+
else text(item, "content");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return { items, nested };
|
|
60
|
+
}
|
|
61
|
+
function ruleSpans(text, personal) {
|
|
62
|
+
const spans = [];
|
|
63
|
+
for (const pattern of secretPatterns) { pattern.lastIndex = 0;for (const m of text.matchAll(pattern)) spans.push({ start: m.index, end: m.index + m[0].length, kind: "secret" }); }
|
|
64
|
+
secretField.lastIndex = 0;
|
|
65
|
+
for (const m of text.matchAll(secretField)) { const at = m.indices[1] || m.indices[2] || m.indices[3];spans.push({ start: at[0], end: at[1], kind: "secret" }); }
|
|
66
|
+
if (personal) for (const m of text.matchAll(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi)) {
|
|
67
|
+
if (!/@(?:example\.(?:com|org|net)|[^@]*\.(?:test|invalid))$/i.test(m[0])) spans.push({ start: m.index, end: m.index + m[0].length, kind: "email" });
|
|
68
|
+
}
|
|
69
|
+
return spans;
|
|
70
|
+
}
|
|
71
|
+
export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal }) {
|
|
72
|
+
const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
|
|
73
|
+
if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
74
|
+
const found = texts.length ? await find(texts, { signal }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
|
|
75
|
+
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
76
|
+
for (let i = 0; i < items.length; i++) {
|
|
77
|
+
const item = items[i], bytes = Buffer.from(item.text), spans = ruleSpans(item.text, personal);
|
|
78
|
+
if (item.secret) spans.push({ start: 0, end: item.text.length, kind: "secret" });
|
|
79
|
+
for (const span of found[i] || []) {
|
|
80
|
+
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");
|
|
81
|
+
if (span.score < 0.8 || span.label !== "common_secret" && !(personal && personalKinds.has(span.label))) continue;
|
|
82
|
+
const start = bytes.subarray(0, span.start).toString("utf8").length, end = bytes.subarray(0, span.end).toString("utf8").length;
|
|
83
|
+
spans.push({ start, end, kind: span.label === "common_secret" ? "secret" : span.label });
|
|
84
|
+
}
|
|
85
|
+
spans.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
86
|
+
let end = 0, output = "";
|
|
87
|
+
for (const span of spans) {
|
|
88
|
+
if (span.start < end) continue;
|
|
89
|
+
const value = item.text.slice(span.start, span.end);
|
|
90
|
+
if (!value || tokenPattern.test(value)) { tokenPattern.lastIndex = 0;continue; }
|
|
91
|
+
tokenPattern.lastIndex = 0;
|
|
92
|
+
const token = `{{CCDX_${createHmac("sha256", secret).update(client + "\0" + value).digest("hex").slice(0, 24)}}}`;
|
|
93
|
+
if (!values.has(token)) { total.bytes += Buffer.byteLength(value);if (values.size >= 8192 || total.bytes > 4 * 1024 * 1024) throw privacyFailure("mapping_limit");values.set(token, value); }
|
|
94
|
+
output += item.text.slice(end, span.start) + token;end = span.end;total.count++;kinds[span.kind] = (kinds[span.kind] || 0) + 1;
|
|
95
|
+
}
|
|
96
|
+
if (end) item.parent[item.key] = output + item.text.slice(end);
|
|
97
|
+
}
|
|
98
|
+
if (total.count) for (const item of nested) item.parent[item.key] = JSON.stringify(item.value);
|
|
99
|
+
const restoreText = text => text.replace(tokenPattern, token => values.get(token) ?? token);
|
|
100
|
+
function restoreValue(value) {
|
|
101
|
+
if (typeof value === "string") return restoreText(value);
|
|
102
|
+
if (Array.isArray(value)) return value.map(restoreValue);
|
|
103
|
+
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, ["signature", "encrypted_content", "thought_signature", "thoughtSignature", "data"].includes(key) ? item
|
|
106
|
+
: key === "arguments" && typeof item === "string" && item ? restoreArguments(item) : restoreValue(item)]));
|
|
107
|
+
}
|
|
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, release: () => values.clear() };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function createPrivacyStream(session) {
|
|
113
|
+
let pending = "", bytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
|
|
114
|
+
const frame = value => `data: ${JSON.stringify(value)}\n\n`;
|
|
115
|
+
function transform(wire) {
|
|
116
|
+
const data = wire.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
117
|
+
if (!data || data === "[DONE]") return wire;
|
|
118
|
+
let event;try { event = JSON.parse(data); } catch { throw privacyFailure("stream_invalid"); }
|
|
119
|
+
if (["thinking_delta", "signature_delta"].includes(event.delta?.type) || /\.reasoning(?:_|\.)/.test(event.type || "")) return wire;
|
|
120
|
+
const isMessages = event.type === "content_block_delta", delta = isMessages ? event.delta : event;
|
|
121
|
+
const tool = delta?.type === "input_json_delta" || event.type === "response.function_call_arguments.delta";
|
|
122
|
+
const text = delta?.type === "text_delta" || event.type === "response.output_text.delta";
|
|
123
|
+
let before = "";
|
|
124
|
+
const key = isMessages ? `m:${event.index}` : `r:${event.item_id || event.item?.id || event.output_index}:${event.content_index || 0}`;
|
|
125
|
+
if (tool || text) {
|
|
126
|
+
const field = tool ? isMessages ? "partial_json" : "delta" : isMessages ? "text" : "delta";
|
|
127
|
+
if (typeof delta[field] !== "string") throw privacyFailure("stream_invalid");
|
|
128
|
+
const channel = channels.get(key) || { tail: "", tool, field, template: event };channel.template = event;
|
|
129
|
+
let value = channel.tail + delta[field];
|
|
130
|
+
if (Buffer.byteLength(value) > 8 * 1024 * 1024) throw privacyFailure("stream_limit");
|
|
131
|
+
if (tool) { channel.tail = value;delta[field] = ""; }
|
|
132
|
+
else {
|
|
133
|
+
let cut = value.length;
|
|
134
|
+
const at = value.lastIndexOf("{{CCDX_");
|
|
135
|
+
if (at >= 0 && !value.slice(at).includes("}}")) cut = at;
|
|
136
|
+
else for (let n = 1; n < TOKEN_START.length; n++) if (value.endsWith(TOKEN_START.slice(0, n))) cut = value.length - n;
|
|
137
|
+
channel.tail = value.slice(cut);delta[field] = session.restoreText(value.slice(0, cut));
|
|
138
|
+
}
|
|
139
|
+
channels.set(key, channel);
|
|
140
|
+
}
|
|
141
|
+
const stopKey = event.type === "content_block_stop" ? `m:${event.index}` : /\.done$/.test(event.type || "") ? key : null;
|
|
142
|
+
const terminal = ["message_stop", "response.completed", "response.incomplete", "error", "response.failed"].includes(event.type);
|
|
143
|
+
for (const [id, channel] of channels) if (terminal || id === stopKey) {
|
|
144
|
+
if (channel.tail) {
|
|
145
|
+
const value = structuredClone(channel.template), target = value.type === "content_block_delta" ? value.delta : value;
|
|
146
|
+
target[channel.field] = channel.tool ? JSON.stringify(session.restoreValue(JSON.parse(channel.tail))) : session.restoreText(channel.tail);
|
|
147
|
+
before += frame(value);
|
|
148
|
+
}
|
|
149
|
+
channels.delete(id);
|
|
150
|
+
}
|
|
151
|
+
event = session.restoreValue(event);
|
|
152
|
+
const lines = wire.split(/\r?\n/);let written = false;
|
|
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;
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
push(chunk) {
|
|
158
|
+
pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw privacyFailure("stream_limit");
|
|
159
|
+
let output = "", match;
|
|
160
|
+
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
|
+
return output;
|
|
162
|
+
},
|
|
163
|
+
finish() { pending += decoder.end();if (pending) { const output = transform(pending + "\n\n");pending = "";return output; }if (channels.size) throw privacyFailure("stream_incomplete");return ""; },
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function protectPrivacyResponse(res, session) {
|
|
168
|
+
if (!session.count) return;
|
|
169
|
+
const write = res.write.bind(res), end = res.end.bind(res), writeHead = res.writeHead.bind(res), stream = createPrivacyStream(session);
|
|
170
|
+
let mode = null, parts = [], size = 0;
|
|
171
|
+
const detach = () => { res.write = write;res.end = end;res.writeHead = writeHead;parts = [];session.release(); };
|
|
172
|
+
res.writeHead = (code, ...args) => {
|
|
173
|
+
const headers = args.find(value => value && typeof value === "object" && !Array.isArray(value));
|
|
174
|
+
if (headers) { const copy = { ...headers };for (const key of Object.keys(copy)) if (key.toLowerCase() === "content-length") delete copy[key];args[args.indexOf(headers)] = copy; }
|
|
175
|
+
res.removeHeader("Content-Length");mode = String(headers?.["Content-Type"] || headers?.["content-type"] || res.getHeader("Content-Type") || "").includes("text/event-stream") ? "stream" : "json";
|
|
176
|
+
return writeHead(code, ...args);
|
|
177
|
+
};
|
|
178
|
+
res.write = (value, encoding, callback) => {
|
|
179
|
+
const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value, typeof encoding === "string" ? encoding : undefined);
|
|
180
|
+
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;
|
|
182
|
+
};
|
|
183
|
+
res.end = (value, encoding, callback) => {
|
|
184
|
+
if (value !== undefined && value !== null) res.write(value, encoding);
|
|
185
|
+
let output;
|
|
186
|
+
if (mode === "stream") { try { output = stream.finish(); }catch (error) { detach();throw error; } }
|
|
187
|
+
else if (parts.length) { const text = Buffer.concat(parts).toString("utf8");try { output = JSON.stringify(session.restoreValue(JSON.parse(text))); }catch { output = session.restoreText(text); }parts = []; }
|
|
188
|
+
return end(output || undefined, typeof encoding === "function" ? encoding : callback);
|
|
189
|
+
};
|
|
190
|
+
const release = () => { session.release();parts = []; };
|
|
191
|
+
res.once("finish", release);res.once("close", release);
|
|
192
|
+
}
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -27,13 +27,14 @@ export function createProviderRuntime(options = {}) {
|
|
|
27
27
|
options = { ...options, corePort: options.corePort ?? Number((options.env || process.env).ADAPTER_PORT || 2026) };
|
|
28
28
|
let connections;
|
|
29
29
|
const legacy = createBuiltinProviderRuntime({ ...options, managedClaude: () => connections?.managesClaude() !== false,
|
|
30
|
+
privacy: { wrap: (fn, context) => connections?.privacy.wrap(fn, context) || fn },
|
|
30
31
|
onClaudeReady: () => connections?.syncSourceClients("m365") });
|
|
31
32
|
connections = createConnectionRuntime({ ...options, legacy });return connections;
|
|
32
33
|
}
|
|
33
34
|
|
|
34
35
|
function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGithubCatalog, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
|
|
35
36
|
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
|
|
36
|
-
discoverM365 = requestM365Accounts, managedClaude, onClaudeReady, preserveClientConfiguration } = {}) {
|
|
37
|
+
discoverM365 = requestM365Accounts, managedClaude, onClaudeReady, preserveClientConfiguration, privacy } = {}) {
|
|
37
38
|
const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
|
|
38
39
|
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
39
40
|
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
@@ -85,7 +86,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
|
|
|
85
86
|
const apiKey = ensureM365GatewayKey({ ...options, create: !preserveClientConfiguration?.() });
|
|
86
87
|
if (!gateway) {
|
|
87
88
|
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
88
|
-
const opened = await start({ provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
|
|
89
|
+
const opened = await start({ privacy, provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
|
|
89
90
|
onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
|
|
90
91
|
if (closed || !enabled) { await opened.close();return null; }
|
|
91
92
|
gateway = opened;
|
|
@@ -152,7 +153,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
|
|
|
152
153
|
if (closed) throw unavailable("m365_runtime_closed");
|
|
153
154
|
if (candidate.models("claude").length) {
|
|
154
155
|
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
155
|
-
opened = await start({ provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log, performance: claudePerformance,
|
|
156
|
+
opened = await start({ privacy, provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log, performance: claudePerformance,
|
|
156
157
|
onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
|
|
157
158
|
}
|
|
158
159
|
candidate.commitSelection(discovered.binding);
|
|
@@ -138,9 +138,13 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
138
138
|
const protocol = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
139
139
|
const capability = createResponseFailureDiagnostics({ maxEntries: 20, now });
|
|
140
140
|
const routes = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
141
|
+
const discovery = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
141
142
|
const counts = { inference: 0, capability: 0, protocol: 0, route: 0, other: 0 };
|
|
142
143
|
return {
|
|
143
144
|
record(details) {
|
|
145
|
+
const probe = isDiscoveryRequest(details.method, details.target) && [404, 405].includes(details.http_status)
|
|
146
|
+
&& details.upstream_attempts === 0;
|
|
147
|
+
if (probe) details = { ...details, request_kind: "discovery" };
|
|
144
148
|
all.record(details);
|
|
145
149
|
const accessNotice = details.reason === "ccdx_model_not_selected" || details.reason === "ccdx_client_source_disabled";
|
|
146
150
|
const category = accessNotice || details.route === "messages_count_tokens" ? "capability"
|
|
@@ -148,6 +152,7 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
148
152
|
: details.route === "image_mcp" && details.http_status === 405 ? "protocol"
|
|
149
153
|
: details.route === "not_found" ? "route" : "other";
|
|
150
154
|
counts[category]++;
|
|
155
|
+
if (probe) { discovery.record(details);return; }
|
|
151
156
|
if ((category === "inference" || category === "other") && !accessNotice) actionable.record(details);
|
|
152
157
|
if (category === "capability") {
|
|
153
158
|
capability.record(details);
|
|
@@ -158,10 +163,16 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
158
163
|
},
|
|
159
164
|
snapshot() { return { ...all.snapshot(), by_category: { ...counts },
|
|
160
165
|
actionable_recent: actionable.snapshot().recent, capability_recent: capability.snapshot().recent,
|
|
161
|
-
protocol_recent: protocol.snapshot().recent, route_recent: routes.snapshot().recent
|
|
166
|
+
protocol_recent: protocol.snapshot().recent, route_recent: routes.snapshot().recent,
|
|
167
|
+
discovery_total: discovery.snapshot().total, discovery_recent: discovery.snapshot().recent }; },
|
|
162
168
|
};
|
|
163
169
|
}
|
|
164
170
|
|
|
171
|
+
export function isDiscoveryRequest(method, pathname) {
|
|
172
|
+
return ["GET", "HEAD"].includes(method) && ["/mcp/image", "/.well-known/oauth-authorization-server",
|
|
173
|
+
"/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname);
|
|
174
|
+
}
|
|
175
|
+
|
|
165
176
|
export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers, model_error,
|
|
166
177
|
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
167
178
|
application, reason, capability_cached, shared_upstream, transport }) {
|
|
@@ -270,6 +270,11 @@ export function createResponsesHandler(options) {
|
|
|
270
270
|
prepared = selected instanceof Promise ? await selected : selected;
|
|
271
271
|
if (prepared.historyParentId === null) releaseHistorySnapshot();
|
|
272
272
|
provider.applyRequestPolicies(prepared.body);
|
|
273
|
+
if (options.privacy) {
|
|
274
|
+
prepared.privacyRestore = value => options.privacy.restoreResponse(res, value);
|
|
275
|
+
responsesFn = options.privacy.wrap(responsesFn, { res, protocol: "responses", client: "codex" });
|
|
276
|
+
chatCompletionsFn = options.privacy.wrap(chatCompletionsFn, { res, protocol: "chat", client: "codex" });
|
|
277
|
+
}
|
|
273
278
|
if (routePlan.protocol === "openai-responses") {
|
|
274
279
|
const restorePlaintextHistory = async (context, { reserveHistory } = {}) => {
|
|
275
280
|
assertPrepareActive();
|
|
@@ -322,7 +327,7 @@ export function createResponsesHandler(options) {
|
|
|
322
327
|
const written = await writeOrDrain(res, `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`, { signal: abort.signal });
|
|
323
328
|
if (!written) return false;
|
|
324
329
|
if (event === "response.completed" || event === "response.incomplete") {
|
|
325
|
-
if (event === "response.completed") rememberResponseHistory(prepared, data.response);
|
|
330
|
+
if (event === "response.completed") rememberResponseHistory(prepared, prepared.privacyRestore?.(data.response) || data.response);
|
|
326
331
|
recordResponsesUsage({ surface: prepared.surface, mode: "stream", model, response: data.response, event: data });
|
|
327
332
|
}
|
|
328
333
|
return true;
|
|
@@ -385,7 +390,7 @@ export function createResponsesHandler(options) {
|
|
|
385
390
|
markResponseTerminal(response.status, {
|
|
386
391
|
model: response.model || model, origin: "chat_completion", reason: response.incomplete_details?.reason,
|
|
387
392
|
});
|
|
388
|
-
rememberResponseHistory(prepared, response);
|
|
393
|
+
rememberResponseHistory(prepared, prepared.privacyRestore?.(response) || response);
|
|
389
394
|
if (response.status === "completed") imagePressure?.markSuccess?.(responseHistoryPressureRootId(prepared));
|
|
390
395
|
recordResponsesUsage({ surface: prepared.surface, mode: "json", model, response, event: response });
|
|
391
396
|
res.writeHead(200, safeUpstreamResponseHeaders(upstream.headers, {
|
|
@@ -553,6 +558,10 @@ export function createResponsesCompactHandler(options) {
|
|
|
553
558
|
prepared = selected instanceof Promise ? await selected : selected;
|
|
554
559
|
releaseHistorySnapshot();
|
|
555
560
|
provider.applyRequestPolicies(prepared.body);
|
|
561
|
+
if (options.privacy) {
|
|
562
|
+
prepared.privacyRestore = value => options.privacy.restoreResponse(res, value);
|
|
563
|
+
responsesCompactFn = options.privacy.wrap(responsesCompactFn, { res, protocol: "responses", client: "codex" });
|
|
564
|
+
}
|
|
556
565
|
const result = await proxyCopilotResponses(prepared, req, res, responsesCompactFn, {
|
|
557
566
|
compatibility: provider.compatibility,
|
|
558
567
|
assertPrepareActive,
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -316,7 +316,7 @@ function parseSuccessfulResponsesResult(text) {
|
|
|
316
316
|
|
|
317
317
|
function storeCompletedResponse(reqContext, completed) {
|
|
318
318
|
if (!completed) return;
|
|
319
|
-
rememberResponseHistory(reqContext, completed.response);
|
|
319
|
+
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(completed.response) || completed.response);
|
|
320
320
|
recordResponsesUsage({
|
|
321
321
|
surface: reqContext.surface,
|
|
322
322
|
mode: "stream",
|
|
@@ -571,7 +571,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
571
571
|
compactionInputWithoutTrigger(reqContext.body.input),
|
|
572
572
|
data,
|
|
573
573
|
);
|
|
574
|
-
rememberResponseHistory(reqContext, response);
|
|
574
|
+
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(response) || response);
|
|
575
575
|
recordResponsesUsage({
|
|
576
576
|
surface: reqContext.surface,
|
|
577
577
|
mode: "json",
|
|
@@ -620,7 +620,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
620
620
|
continue;
|
|
621
621
|
}
|
|
622
622
|
}
|
|
623
|
-
rememberResponseHistory(reqContext, response);
|
|
623
|
+
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(response) || response);
|
|
624
624
|
recordResponsesUsage({
|
|
625
625
|
surface: reqContext.surface,
|
|
626
626
|
mode: "json",
|
package/src/service-control.mjs
CHANGED
|
@@ -18,7 +18,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
18
18
|
try { imageConfigured = Boolean(readImages()); } catch {}
|
|
19
19
|
try { predictionConfigured = readPrediction().enabled === true; } catch {}
|
|
20
20
|
const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
|
|
21
|
-
return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options),
|
|
21
|
+
return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: providerRuntime?.privacy?.snapshot(),
|
|
22
22
|
nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
|
|
23
23
|
effective: {
|
|
24
24
|
terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
|
|
@@ -40,6 +40,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
40
40
|
if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
|
|
41
41
|
const before = nightlyUpdatePreference(options);
|
|
42
42
|
writeSettingsPreferences(input, options);
|
|
43
|
+
if (input.action !== "preferences" || Object.keys(input.values || {}).some(key => key.startsWith("privacy_"))) providerRuntime?.privacy?.settingsChanged();
|
|
43
44
|
const current = settingsPreferencesSnapshot(options).values;
|
|
44
45
|
terminal?.apply?.({ ...servicePreferences(options), theme: current.terminal_animation, color_theme: current.terminal_color_theme });
|
|
45
46
|
if (before !== current.nightly_updates) nightlyChanged(current.nightly_updates);
|
|
@@ -9,7 +9,7 @@ import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-
|
|
|
9
9
|
import { withFileLockSync } from "./lock.mjs";
|
|
10
10
|
|
|
11
11
|
export const SETTINGS_DEFAULTS = Object.freeze({ terminal_color_theme: "green", terminal_animation: DEFAULT_TERMINAL_ANIMATION_THEME,
|
|
12
|
-
terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true });
|
|
12
|
+
terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false });
|
|
13
13
|
const keys = Object.keys(SETTINGS_DEFAULTS);
|
|
14
14
|
const fail = (code, message, statusCode = 409) => Object.assign(new Error(message), { code, statusCode });
|
|
15
15
|
const idValid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
|
|
@@ -30,7 +30,8 @@ function readBackup(options) {
|
|
|
30
30
|
const value = JSON.parse(readBoundedFileSync(settingsBackupPath(options), { encoding: "utf8", maxBytes: 8192 }));
|
|
31
31
|
if (value?.version !== 1 || !idValid(value.id) || typeof value.created_at !== "string" || !Number.isFinite(Date.parse(value.created_at))
|
|
32
32
|
|| Object.keys(value).some(key => !["version", "id", "created_at", "values"].includes(key))
|
|
33
|
-
|| keys.some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
|
|
33
|
+
|| keys.filter(key => !key.startsWith("privacy_")).some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
|
|
34
|
+
value.values = { privacy_enabled: false, privacy_personal: false, ...value.values };
|
|
34
35
|
checkedPreferenceValues(value.values);return value;
|
|
35
36
|
} catch (error) {
|
|
36
37
|
if (error.code === "ENOENT") return null;
|
package/src/startup-ui.mjs
CHANGED
|
@@ -82,7 +82,7 @@ export function predictionStartupCheck(prediction) {
|
|
|
82
82
|
: prediction.active === false ? "Paused; trust and route retained"
|
|
83
83
|
: "Running; suggestion display not verified";
|
|
84
84
|
if (problem) detail += environment === "needs_service_restart" ? "; restart CCDX" : environment === "needs_app_relaunch" ? "; relaunch Codex" : "; environment unavailable";
|
|
85
|
-
const warning = prediction.bridge !== "running" || problem || prediction.launch_route === "unverified";
|
|
85
|
+
const warning = prediction.bridge !== "running" || problem || prediction.launch_route === "unverified" && prediction.client_route !== "observed";
|
|
86
86
|
const lines = [startupCheck(warning ? "warn" : "info", "Suggestions", detail)];
|
|
87
87
|
if (prediction.bridge !== "running" && prediction.reason) lines.push(startupCheck("warn", "Reason", prediction.reason));
|
|
88
88
|
if (warning) lines.push(startupCheck("info", "Details", "ccdx app codex prediction status"));
|
|
@@ -342,7 +342,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
342
342
|
observeContext(values) {
|
|
343
343
|
if (finished || !values || typeof values !== "object") return;
|
|
344
344
|
if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
|
|
345
|
-
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints"]) {
|
|
345
|
+
for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms"]) {
|
|
346
346
|
const value = values[key];
|
|
347
347
|
if (["capability_revision", "capability_constraints"].includes(key)) {
|
|
348
348
|
if (typeof value === "string" && /^[a-z0-9_,]{1,80}$/.test(value)) context[key] = value;continue;
|
package/src/terminal-colors.mjs
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
export const
|
|
1
|
+
export const TERMINAL_COLOR_THEMES = Object.freeze(["green", "klein", "pink", "mono", "orange"]);
|
|
2
|
+
export const isColorTheme = value => TERMINAL_COLOR_THEMES.includes(value);
|
|
2
3
|
|
|
3
4
|
export function terminalColorCode(theme, { output = process.stdout, env = process.env } = {}) {
|
|
4
5
|
if (output.isTTY !== true || Object.hasOwn(env, "NO_COLOR") || env.TERM === "dumb") return "";
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
if (theme === "mono") return "\x1b[39m";
|
|
7
|
+
// Preserve the original green exactly. Other colors adapt to terminal depth.
|
|
8
|
+
if (theme !== "klein" && theme !== "pink" && theme !== "orange") return "\x1b[38;2;166;245;168m";
|
|
7
9
|
const depth = output.getColorDepth?.(env) || (/truecolor|24bit/i.test(env.COLORTERM || "") ? 24 : 4);
|
|
10
|
+
const light = /^(7|15)$/.test(String(env.COLORFGBG || "").split(";").at(-1));
|
|
11
|
+
if (theme === "orange") return depth >= 24 ? light ? "\x1b[38;2;173;77;0m" : "\x1b[38;2;255;154;61m"
|
|
12
|
+
: depth >= 8 ? light ? "\x1b[38;5;130m" : "\x1b[38;5;208m" : light ? "\x1b[33m" : "\x1b[93m";
|
|
8
13
|
if (theme === "pink") {
|
|
9
|
-
const light = /^(7|15)$/.test(String(env.COLORFGBG || "").split(";").at(-1));
|
|
10
14
|
return depth >= 24 ? light ? "\x1b[38;2;168;62;104m" : "\x1b[38;2;243;168;200m"
|
|
11
15
|
: depth >= 8 ? light ? "\x1b[38;5;132m" : "\x1b[38;5;218m" : "\x1b[95m";
|
|
12
16
|
}
|
|
@@ -19,7 +23,7 @@ export function colorTerminalText(text, theme, options) {
|
|
|
19
23
|
}
|
|
20
24
|
|
|
21
25
|
export function colorTerminalMotion(frame, theme, options) {
|
|
22
|
-
if (theme
|
|
26
|
+
if (!isColorTheme(theme) || theme === "green") return frame;
|
|
23
27
|
const code = terminalColorCode(theme, options);
|
|
24
28
|
return frame.replace(/\x1b\[(?:38;5;\d+|97)m/g, code);
|
|
25
29
|
}
|
package/src/usage-analysis.mjs
CHANGED
|
@@ -1,51 +1,94 @@
|
|
|
1
|
-
import
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import { summarizeUsage, summarizeUsageLogs, usageLogPath, usageSummaryVersion, subscribeUsageAppends, usageProvider, mergeUsageSummary } from "./usage-store.mjs";
|
|
2
4
|
import { createUsageAnalytics } from "./usage-analytics.mjs";
|
|
3
5
|
import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
|
|
4
6
|
|
|
5
7
|
const MAX_ENTRIES = 2;
|
|
6
8
|
const MAX_BYTES = 2 * 1024 * 1024;
|
|
7
|
-
const
|
|
8
|
-
const activeReads = createAbortAwareSingleflight();
|
|
9
|
+
const MAX_PENDING_BYTES = 256 * 1024;
|
|
10
|
+
const cache = new Map(), activeReads = createAbortAwareSingleflight();
|
|
11
|
+
let unsubscribe;
|
|
12
|
+
|
|
13
|
+
async function completeLines(file) {
|
|
14
|
+
for (const candidate of [file + ".1", file]) {
|
|
15
|
+
let handle;
|
|
16
|
+
try {
|
|
17
|
+
handle = await fs.open(candidate, "r");const stat = await handle.stat();
|
|
18
|
+
if (!stat.size) continue;
|
|
19
|
+
const byte = Buffer.alloc(1);await handle.read(byte, 0, 1, stat.size - 1);
|
|
20
|
+
if (byte[0] !== 10) return false;
|
|
21
|
+
} catch (error) { if (error.code !== "ENOENT") return false; }
|
|
22
|
+
finally { await handle?.close(); }
|
|
23
|
+
}
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Reuse only appends witnessed inside the writer's existing cross-process lock.
|
|
28
|
+
// External edits, another process's writes and rotations force the normal scan.
|
|
29
|
+
function appendOnly(before, after, bytes) {
|
|
30
|
+
if (!before || !after) return false;
|
|
31
|
+
const a = before.split("\0"), b = after.split("\0");
|
|
32
|
+
if (a.length !== 2 || b.length !== 2 || a[0] !== b[0]) return false;
|
|
33
|
+
const oldFiles = a[1].split("|"), nextFiles = b[1].split("|");
|
|
34
|
+
if (oldFiles.length !== 2 || nextFiles.length !== 2 || oldFiles[0] !== nextFiles[0]) return false;
|
|
35
|
+
const old = oldFiles[1].split(":"), next = nextFiles[1].split(":");
|
|
36
|
+
return next.length === 5 && (oldFiles[1] === "missing" ? Number(next[2]) === bytes
|
|
37
|
+
: old.length === 5 && old[0] === next[0] && old[1] === next[1] && Number(next[2]) === Number(old[2]) + bytes);
|
|
38
|
+
}
|
|
39
|
+
function prune() {
|
|
40
|
+
let bytes = [...cache.values()].reduce((sum, e) => sum + e.bytes + e.pendingBytes, 0);
|
|
41
|
+
for (const [key, entry] of cache) {
|
|
42
|
+
if (bytes <= MAX_BYTES && cache.size <= MAX_ENTRIES) break;
|
|
43
|
+
cache.delete(key);bytes -= entry.bytes + entry.pendingBytes;
|
|
44
|
+
}
|
|
45
|
+
if (!cache.size && unsubscribe) { unsubscribe();unsubscribe = null; }
|
|
46
|
+
}
|
|
47
|
+
function observe() {
|
|
48
|
+
unsubscribe ||= subscribeUsageAppends(change => {
|
|
49
|
+
for (const [key, entry] of cache) {
|
|
50
|
+
if (entry.file !== change.filePath) continue;
|
|
51
|
+
if (entry.version !== change.before || !appendOnly(change.before, change.after, change.bytes)
|
|
52
|
+
|| entry.pendingBytes + change.bytes > MAX_PENDING_BYTES) { cache.delete(key);continue; }
|
|
53
|
+
entry.pending.push(...change.lines);entry.pendingBytes += change.bytes;entry.version = change.after;
|
|
54
|
+
}
|
|
55
|
+
prune();
|
|
56
|
+
});
|
|
57
|
+
}
|
|
9
58
|
|
|
10
|
-
// Only bounded, settled-file aggregates survive. No record index or payload cache.
|
|
11
59
|
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", signal } = {}) {
|
|
12
|
-
const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider });
|
|
13
60
|
const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const key = version === null ? null : `${version}\0${query}`;
|
|
17
|
-
const activeVersion = version === null && warn === console.error ? await usageSummaryVersion(filePath, { settled: false }) : null;
|
|
18
|
-
if (key && cache.has(key)) return structuredClone(await cache.get(key).promise);
|
|
19
|
-
if (key) {
|
|
20
|
-
for (const [old, entry] of cache) if (entry.version !== version) cache.delete(old);
|
|
21
|
-
while (cache.size >= MAX_ENTRIES) cache.delete(cache.keys().next().value);
|
|
22
|
-
} else cache.clear();
|
|
23
|
-
const entry = { version, bytes: 0, promise: null };
|
|
61
|
+
const file = path.resolve(filePath), query = `${file}\0${provider}\0${zone.resolvedOptions().timeZone}\0${zone.format(new Date(now))}`;
|
|
62
|
+
const version = warn === console.error ? await usageSummaryVersion(file, { settled: false }) : null;
|
|
24
63
|
const collect = async () => {
|
|
64
|
+
const cached = version && cache.get(query);
|
|
65
|
+
if (cached?.version === version) {
|
|
66
|
+
cache.delete(query);cache.set(query, cached);
|
|
67
|
+
cached.analytics.advanceTime(now);
|
|
68
|
+
for (const line of cached.pending) {
|
|
69
|
+
const record = JSON.parse(line);
|
|
70
|
+
if (provider && provider !== usageProvider(record)) continue;
|
|
71
|
+
const one = summarizeUsage([record]);mergeUsageSummary(cached.summary, one);cached.analytics.record(record, one);
|
|
72
|
+
}
|
|
73
|
+
cached.pending = [];cached.pendingBytes = 0;
|
|
74
|
+
const result = { summary: cached.summary, analytics: cached.analytics.snapshot() };
|
|
75
|
+
cached.bytes = Buffer.byteLength(JSON.stringify(result));
|
|
76
|
+
if (result.analytics.undated_records > 0) cache.delete(query);
|
|
77
|
+
prune();return result;
|
|
78
|
+
}
|
|
79
|
+
cache.delete(query);prune();
|
|
80
|
+
const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider });
|
|
25
81
|
let warned = false;
|
|
26
|
-
const summary = await summarizeUsageLogs(filePath, {
|
|
27
|
-
|
|
28
|
-
onRecord: analytics.record,
|
|
29
|
-
warn(message) { warned = true; warn(message); },
|
|
30
|
-
});
|
|
82
|
+
const summary = await summarizeUsageLogs(filePath, { provider, onRecord: analytics.record,
|
|
83
|
+
warn(message) { warned = true;warn(message); } });
|
|
31
84
|
const result = { summary, analytics: analytics.snapshot() };
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
let bytes = [...cache.values()].reduce((total, item) => total + item.bytes, 0);
|
|
38
|
-
for (const [old, item] of cache) {
|
|
39
|
-
if (bytes <= MAX_BYTES) break;
|
|
40
|
-
cache.delete(old);
|
|
41
|
-
bytes -= item.bytes;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
85
|
+
const complete = version && await completeLines(file);
|
|
86
|
+
const after = version ? await usageSummaryVersion(file, { settled: false }) : null;
|
|
87
|
+
const bytes = Buffer.byteLength(JSON.stringify(result));
|
|
88
|
+
if (version && complete && after === version && !warned && !result.analytics.undated_records && bytes <= MAX_BYTES) {
|
|
89
|
+
cache.set(query, { file, version, summary, analytics, bytes, pending: [], pendingBytes: 0 });observe();prune();
|
|
44
90
|
}
|
|
45
91
|
return result;
|
|
46
92
|
};
|
|
47
|
-
|
|
48
|
-
if (key) cache.set(key, entry);
|
|
49
|
-
try { return structuredClone(await entry.promise); }
|
|
50
|
-
catch (error) { if (cache.get(key) === entry) cache.delete(key); throw error; }
|
|
93
|
+
return structuredClone(await (version ? activeReads.run(`${version}\0${query}`, collect, { signal }) : collect()));
|
|
51
94
|
}
|
package/src/usage-analytics.mjs
CHANGED
|
@@ -40,6 +40,7 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
return {
|
|
43
|
+
advanceTime(value) { now = value; },
|
|
43
44
|
record(record, summary) {
|
|
44
45
|
const timestamp = typeof record.ts === "string" ? Date.parse(record.ts) : NaN;
|
|
45
46
|
if (!Number.isFinite(timestamp) || timestamp > now) { undated += 1; return; }
|
package/src/usage-store.mjs
CHANGED
|
@@ -25,6 +25,10 @@ let pendingRecords = 0;
|
|
|
25
25
|
let pendingBytes = 0;
|
|
26
26
|
let droppedRecords = 0;
|
|
27
27
|
let writeFailures = 0;
|
|
28
|
+
const appendObservers = new Set();
|
|
29
|
+
export function subscribeUsageAppends(listener) {
|
|
30
|
+
appendObservers.add(listener);return () => appendObservers.delete(listener);
|
|
31
|
+
}
|
|
28
32
|
const runtimeUsage = { since: new Date().toISOString(), records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 };
|
|
29
33
|
const runtimeUsageByProvider = new Map();
|
|
30
34
|
|
|
@@ -155,7 +159,14 @@ async function writeUsageBatch(batch) {
|
|
|
155
159
|
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
156
160
|
await withFileLock(`${path.resolve(filePath)}.lock`, async () => {
|
|
157
161
|
batch.push(...takePendingWrites(filePath, maxBytes));
|
|
162
|
+
const before = appendObservers.size ? await usageSummaryVersion(filePath, { settled: false }) : null;
|
|
158
163
|
await appendRotatingLines(filePath, batch.map(({ line }) => line), maxBytes);
|
|
164
|
+
if (before && appendObservers.size) {
|
|
165
|
+
const after = await usageSummaryVersion(filePath, { settled: false });
|
|
166
|
+
const change = { filePath: path.resolve(filePath), before, after,
|
|
167
|
+
lines: batch.map(entry => entry.line), bytes: batch.reduce((sum, entry) => sum + entry.bytes, 0) };
|
|
168
|
+
for (const listener of appendObservers) { try { listener(change); } catch { /* Analytics cannot fail a log write. */ } }
|
|
169
|
+
}
|
|
159
170
|
}, {
|
|
160
171
|
timeoutMs: USAGE_WRITE_LOCK_TIMEOUT_MS,
|
|
161
172
|
staleMs: USAGE_WRITE_LOCK_STALE_MS,
|
|
@@ -351,22 +362,21 @@ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord
|
|
|
351
362
|
if (provider && provider !== usageProvider(record)) continue;
|
|
352
363
|
const one = summarizeUsage([record]);
|
|
353
364
|
onRecord?.(record, one);
|
|
354
|
-
summary
|
|
355
|
-
addUsageTotals(summary.totals, one.totals);
|
|
356
|
-
addUsageTotals(summary.providers, one.providers);
|
|
357
|
-
for (const [model, values] of Object.entries(one.byModel)) {
|
|
358
|
-
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
359
|
-
addUsageTotals(summary.byModel[model], values);
|
|
360
|
-
}
|
|
361
|
-
for (const [model, values] of Object.entries(one.bySourceModel)) {
|
|
362
|
-
if (!Object.hasOwn(summary.bySourceModel, model)) summary.bySourceModel[model] = {};
|
|
363
|
-
addUsageTotals(summary.bySourceModel[model], values);
|
|
364
|
-
}
|
|
365
|
+
mergeUsageSummary(summary, one);
|
|
365
366
|
}
|
|
366
367
|
}
|
|
367
368
|
return summary;
|
|
368
369
|
}
|
|
369
370
|
|
|
371
|
+
export function mergeUsageSummary(summary, one) {
|
|
372
|
+
summary.requests += one.requests;
|
|
373
|
+
addUsageTotals(summary.totals, one.totals);addUsageTotals(summary.providers, one.providers);
|
|
374
|
+
for (const key of ["byModel", "bySourceModel"]) for (const [model, values] of Object.entries(one[key])) {
|
|
375
|
+
if (!Object.hasOwn(summary[key], model)) Object.defineProperty(summary[key], model, { value: {}, enumerable: true, configurable: true, writable: true });
|
|
376
|
+
addUsageTotals(summary[key][model], values);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
370
380
|
const SUMMARY_CACHE_MAX_BYTES = 256 * 1024;
|
|
371
381
|
const SUMMARY_CACHE_SETTLED_MS = 2000;
|
|
372
382
|
let cachedSummary = null;
|