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
|
@@ -380,7 +380,7 @@
|
|
|
380
380
|
el("connection-client-cancel").disabled = !bindingDirty;
|
|
381
381
|
const body = el("connection-bindings"), c = client(editingClient);body.replaceChildren();
|
|
382
382
|
const available = c.model_plan?.available || [], availableKeys = new Set(available.map(item => bindingKey(item.source, item.id)));
|
|
383
|
-
const missing = [...bindingSelection].filter(key => !availableKeys.has(key)).map(key => { const [source, id] = key.split("\0")
|
|
383
|
+
const missing = [...bindingSelection].filter(key => !availableKeys.has(key)).map(key => { const [source, id] = key.split("\0"), saved = c.model_plan?.unavailable?.find(item => item.source === source && item.id === id);return { source, id, route_id: saved?.route_id, reason: saved?.reason, unavailable: true }; });
|
|
384
384
|
for (const item of [...available, ...missing]) {
|
|
385
385
|
const key = bindingKey(item.source, item.id), row = node("tr"), name = node("td"), capability = item.capability?.values || {};
|
|
386
386
|
const selection = check("binding-model", key, bindingSelection.has(key), item.display_name || item.id);
|
|
@@ -398,7 +398,7 @@
|
|
|
398
398
|
const action = button(bindingDefault === routeId(item) && bindingSelection.has(key) ? "cap_default" : "cap_set_default", () => { bindingDirty = true;bindingSelection.add(key);bindingDefault = routeId(item);rememberDraft();bindingRows({ kind: "default", key }); });
|
|
399
399
|
action.setAttribute("aria-pressed", String(bindingDefault === routeId(item) && bindingSelection.has(key)));
|
|
400
400
|
action.dataset.binding = key;action.disabled = Boolean(item.unavailable);action.setAttribute("aria-label", item.id + " · " + format(bindingDefault === routeId(item) ? "cap_default" : "cap_set_default"));
|
|
401
|
-
if (item.unavailable) { const warning = node("span", undefined, "hint binding-unavailable");words(warning, "cap_model_unavailable");name.append(warning); }
|
|
401
|
+
if (item.unavailable) { const warning = node("span", undefined, "hint binding-unavailable");words(warning, item.reason ? "visibility_" + item.reason : "cap_model_unavailable");name.append(warning); }
|
|
402
402
|
const cell = node("td");cell.append(action);
|
|
403
403
|
const details = [node("td", source(item.source)?.name || item.source), node("td", count(capability.context_window)), node("td", reasoningText(capability))];
|
|
404
404
|
details.forEach((cell, i) => cell.dataset.label = format(["source", "cap_context", "cap_reasoning"][i]));
|
package/src/dashboard/console.js
CHANGED
|
@@ -113,6 +113,7 @@
|
|
|
113
113
|
}
|
|
114
114
|
window.addEventListener("ccdx:providers", () => { syncSources();if (current === "codex") void loadSourceModels(); });
|
|
115
115
|
function applySettings(data, meta) {
|
|
116
|
+
globalThis.ccdxPrivacy?.sync(data.local_privacy);
|
|
116
117
|
settings = data;
|
|
117
118
|
const nightly = data.nightly_update;
|
|
118
119
|
el("nightly-update").checked = nightly?.enabled === true;el("nightly-update").disabled = false;
|
|
@@ -320,6 +321,7 @@
|
|
|
320
321
|
});
|
|
321
322
|
el("auto-refresh").addEventListener("click", schedule);
|
|
322
323
|
el("refresh").addEventListener("click", () => { if (settingsViews.includes(current)) void loadSettings(); });
|
|
324
|
+
document.addEventListener("ccdx:privacy-preferences", event => { if (event.detail?.preferences) preferences?.sync(event.detail);else if (settingsViews.includes(current)) void loadSettings(); });
|
|
323
325
|
window.addEventListener("pagehide", () => { stopped = true;clearTimeout(timer); });
|
|
324
326
|
window.addEventListener("pageshow", () => { stopped = false;schedule(); });
|
|
325
327
|
navigate();schedule();
|
package/src/dashboard/index.html
CHANGED
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
<script src="/console.js" defer></script>
|
|
27
27
|
<script src="/tools.js" defer></script>
|
|
28
28
|
<script src="/connections.js" defer></script>
|
|
29
|
+
<script src="/privacy.js" defer></script>
|
|
29
30
|
<title data-i18n="ccdx_local_dashboard">CCDX · Dashboard</title>
|
|
30
31
|
</head>
|
|
31
32
|
<body>
|
|
@@ -355,7 +356,7 @@
|
|
|
355
356
|
<details class="lower" id="recent-failures" open>
|
|
356
357
|
<summary class="panel-heading"><h2 data-i18n="recent_inference_http_failures">RECENT REQUEST ISSUES</h2><span id="failure-count">requests + events</span></summary>
|
|
357
358
|
<label for="failure-kind" class="sr-only" data-i18n="issue_category">Issue category</label>
|
|
358
|
-
<select id="failure-kind"><option value="issues" data-i18n="issue_replies">Reply issues</option><option value="capability" data-i18n="issue_capabilities">Capability notices</option><option value="connection" data-i18n="issue_connections">Connections and paths</option></select>
|
|
359
|
+
<select id="failure-kind"><option value="issues" data-i18n="issue_replies">Reply issues</option><option value="capability" data-i18n="issue_capabilities">Capability notices</option><option value="connection" data-i18n="issue_connections">Connections and paths</option><option value="discovery" data-i18n="issue_discovery">Service probes</option></select>
|
|
359
360
|
<ol id="failures"><li class="empty" data-i18n="reading_874bf">Reading…</li></ol>
|
|
360
361
|
</details>
|
|
361
362
|
</div>
|
|
@@ -372,7 +373,7 @@
|
|
|
372
373
|
<h2 id="terminal-appearance-title" data-i18n="terminal_appearance">终端外观</h2>
|
|
373
374
|
<div class="appearance-row">
|
|
374
375
|
<div class="appearance-label"><label for="terminal-color-theme" data-i18n="appearance_color_theme">颜色主题</label><p id="terminal-color-note" role="status" data-i18n="appearance_terminal_effect">Table updates now; startup logo next launch.</p></div>
|
|
375
|
-
<select id="terminal-color-theme" disabled class="appearance-select"><option value="green" data-i18n="appearance_classic_green">经典绿(默认)</option><option value="klein" data-i18n="appearance_klein_blue">克莱因蓝</option><option value="pink" data-i18n="appearance_soft_pink">淡粉色</option></select>
|
|
376
|
+
<select id="terminal-color-theme" disabled class="appearance-select"><option value="green" data-i18n="appearance_classic_green">经典绿(默认)</option><option value="klein" data-i18n="appearance_klein_blue">克莱因蓝</option><option value="pink" data-i18n="appearance_soft_pink">淡粉色</option><option value="mono" data-i18n="appearance_black_white">黑白</option><option value="orange" data-i18n="appearance_orange">橙色</option></select>
|
|
376
377
|
</div>
|
|
377
378
|
|
|
378
379
|
<div class="setting-row terminal-animation-toggle"><label for="setting-terminal_animation_enabled" data-i18n="terminal_animation">Terminal animation</label><input id="setting-terminal_animation_enabled" type="checkbox" role="switch" disabled><span id="effect-terminal_animation_enabled" class="hint" role="status"></span></div>
|
|
@@ -436,6 +437,18 @@
|
|
|
436
437
|
<p id="install-windows-policy" class="hint" hidden data-i18n="update_windows_policy">If scripts are blocked, use your company’s approved installation method.</p>
|
|
437
438
|
</details><p id="update-copy-note" class="hint" role="status"></p>
|
|
438
439
|
</section>
|
|
440
|
+
<section class="panel dashboard-section" id="privacy-settings" aria-labelledby="privacy-heading">
|
|
441
|
+
<h2 id="privacy-heading" data-i18n="privacy_heading">ADVANCED</h2>
|
|
442
|
+
<div class="setting-row"><label for="privacy-enabled" data-i18n="privacy_enable">Local masking</label><input id="privacy-enabled" type="checkbox" role="switch" disabled><span id="privacy-status" class="hint" role="status" aria-live="polite"></span></div>
|
|
443
|
+
<p class="hint" data-i18n="privacy_scope">Conversation and tool text. Images and predictions keep their current behavior.</p>
|
|
444
|
+
<div id="privacy-options" hidden>
|
|
445
|
+
<div class="setting-row"><label for="privacy-personal" data-i18n="privacy_personal">Include personal information</label><input id="privacy-personal" type="checkbox" role="switch"><span id="privacy-device" class="hint"></span></div>
|
|
446
|
+
<p class="hint" data-i18n="privacy_personal_hint">Names and addresses may be mistaken for code.</p>
|
|
447
|
+
<details class="privacy-preview"><summary data-i18n="privacy_try">Try locally</summary><label for="privacy-text" data-i18n="privacy_sample">Sample text</label><textarea id="privacy-text" rows="3" maxlength="8192" spellcheck="false"></textarea><div class="section-actions"><button id="privacy-preview" type="button" data-i18n="privacy_check">Check text</button><span id="privacy-preview-count" class="hint" role="status"></span></div><pre id="privacy-result" hidden></pre></details>
|
|
448
|
+
</div>
|
|
449
|
+
<div class="section-actions"><button id="privacy-cancel" type="button" hidden data-i18n="cancel">Cancel</button><button id="privacy-retry" type="button" hidden data-i18n="view_retry">Retry</button><button id="privacy-remove" type="button" hidden data-i18n="privacy_remove">Delete model</button><p id="privacy-error" class="hint" role="alert"></p></div>
|
|
450
|
+
</section>
|
|
451
|
+
<dialog id="privacy-dialog" class="preferences-dialog" aria-labelledby="privacy-dialog-title"><h2 id="privacy-dialog-title" data-i18n="privacy_enable">Local masking</h2><p data-i18n="privacy_download">Downloads about 39 MB plus the local component. Checks may add delay or mistake ordinary text.</p><p data-i18n="privacy_fail_closed">If a check cannot finish, the request is not sent.</p><div class="section-actions"><button id="privacy-dialog-cancel" type="button" data-i18n="cancel">Cancel</button><button id="privacy-dialog-confirm" type="button" data-i18n="privacy_confirm">Download & enable</button></div></dialog>
|
|
439
452
|
<section class="panel dashboard-section" id="settings-preferences" aria-labelledby="preferences-heading">
|
|
440
453
|
<h2 id="preferences-heading" data-i18n="preferences_heading">SAVE & RESTORE</h2>
|
|
441
454
|
<div class="preferences-row"><div><label for="preferences-auto" data-i18n="preferences_auto">Save changes automatically</label><p class="hint" data-i18n="preferences_auto_hint">Valid changes on this page save automatically.</p></div><input id="preferences-auto" type="checkbox" role="switch" disabled checked></div>
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
privacy_heading: ["ADVANCED", "高级"], privacy_enable: ["Local masking", "本地脱敏"], privacy_scope: ["Conversation and tool text. Images and predictions keep their current behavior.", "检查对话和工具文本。图片与预测保持原有行为。"], privacy_state_checking: ["On · checking locally", "已开启 · 本地检查中"],
|
|
4
|
+
privacy_personal: ["Include personal information", "同时保护个人信息"], privacy_personal_hint: ["Names and addresses may be mistaken for code.", "姓名和地址可能与代码混淆。"], privacy_try: ["Try locally", "本地试用"], privacy_sample: ["Sample text", "试用文本"], privacy_check: ["Check text", "检查文本"], privacy_remove: ["Delete model", "删除模型"],
|
|
5
|
+
privacy_download: ["Downloads about 39 MB plus the local component. Checks may add delay or mistake ordinary text.", "下载约 39 MB 模型及本地组件。检查可能增加等待或误识别。"], privacy_fail_closed: ["If a check cannot finish, the request is not sent.", "检查未完成时,请求不会发出。"], privacy_confirm: ["Download & enable", "下载并开启"],
|
|
6
|
+
privacy_state_off: ["Off", "已关闭"], privacy_state_downloading: ["Downloading · {percent}%", "下载中 · {percent}%"], privacy_state_loading: ["Loading locally", "本地加载中"], privacy_state_ready: ["On · keys and passwords", "已开启 · 密钥与密码"], privacy_state_error: ["Not ready", "尚未就绪"], privacy_state_installed: ["Downloaded · off", "已下载 · 已关闭"], privacy_result: ["{count} values masked · {ms} ms", "脱敏 {count} 项 · {ms} ms"],
|
|
7
|
+
privacy_error: ["Check could not finish. Nothing was sent; retry or review these settings.", "检查未完成,未发送请求。请重试或检查设置。"], privacy_download_error: ["Download failed. Check approved download access, proxy and certificates.", "下载失败。请检查下载权限、代理和证书。"], privacy_changed: ["Settings changed elsewhere. Reload this section before trying again.", "设置已在其他窗口修改。请刷新后重试。"], privacy_preview_error: ["Local check failed. No text was sent to a provider.", "本地检查失败。未向模型来源发送文本。"],
|
|
3
8
|
"client_key_encrypted_kept": ["Key kept encrypted; access not checked.", "密钥保持加密,访问未验证。"],
|
|
4
9
|
"context_tabs": ["Usage view", "统计视图"],
|
|
5
10
|
"context_unknown_window": ["Unknown", "未知"],
|
|
@@ -143,6 +148,16 @@
|
|
|
143
148
|
"issue_replies": ["Reply issues", "回复问题"],
|
|
144
149
|
"issue_capabilities": ["Capabilities and access", "能力与访问"],
|
|
145
150
|
"issue_connections": ["Connections and paths", "连接与路径"],
|
|
151
|
+
"issue_discovery": ["Service probes", "连接探测"],
|
|
152
|
+
"appearance_black_white": ["Black & white", "黑白"],
|
|
153
|
+
"appearance_orange": ["Orange", "橙色"],
|
|
154
|
+
"visibility_app_disabled": ["App access is off", "应用接入已关闭"],
|
|
155
|
+
"visibility_source_disabled": ["Source is off", "模型来源已关闭"],
|
|
156
|
+
"visibility_source_not_allowed": ["Source access not granted", "尚未授权此来源"],
|
|
157
|
+
"visibility_model_missing": ["Missing from source catalog", "来源目录暂未提供"],
|
|
158
|
+
"visibility_source_restricted": ["Hidden or restricted by source", "来源隐藏或限制了此模型"],
|
|
159
|
+
"visibility_protocol_unsupported": ["Required interface unavailable", "缺少应用所需接口"],
|
|
160
|
+
"visibility_model_not_selected": ["Not selected for this app", "此应用尚未选择该模型"],
|
|
146
161
|
"http_categories": ["Generation {inference} · Capabilities/access {capability} · Methods {protocol} · Paths {route} · Other {other}", "生成 {inference} · 能力/访问 {capability} · 方法 {protocol} · 路径 {route} · 其他 {other}"],
|
|
147
162
|
"no_upstream_call": ["No upstream call", "未调用上游"],
|
|
148
163
|
"repeated_issue": ["{detail} · {count} occurrences", "{detail} · 出现 {count} 次"],
|
|
@@ -54,10 +54,10 @@
|
|
|
54
54
|
}
|
|
55
55
|
function sync(data, { readVersion } = {}) {
|
|
56
56
|
if (!data.preferences) return;
|
|
57
|
-
terminalMode = data.terminal
|
|
57
|
+
if (data.terminal) terminalMode = data.terminal.mode;
|
|
58
58
|
if (readVersion !== undefined && readVersion !== version || pending) { render();return; }
|
|
59
59
|
const next = data.preferences;
|
|
60
|
-
locks.terminal_animation_enabled = data.effective
|
|
60
|
+
if (data.effective) locks.terminal_animation_enabled = data.effective.terminal_animation_enabled?.locked;
|
|
61
61
|
if (base) for (const key of Object.keys(draft)) {
|
|
62
62
|
if (next.values[key] === draft[key]) delete draft[key];
|
|
63
63
|
else if (next.values[key] !== base.values[key]) { conflict = true;error = "preferences_changed"; }
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const el = id => document.getElementById(id), root = el("privacy-settings");if (!root) return;
|
|
3
|
+
const words = (id, key, values) => globalThis.ccdxLanguage.set(el(id), key, values);
|
|
4
|
+
let state = null, pending = false, timer, pushed = 0;
|
|
5
|
+
const visible = () => !root.closest("[hidden]") && document.visibilityState === "visible";
|
|
6
|
+
function apply(value) {
|
|
7
|
+
const previous = state?.revision;state = value;render();
|
|
8
|
+
if (value.preferences || previous && previous !== state.revision) document.dispatchEvent(new CustomEvent("ccdx:privacy-preferences", { detail: value.preferences ? { preferences: value.preferences } : null }));
|
|
9
|
+
}
|
|
10
|
+
async function request(input) {
|
|
11
|
+
const response = await fetch("/_ccdx/ui/privacy", { method: input ? "POST" : "GET", headers: { "X-CCDX-Dashboard": "1", ...(input ? { "Content-Type": "application/json" } : {}) }, body: input ? JSON.stringify(input) : undefined, signal: AbortSignal.timeout(20000) });
|
|
12
|
+
const data = await response.json();if (!response.ok) throw Object.assign(Error(), { code: data.code });return data;
|
|
13
|
+
}
|
|
14
|
+
function render() {
|
|
15
|
+
if (!state) return;
|
|
16
|
+
const busy = pending || state.action_pending || ["downloading", "loading"].includes(state.state);
|
|
17
|
+
el("privacy-enabled").checked = state.enabled;el("privacy-enabled").disabled = pending || busy && !state.enabled;
|
|
18
|
+
el("privacy-personal").checked = state.personal;el("privacy-personal").disabled = busy;
|
|
19
|
+
el("privacy-options").hidden = !state.enabled || state.state !== "ready";
|
|
20
|
+
el("privacy-cancel").hidden = !busy;el("privacy-cancel").disabled = pending;
|
|
21
|
+
el("privacy-retry").hidden = state.state !== "error" && !state.error;el("privacy-retry").disabled = pending;
|
|
22
|
+
el("privacy-remove").hidden = busy || state.state === "not_downloaded";el("privacy-remove").disabled = pending;
|
|
23
|
+
const status = ["downloading", "loading", "error"].includes(state.state) ? state.state : state.enabled ? state.state === "ready" ? state.pending_checks ? "checking" : "ready" : "error" : state.state === "installed" || state.state === "ready" ? "installed" : "off";
|
|
24
|
+
words("privacy-status", `privacy_state_${status}`, { percent: Math.min(100, Math.round((state.downloaded_bytes || 0) * 100 / Math.max(1, state.download_bytes))) });
|
|
25
|
+
el("privacy-device").textContent = state.backend || "";
|
|
26
|
+
if (state.error) words("privacy-error", state.error.includes("download") ? "privacy_download_error" : "privacy_error");
|
|
27
|
+
else { el("privacy-error").textContent = "";el("privacy-error").removeAttribute("data-i18n"); }
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
if (busy && visible()) timer = setTimeout(() => { if (Date.now() - pushed > 2500) void load();else render(); }, 3000);
|
|
30
|
+
}
|
|
31
|
+
async function load() {
|
|
32
|
+
if (!visible() || pending) return;
|
|
33
|
+
try { apply(await request()); } catch { words("privacy-error", "privacy_error"); }
|
|
34
|
+
}
|
|
35
|
+
async function act(action, extra = {}) {
|
|
36
|
+
if (!state || pending) return;
|
|
37
|
+
pending = true;render();
|
|
38
|
+
try { apply(await request({ action, revision: state.revision, ...extra })); }
|
|
39
|
+
catch (error) { words("privacy-error", error.code === "ccdx_privacy_settings_changed" ? "privacy_changed" : "privacy_error");await load(); }
|
|
40
|
+
finally { pending = false;render(); }
|
|
41
|
+
}
|
|
42
|
+
function enable() { el("privacy-dialog").showModal(); }
|
|
43
|
+
el("privacy-enabled").addEventListener("change", () => {
|
|
44
|
+
if (el("privacy-enabled").checked) { el("privacy-enabled").checked = false;enable(); }
|
|
45
|
+
else void act("disable");
|
|
46
|
+
});
|
|
47
|
+
el("privacy-personal").addEventListener("change", () => void act("personal", { personal: el("privacy-personal").checked }));
|
|
48
|
+
el("privacy-dialog-cancel").addEventListener("click", () => el("privacy-dialog").close());
|
|
49
|
+
el("privacy-dialog-confirm").addEventListener("click", () => { el("privacy-dialog").close();void act("enable"); });
|
|
50
|
+
el("privacy-cancel").addEventListener("click", () => void act("disable"));
|
|
51
|
+
el("privacy-retry").addEventListener("click", () => void act("enable"));
|
|
52
|
+
el("privacy-remove").addEventListener("click", () => void act("remove"));
|
|
53
|
+
el("privacy-preview").addEventListener("click", async () => {
|
|
54
|
+
const trigger = el("privacy-preview");trigger.disabled = true;el("privacy-result").hidden = true;
|
|
55
|
+
try {
|
|
56
|
+
const result = await request({ action: "try", text: el("privacy-text").value });
|
|
57
|
+
el("privacy-result").textContent = result.text;el("privacy-result").hidden = false;
|
|
58
|
+
words("privacy-preview-count", "privacy_result", { count: result.count, ms: result.elapsed_ms });
|
|
59
|
+
} catch { words("privacy-preview-count", "privacy_preview_error"); }
|
|
60
|
+
finally { trigger.disabled = false; }
|
|
61
|
+
});
|
|
62
|
+
document.addEventListener("visibilitychange", () => { clearTimeout(timer);if (visible()) void load(); });
|
|
63
|
+
window.addEventListener("hashchange", () => { clearTimeout(timer);if (visible()) void load(); });
|
|
64
|
+
el("refresh").addEventListener("click", () => void load());
|
|
65
|
+
globalThis.ccdxPrivacy = { sync(value) { if (!value || !visible()) return;pushed = Date.now();apply(value); } };
|
|
66
|
+
void load();
|
|
67
|
+
})();
|
package/src/dashboard/status.js
CHANGED
|
@@ -306,6 +306,7 @@
|
|
|
306
306
|
issues: [...(data.response_failures?.recent || []), ...(data.http_errors?.actionable_recent || data.http_errors?.recent || [])],
|
|
307
307
|
capability: data.http_errors?.capability_recent || [],
|
|
308
308
|
connection: [...(data.http_errors?.protocol_recent || []), ...(data.http_errors?.route_recent || [])],
|
|
309
|
+
discovery: data.http_errors?.discovery_recent || [],
|
|
309
310
|
};
|
|
310
311
|
for (const rows of Object.values(issueGroups)) rows.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));
|
|
311
312
|
issueRequests = recentRequests;
|
|
@@ -382,7 +383,8 @@
|
|
|
382
383
|
const key = String(request.request_id || `${request.at || ""}/${request.provider || ""}/${request.model || ""}`).slice(0, 256);
|
|
383
384
|
details.setAttribute?.("data-request-key", key);details.open = expanded.has(key);
|
|
384
385
|
details.className = "request-details";fields.className = "failure-detail";
|
|
385
|
-
|
|
386
|
+
if (Number.isSafeInteger(context.privacy_count)) globalThis.ccdxLanguage.set(summary, "privacy_result", { count: context.privacy_count, ms: context.privacy_ms || 0 });
|
|
387
|
+
else localize(summary, "request_metadata");details.append(summary, fields);
|
|
386
388
|
for (const [key, value] of [["request_id", request.request_id || "—"], ["http_status", number(request.http_status)], ["attempts", number(request.upstream_attempts)], ["model_outcome", globalThis.ccdxLanguage?.format(outcome.toLowerCase()) || outcome],
|
|
387
389
|
["time", Number.isFinite(at) ? time(at, { date: true }) : "—"],
|
|
388
390
|
["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
|
package/src/dashboard/ui.css
CHANGED
|
@@ -422,6 +422,13 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
422
422
|
--bad:#000; --failed:#000; --incomplete:#000;
|
|
423
423
|
}
|
|
424
424
|
.terminal-sample[data-terminal-palette="pink"] { --sample-logo:#f3a8c8; --sample-table:#f3a8c8; --sample-motion:#f3a8c8; }
|
|
425
|
+
.terminal-sample[data-terminal-palette="orange"] { --sample-logo:#ff9a3d; --sample-table:#ff9a3d; --sample-motion:#ff9a3d; }
|
|
426
|
+
.terminal-sample[data-terminal-palette="mono"] { --sample-bg:#000; --sample-text:#fff; --sample-muted:#aaa; --sample-line:#777; --sample-logo:#fff; --sample-table:#fff; --sample-motion:#fff; }
|
|
427
|
+
:root[data-theme="light"] .terminal-sample[data-terminal-palette="mono"] { --sample-bg:#fff; --sample-text:#000; --sample-muted:#555; --sample-logo:#000; --sample-table:#000; --sample-motion:#000; }
|
|
428
|
+
:root:not([data-theme="light"]) #animation-settings[data-terminal-palette="orange"] { --ansi-white:#ff9a3d;--ansi-159:#ff9a3d;--ansi-123:#ff9a3d;--ansi-87:#ff9a3d;--ansi-51:#ff9a3d;--ansi-45:#ff9a3d;--ansi-39:#ff9a3d;--ansi-33:#ff9a3d; }
|
|
429
|
+
:root[data-theme="light"] #animation-settings[data-terminal-palette="orange"] { --ansi-white:#ad4d00;--ansi-159:#ad4d00;--ansi-123:#ad4d00;--ansi-87:#ad4d00;--ansi-51:#ad4d00;--ansi-45:#ad4d00;--ansi-39:#ad4d00;--ansi-33:#ad4d00; }
|
|
430
|
+
:root:not([data-theme="light"]) #animation-settings[data-terminal-palette="mono"] { --ansi-white:#fff;--ansi-159:#fff;--ansi-123:#fff;--ansi-87:#fff;--ansi-51:#fff;--ansi-45:#fff;--ansi-39:#fff;--ansi-33:#fff; }
|
|
431
|
+
:root[data-theme="light"] #animation-settings[data-terminal-palette="mono"] { --ansi-white:#000;--ansi-159:#000;--ansi-123:#000;--ansi-87:#000;--ansi-51:#000;--ansi-45:#000;--ansi-39:#000;--ansi-33:#000; }
|
|
425
432
|
:root:not([data-theme="light"]) #animation-settings[data-terminal-palette="pink"] { --ansi-white:#f3a8c8;--ansi-159:#f3a8c8;--ansi-123:#f3a8c8;--ansi-87:#f3a8c8;--ansi-51:#f3a8c8;--ansi-45:#f3a8c8;--ansi-39:#f3a8c8;--ansi-33:#f3a8c8; }
|
|
426
433
|
:root[data-theme="light"] #animation-settings[data-terminal-palette="pink"] { --ansi-white:#a83e68;--ansi-159:#a83e68;--ansi-123:#a83e68;--ansi-87:#a83e68;--ansi-51:#a83e68;--ansi-45:#a83e68;--ansi-39:#a83e68;--ansi-33:#a83e68; }
|
|
427
434
|
|
|
@@ -627,6 +634,10 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
627
634
|
#preferences-save, #preferences-dialog-confirm { background:var(--accent); color:var(--page); border-color:var(--accent); }
|
|
628
635
|
.preferences-dialog { width:480px; max-width:calc(100% - 32px); padding:25px; border:1px solid var(--border); border-radius:2px; background:var(--surface); color:var(--text); font:inherit; }
|
|
629
636
|
.preferences-dialog::backdrop { background:#0007; }
|
|
637
|
+
.privacy-preview { margin-top:12px; }
|
|
638
|
+
.privacy-preview label { display:block; margin:12px 0 6px; }
|
|
639
|
+
.privacy-preview textarea { width:100%; box-sizing:border-box; resize:vertical; padding:8px; color:var(--text); background:var(--surface); border:1px solid var(--border); border-radius:2px; font:inherit; }
|
|
640
|
+
.privacy-preview pre { white-space:pre-wrap; overflow-wrap:anywhere; margin:12px 0 0; font-size:12px; }
|
|
630
641
|
.preferences-dialog h2 { font-size:19px; margin:0 0 18px; color:var(--strong); }
|
|
631
642
|
.preferences-dialog p, .preferences-dialog dl { font-size:12px; line-height:1.8; }
|
|
632
643
|
.preferences-dialog dl > div { display:grid; grid-template-columns:80px minmax(0,1fr); gap:12px; margin-top:12px; }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -215,6 +215,11 @@ function applyModels(data, { changed }) {
|
|
|
215
215
|
if (translated) localize(detail, value);else detail.textContent = value;
|
|
216
216
|
fields.append(term, detail);
|
|
217
217
|
}
|
|
218
|
+
for (const item of model.client_visibility || []) if (item.reason) {
|
|
219
|
+
const term = document.createElement("dt"), detail = document.createElement("dd");
|
|
220
|
+
term.textContent = ({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" })[item.client] || item.client;
|
|
221
|
+
localize(detail, "visibility_" + item.reason);fields.append(term, detail);
|
|
222
|
+
}
|
|
218
223
|
row.children[2].append(details);body.append(row);
|
|
219
224
|
}
|
|
220
225
|
if (!data.models.length) emptyTable("live-models-body", 3, "no_models_advertised");
|
|
@@ -421,6 +426,7 @@ let liveCompleted = null;
|
|
|
421
426
|
const liveActivity = globalThis.ccdxLive.create({
|
|
422
427
|
visible: () => document.visibilityState === "visible",
|
|
423
428
|
apply: data => {
|
|
429
|
+
globalThis.ccdxPrivacy?.sync(data.local_privacy);
|
|
424
430
|
renderActivity(data);
|
|
425
431
|
const completed = JSON.stringify([data.instance_id, data.requests?.completed]);
|
|
426
432
|
if (completed !== liveCompleted && globalThis.ccdxContextView?.visible()) void dashboardRefresh.refresh("context", { force: true });
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroup
|
|
|
18
18
|
import { createUsageAnalytics } from "./usage-analytics.mjs";
|
|
19
19
|
import { analyzeUsageLogs } from "./usage-analysis.mjs";
|
|
20
20
|
import { readUserSettings, terminalAnimationPreference, writeTerminalAnimationTheme } from "./user-settings.mjs";
|
|
21
|
+
import { settingsPreferencesSnapshot } from "./settings-preferences.mjs";
|
|
21
22
|
|
|
22
23
|
const ANIMATION_PATH = "/_ccdx/ui/animation";
|
|
23
24
|
const MODELS_PATH = "/_ccdx/ui/models/live";
|
|
@@ -152,6 +153,7 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
152
153
|
updateStatusFn,
|
|
153
154
|
serviceControl,
|
|
154
155
|
applyAnimation,
|
|
156
|
+
privacy,
|
|
155
157
|
tools,
|
|
156
158
|
} = {}) {
|
|
157
159
|
if (!isLoopbackAddress(req.socket?.remoteAddress)
|
|
@@ -165,6 +167,19 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
165
167
|
return;
|
|
166
168
|
}
|
|
167
169
|
|
|
170
|
+
if (pathname === "/_ccdx/ui/privacy") {
|
|
171
|
+
if (!privacy) { sendJson(res, 503, { code: "ccdx_privacy_unavailable" });return; }
|
|
172
|
+
if (req.headers.origin && !sameOrigin(req)) { sendJson(res, 403, { code: "ccdx_privacy_origin_required" });return; }
|
|
173
|
+
if (req.method === "GET") { sendJson(res, 200, { ...privacy.snapshot(), preferences: settingsPreferencesSnapshot({ home, env }) });return; }
|
|
174
|
+
if (req.method !== "POST") { sendJson(res, 405, { error: "Use GET or POST" });return; }
|
|
175
|
+
if (!sameOrigin(req) || !/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { sendJson(res, 403, { code: "ccdx_privacy_origin_required" });return; }
|
|
176
|
+
const abort = createRequestAbort(req, res);abort.setTimeout(5000, "request_body_timeout");
|
|
177
|
+
try {
|
|
178
|
+
const input = await readJsonBody(req, { maxBodyBytes: 16384, maxDecodedBodyBytes: 16384, signal: abort.signal });abort.clearTimeout();
|
|
179
|
+
sendJson(res, 200, { ...await privacy.action(input), preferences: settingsPreferencesSnapshot({ home, env }) });
|
|
180
|
+
} catch (error) { sendJson(res, error.statusCode || 503, { code: /^ccdx_privacy_[a-z_]+$/.test(error.code || "") ? error.code : "ccdx_privacy_unavailable" }); }
|
|
181
|
+
finally { abort.cleanup(); }return;
|
|
182
|
+
}
|
|
168
183
|
if (pathname === "/_ccdx/ui/context") {
|
|
169
184
|
if (req.method !== "GET") { sendJson(res, 405, { error: "Use GET" });return; }
|
|
170
185
|
if (req.headers.origin && !sameOrigin(req)) { sendJson(res, 403, { error: "Context requires the same-origin dashboard" });return; }
|
|
@@ -324,6 +339,10 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
324
339
|
preview: model.preview === true,
|
|
325
340
|
selectable: model.selectable !== false,
|
|
326
341
|
clients: Array.isArray(model.clients) ? model.clients.filter(value => typeof value === "string").slice(0, 8).map(value => safeText(value, 40)) : [],
|
|
342
|
+
client_visibility: Array.isArray(model.client_visibility) ? model.client_visibility.slice(0, 3)
|
|
343
|
+
.filter(value => ["codex", "claude_app", "claude_code"].includes(value?.client) && (value.reason === null
|
|
344
|
+
|| ["app_disabled", "source_disabled", "source_not_allowed", "model_missing", "source_restricted", "protocol_unsupported", "model_not_selected"].includes(value.reason)))
|
|
345
|
+
.map(({ client, reason }) => ({ client, reason })) : [],
|
|
327
346
|
auto_review_efforts: Array.isArray(model.auto_review_efforts) ? model.auto_review_efforts.slice(0, 16).map(value => safeText(value, 16)) : [],
|
|
328
347
|
reasoning_efforts: Array.isArray(model.reasoning_efforts) ? model.reasoning_efforts.slice(0, 16).map(value => safeText(value, 16)) : null,
|
|
329
348
|
state: ["listed", "restricted", "hidden"].includes(model.state) ? model.state : "listed",
|
package/src/dashboard.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";
|
|
|
4
4
|
import { ADAPTER_VERSION } from "./running-adapter.mjs";
|
|
5
5
|
|
|
6
6
|
const ASSETS = new Map([
|
|
7
|
+
["/privacy.js", ["./dashboard/privacy.js", "text/javascript; charset=utf-8"]],
|
|
7
8
|
["/", ["./dashboard/index.html", "text/html; charset=utf-8"]],
|
|
8
9
|
["/ui.css", ["./dashboard/ui.css", "text/css; charset=utf-8"]],
|
|
9
10
|
["/theme.js", ["./dashboard/theme.js", "text/javascript; charset=utf-8"]],
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
4
|
+
import { readUserSettings, userSettingsPath } from "./user-settings.mjs";
|
|
5
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
6
|
+
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
7
|
+
import { createChangeSignal } from "./activity-events.mjs";
|
|
8
|
+
import { createPrivacyModel, privacyFailure } from "./privacy-model.mjs";
|
|
9
|
+
import { maskPrivacyRequest, protectPrivacyResponse } from "./privacy-transform.mjs";
|
|
10
|
+
import { markRequestObservation } from "./stream-performance.mjs";
|
|
11
|
+
|
|
12
|
+
export function createLocalPrivacy(options = {}) {
|
|
13
|
+
const changes = createChangeSignal(), secret = randomBytes(32), cache = new Map(), flights = new Map(), responses = new WeakMap(), policies = new WeakMap();
|
|
14
|
+
const model = options.model || createPrivacyModel({ ...options, changed: changes.changed });
|
|
15
|
+
let cacheBytes = 0, generation = 0, pending = null, disposed = false;
|
|
16
|
+
let keyLoaded = false, actionError = null;
|
|
17
|
+
const settings = () => {
|
|
18
|
+
const saved = readUserSettings({ ...options, strict: true });
|
|
19
|
+
return { enabled: saved.privacy_enabled === true, personal: saved.privacy_personal === true };
|
|
20
|
+
};
|
|
21
|
+
const revision = saved => createHash("sha256").update(JSON.stringify(saved)).digest("hex");
|
|
22
|
+
const snapshot = () => { const saved = settings();return { ...model.snapshot(), ...saved, ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
|
|
23
|
+
function loadKey() {
|
|
24
|
+
if (keyLoaded) return;
|
|
25
|
+
const file = path.join(path.dirname(userSettingsPath(options)), "privacy-key");fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
26
|
+
withFileLockSync(file + ".lock", () => {
|
|
27
|
+
try { const bytes = fs.readFileSync(file);if (bytes.length !== 32) throw privacyFailure("key_invalid");bytes.copy(secret); }
|
|
28
|
+
catch (error) { if (error.code !== "ENOENT") throw error;fs.writeFileSync(file, secret, { mode: 0o600, flag: "wx" }); }
|
|
29
|
+
});keyLoaded = true;
|
|
30
|
+
}
|
|
31
|
+
function save(values, expected) {
|
|
32
|
+
const file = userSettingsPath(options);fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
33
|
+
withFileLockSync(file + ".lock", () => {
|
|
34
|
+
const saved = readUserSettings({ ...options, strict: true });
|
|
35
|
+
if (expected && revision(settings()) !== expected) throw privacyFailure("settings_changed");
|
|
36
|
+
atomicWriteFileIfChangedSync(file, JSON.stringify({ ...saved, ...values }, null, 2) + "\n", { mode: 0o600 });
|
|
37
|
+
});changes.changed();
|
|
38
|
+
}
|
|
39
|
+
async function find(texts, { signal } = {}) {
|
|
40
|
+
const waiting = [], fresh = [], entries = [];
|
|
41
|
+
for (const text of texts) {
|
|
42
|
+
const key = createHash("sha256").update(text).digest("hex");
|
|
43
|
+
if (cache.has(key)) {
|
|
44
|
+
const saved = cache.get(key);cache.delete(key);cache.set(key, saved);waiting.push(Promise.resolve(saved.found));
|
|
45
|
+
} else if (flights.has(key)) waiting.push(flights.get(key).promise);
|
|
46
|
+
else {
|
|
47
|
+
const entry = Promise.withResolvers();entry.key = key;flights.set(key, entry);
|
|
48
|
+
waiting.push(entry.promise);fresh.push(text);entries.push(entry);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (fresh.length) void model.find(fresh).then(found => {
|
|
52
|
+
if (!Array.isArray(found) || found.length !== fresh.length) throw privacyFailure("engine_invalid");
|
|
53
|
+
for (let i = 0; i < found.length; i++) {
|
|
54
|
+
const cost = Buffer.byteLength(JSON.stringify(found[i] || [])) + 128, entry = entries[i];
|
|
55
|
+
if (cost <= 1024 * 1024) {
|
|
56
|
+
const previous = cache.get(entry.key);if (previous) cacheBytes -= previous.bytes;
|
|
57
|
+
cache.set(entry.key, { found: found[i] || [], bytes: cost });cacheBytes += cost;
|
|
58
|
+
while (cache.size > 5000 || cacheBytes > 4 * 1024 * 1024) { const oldest = cache.keys().next().value;cacheBytes -= cache.get(oldest).bytes;cache.delete(oldest); }
|
|
59
|
+
}
|
|
60
|
+
entry.resolve(found[i] || []);
|
|
61
|
+
}
|
|
62
|
+
}).catch(error => entries.forEach(entry => entry.reject(error))).finally(() => entries.forEach(entry => { if (flights.get(entry.key) === entry) flights.delete(entry.key); }));
|
|
63
|
+
let listener;
|
|
64
|
+
const aborted = new Promise((_, reject) => { listener = () => reject(signal.reason);if (signal?.aborted) listener();else signal?.addEventListener("abort", listener, { once: true }); });
|
|
65
|
+
try { return await (signal ? Promise.race([Promise.all(waiting), aborted]) : Promise.all(waiting)); }
|
|
66
|
+
finally { signal?.removeEventListener("abort", listener); }
|
|
67
|
+
}
|
|
68
|
+
async function prepare(body, { protocol, client, signal, res, policy } = {}) {
|
|
69
|
+
const saved = policy || settings();if (!saved.enabled) return body;
|
|
70
|
+
if (disposed) throw privacyFailure("engine_unavailable");
|
|
71
|
+
loadKey();
|
|
72
|
+
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) { if (deadline.aborted && !signal?.aborted) throw privacyFailure("check_timeout");throw error; }
|
|
76
|
+
if (signal?.aborted) { session.release();throw signal.reason; }
|
|
77
|
+
markRequestObservation({ privacy_count: session.count, privacy_ms: Math.round(performance.now() - start), privacy_state: "checked" });
|
|
78
|
+
if (res && session.count) {
|
|
79
|
+
let current = responses.get(res);
|
|
80
|
+
if (!current) {
|
|
81
|
+
const sessions = [];
|
|
82
|
+
current = { count: session.count, sessions,
|
|
83
|
+
restoreText: value => sessions.reduce((text, item) => item.restoreText(text), value),
|
|
84
|
+
restoreValue: value => sessions.reduce((text, item) => item.restoreValue(text), value),
|
|
85
|
+
release: () => { sessions.forEach(item => item.release());sessions.length = 0;responses.delete(res); } };
|
|
86
|
+
responses.set(res, current);sessions.push(session);protectPrivacyResponse(res, current);
|
|
87
|
+
} else current.sessions.push(session);
|
|
88
|
+
}
|
|
89
|
+
return session.body;
|
|
90
|
+
}
|
|
91
|
+
async function action(input) {
|
|
92
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["action", "revision", "personal", "text"].includes(key))) throw privacyFailure("action_invalid");
|
|
93
|
+
if (input.action === "try") {
|
|
94
|
+
if (typeof input.text !== "string" || Buffer.byteLength(input.text) > 8192 || model.snapshot().state !== "ready") throw privacyFailure("preview_unavailable");
|
|
95
|
+
const start = performance.now(), session = await maskPrivacyRequest({ input: input.text }, { protocol: "responses", client: "preview", personal: settings().personal, secret, find });
|
|
96
|
+
const output = { text: session.body.input, count: session.count, elapsed_ms: Math.round(performance.now() - start) };session.release();return output;
|
|
97
|
+
}
|
|
98
|
+
const before = settings();if (input.revision !== revision(before)) throw privacyFailure("settings_changed");
|
|
99
|
+
if (input.action === "personal") {
|
|
100
|
+
if (typeof input.personal !== "boolean") throw privacyFailure("action_invalid");save({ privacy_personal: input.personal }, input.revision);
|
|
101
|
+
} else if (input.action === "disable" || input.action === "remove") {
|
|
102
|
+
generation++;actionError = null;save({ privacy_enabled: false }, input.revision);model.stop();
|
|
103
|
+
if (input.action === "remove") await model.remove();
|
|
104
|
+
} else if (input.action === "enable") {
|
|
105
|
+
if (pending) return snapshot();
|
|
106
|
+
const current = ++generation;
|
|
107
|
+
const work = (async () => {
|
|
108
|
+
actionError = null;loadKey();
|
|
109
|
+
if (!await model.installed()) await model.download();
|
|
110
|
+
if (current !== generation) return;
|
|
111
|
+
await model.load();if (current !== generation) return;
|
|
112
|
+
save({ privacy_enabled: true }, input.revision);
|
|
113
|
+
})();pending = work;
|
|
114
|
+
void work.catch(error => { if (current === generation) actionError = /^ccdx_privacy_[a-z_]+$/.test(error.code || "") ? error.code : "ccdx_privacy_unavailable"; }).finally(() => { if (pending === work) pending = null;changes.changed(); });
|
|
115
|
+
} else throw privacyFailure("action_invalid");
|
|
116
|
+
changes.changed();return snapshot();
|
|
117
|
+
}
|
|
118
|
+
function warm() { const current = generation;if (settings().enabled) void model.load().catch(error => { if (current !== generation || !settings().enabled) return;actionError = /^ccdx_privacy_[a-z_]+$/.test(error.code || "") ? error.code : "ccdx_privacy_unavailable";changes.changed(); }); }
|
|
119
|
+
try { warm(); } catch { /* Invalid preferences remain visible and are never rewritten. */ }
|
|
120
|
+
return { snapshot, action, prepare, subscribe: changes.subscribe, busy: () => Boolean(pending || flights.size || model.busy()),
|
|
121
|
+
wrap(fn, context) {
|
|
122
|
+
if (!fn) return fn;
|
|
123
|
+
const policy = context.res && policies.get(context.res) || settings();if (context.res) policies.set(context.res, policy);
|
|
124
|
+
if (!policy.enabled) return fn;
|
|
125
|
+
return async (body, options = {}) => {
|
|
126
|
+
const masked = await prepare(body, { ...context, policy, signal: options.signal });
|
|
127
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
128
|
+
if (!settings().enabled) model.stop();
|
|
129
|
+
return fn(masked, masked === body ? options : { ...options, bodyText: undefined });
|
|
130
|
+
};
|
|
131
|
+
},
|
|
132
|
+
restoreResponse: (res, value) => responses.get(res)?.restoreValue(value) || value,
|
|
133
|
+
settingsChanged() { actionError = null;if (!settings().enabled) { generation++;model.stop(); }else warm();changes.changed(); },
|
|
134
|
+
close() { disposed = true;generation++;model.close();cache.clear();cacheBytes = 0;secret.fill(0); } };
|
|
135
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { installedWindowsPredictionAppAsync, windowsPredictionProfile } from "./native-prediction-windows.mjs";
|
|
6
|
+
|
|
7
|
+
const execute = promisify(execFile);
|
|
8
|
+
const checks = new WeakMap();
|
|
9
|
+
const stat = file => {
|
|
10
|
+
const value = fs.statSync(file);
|
|
11
|
+
if (!value.isFile()) throw new Error("App identity is not a regular file");
|
|
12
|
+
return { size: value.size, mtimeMs: value.mtimeMs };
|
|
13
|
+
};
|
|
14
|
+
const matches = (file, size, mtimeMs) => {
|
|
15
|
+
const value = stat(file);
|
|
16
|
+
return value.size === size && value.mtimeMs === mtimeMs;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// Installation identity is independent of renderer chunks and prediction
|
|
20
|
+
// implementation strings. Live responses decide whether an overlay applies.
|
|
21
|
+
export async function installedPredictionApp({ exec = execute, platform = process.platform, ...options } = {}) {
|
|
22
|
+
if (platform === "win32") {
|
|
23
|
+
const app = await installedWindowsPredictionAppAsync({ ...options, exec });
|
|
24
|
+
const identity = stat(app.app);
|
|
25
|
+
return { ...app, identity_version: 2, executable: app.app, ...identity,
|
|
26
|
+
profile: windowsPredictionProfile({ app, env: options.env, preferredProfile: options.preferredProfile }) };
|
|
27
|
+
}
|
|
28
|
+
if (platform !== "darwin") throw new Error("Prediction App discovery supports macOS and Windows only");
|
|
29
|
+
for (const app of ["/Applications/ChatGPT.app", "/Applications/Codex.app"]) {
|
|
30
|
+
const metadata = path.join(app, "Contents", "Info.plist");
|
|
31
|
+
if (!fs.existsSync(metadata)) continue;
|
|
32
|
+
const info = stat(metadata);
|
|
33
|
+
const result = await exec("/usr/bin/plutil", ["-convert", "json", "-o", "-", metadata],
|
|
34
|
+
{ encoding: "utf8", timeout: 3000, maxBuffer: 64 * 1024 });
|
|
35
|
+
const parsed = JSON.parse(String(result?.stdout ?? result));
|
|
36
|
+
if (parsed?.CFBundleIdentifier !== "com.openai.codex" || !["ChatGPT", "Codex"].includes(parsed.CFBundleExecutable)) {
|
|
37
|
+
throw new Error("Unknown Codex App identity; prediction setup was preserved");
|
|
38
|
+
}
|
|
39
|
+
const executable = path.join(app, "Contents", "MacOS", parsed.CFBundleExecutable), identity = stat(executable);
|
|
40
|
+
const key = JSON.stringify([app, info, identity]);
|
|
41
|
+
let cache = checks.get(exec);
|
|
42
|
+
if (!cache) { cache = new Map();checks.set(exec, cache); }
|
|
43
|
+
if (!cache.has(key)) {
|
|
44
|
+
while (cache.size >= 2) cache.delete(cache.keys().next().value);
|
|
45
|
+
const pending = (async () => {
|
|
46
|
+
await exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", "-R", '=identifier "com.openai.codex" and anchor apple generic and certificate leaf[subject.OU] = "2DC432GLL2"', app],
|
|
47
|
+
{ encoding: "utf8", timeout: 15_000, maxBuffer: 64 * 1024 });
|
|
48
|
+
if (!matches(metadata, info.size, info.mtimeMs) || !matches(executable, identity.size, identity.mtimeMs)) {
|
|
49
|
+
throw new Error("Codex App changed during identity verification");
|
|
50
|
+
}
|
|
51
|
+
return { app, identity_version: 2, executable, ...identity, metadata,
|
|
52
|
+
metadataSize: info.size, metadataMtimeMs: info.mtimeMs };
|
|
53
|
+
})();
|
|
54
|
+
cache.set(key, pending);
|
|
55
|
+
pending.catch(() => { if (cache.get(key) === pending) cache.delete(key); });
|
|
56
|
+
}
|
|
57
|
+
return { ...await cache.get(key) };
|
|
58
|
+
}
|
|
59
|
+
throw new Error("A registered Codex App was not found; prediction setup was preserved");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function predictionAppMatches(app) {
|
|
63
|
+
try {
|
|
64
|
+
return app?.identity_version === 2 && matches(app.executable, app.size, app.mtimeMs)
|
|
65
|
+
&& (!app.metadata || matches(app.metadata, app.metadataSize, app.metadataMtimeMs));
|
|
66
|
+
} catch { return false; }
|
|
67
|
+
}
|
|
@@ -22,6 +22,6 @@ export async function requestPredictionFix({ host = "127.0.0.1", port = 2026, fe
|
|
|
22
22
|
|| !["running", "stopped", "unavailable", "recovering"].includes(value?.prediction?.bridge)
|
|
23
23
|
|| value.prediction.candidate !== "unknown"
|
|
24
24
|
|| (["ready", "needs_app_relaunch", "route_unverified"].includes(value.status) && value.prediction.bridge !== "running")
|
|
25
|
-
|| (value.status === "ready" && !["verified", "closed"].includes(value.app_route))) throw new Error("Adapter returned an invalid prediction repair result");
|
|
25
|
+
|| (value.status === "ready" && !["verified", "closed"].includes(value.app_route) && value.prediction.client_route !== "observed")) throw new Error("Adapter returned an invalid prediction repair result");
|
|
26
26
|
return value;
|
|
27
27
|
}
|
|
@@ -8,10 +8,9 @@ import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
|
8
8
|
import { userSettingsPath } from "./user-settings.mjs";
|
|
9
9
|
import { resolveNetworkRoute } from "./network-route.mjs";
|
|
10
10
|
import { codexPaths } from "./codex-paths.mjs";
|
|
11
|
-
import { assertWindowsCodexClosed,
|
|
12
|
-
windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
|
|
11
|
+
import { assertWindowsCodexClosed, windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
|
|
13
12
|
import { windowsPredictionCertificate } from "./windows-prediction-certificate.mjs";
|
|
14
|
-
|
|
13
|
+
export { installedPredictionApp, predictionAppMatches } from "./native-prediction-app.mjs";
|
|
15
14
|
|
|
16
15
|
export function predictionPaths({ env = process.env, home = os.homedir(), platform = process.platform, app } = {}) {
|
|
17
16
|
const directory = path.join(path.dirname(userSettingsPath({ env, home })), "native-prediction");
|
|
@@ -59,39 +58,6 @@ export function assertCodexClosed({ exec = execFileSync, platform = process.plat
|
|
|
59
58
|
}
|
|
60
59
|
}
|
|
61
60
|
|
|
62
|
-
export function installedPredictionApp({ exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
63
|
-
const candidates = platform === "win32" ? [installedWindowsPredictionApp({ ...options, exec })]
|
|
64
|
-
: ["/Applications/ChatGPT.app", "/Applications/Codex.app"].map(app => ({ app, archive: path.join(app, "Contents", "Resources", "app.asar") }));
|
|
65
|
-
for (const candidate of candidates) {
|
|
66
|
-
const { app, archive } = candidate;
|
|
67
|
-
if (!fs.existsSync(archive)) continue;
|
|
68
|
-
const inspected = inspectPredictionArchive(archive);
|
|
69
|
-
if (!inspected.compatible) continue;
|
|
70
|
-
if (platform !== "win32") exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
|
|
71
|
-
const stat = fs.statSync(archive);
|
|
72
|
-
if (stat.size !== inspected.size || stat.mtimeMs !== inspected.mtimeMs) throw new Error("Codex App changed during compatibility verification");
|
|
73
|
-
if (platform === "win32") {
|
|
74
|
-
const executable = fs.statSync(app);
|
|
75
|
-
return { ...candidate, profile: windowsPredictionProfile({ app: candidate, env: options.env, preferredProfile: options.preferredProfile }),
|
|
76
|
-
size: stat.size, mtimeMs: stat.mtimeMs, executableSize: executable.size, executableMtimeMs: executable.mtimeMs };
|
|
77
|
-
}
|
|
78
|
-
return { app, archive, size: stat.size, mtimeMs: stat.mtimeMs };
|
|
79
|
-
}
|
|
80
|
-
throw new Error("This Codex App does not expose the verified native prediction protocol; setup was skipped");
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function predictionAppMatches(app) {
|
|
84
|
-
try {
|
|
85
|
-
const stat = fs.statSync(app.archive);
|
|
86
|
-
if (app.executableSize !== undefined) {
|
|
87
|
-
const executable = fs.statSync(app.app);
|
|
88
|
-
if (executable.size !== app.executableSize || executable.mtimeMs !== app.executableMtimeMs) return false;
|
|
89
|
-
}
|
|
90
|
-
return stat.size === app.size && stat.mtimeMs === app.mtimeMs;
|
|
91
|
-
}
|
|
92
|
-
catch { return false; }
|
|
93
|
-
}
|
|
94
|
-
|
|
95
61
|
function privateDirectory(directory, { platform = process.platform, ...options } = {}) {
|
|
96
62
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
97
63
|
const stat = fs.lstatSync(directory);
|
|
@@ -34,7 +34,10 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
|
|
|
34
34
|
state.configuration[event.route] = { status: event.status, modified: event.changed === true, official: event.official === true };
|
|
35
35
|
} else if (event.type === "tls_error") state.counters.tls_errors++;
|
|
36
36
|
else if (event.type === "upstream_error") state.counters.upstream_errors++;
|
|
37
|
-
if (event.error) state.last_error = { code: event.error.code, source: event.error.source, message: event.error.message, status: event.error.status
|
|
37
|
+
if (event.error) state.last_error = { code: event.error.code, source: event.error.source, message: event.error.message, status: event.error.status,
|
|
38
|
+
...(["request_headers", "response_headers", "response_body", "upstream_request"].includes(event.phase) ? { phase: event.phase } : {}),
|
|
39
|
+
...(["bootstrap", "prediction", "refresh", "passthrough", "upgrade"].includes(event.target) ? { target: event.target } : {}),
|
|
40
|
+
...(event.header_limit === 65536 ? { header_limit: event.header_limit } : {}) };
|
|
38
41
|
},
|
|
39
42
|
snapshot() { return structuredClone(state); },
|
|
40
43
|
};
|