codex-copilot-dx 1.3.9 → 1.3.11

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 CHANGED
@@ -51,6 +51,7 @@ Model availability depends on your account and service. Microsoft 365 also requi
51
51
  | Inspect failures | `ccdx requests --failed` |
52
52
  | Read usage | `ccdx usage` / `ccdx usage --scope run` |
53
53
  | Inspect preferences | `ccdx config show --effective` |
54
+ | Inspect local masking | `ccdx config privacy status` |
54
55
  | Check local setup | `ccdx doctor` |
55
56
 
56
57
  Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; the Web UI supports English and Chinese.
@@ -1060,13 +1060,15 @@ the original full scan. No persistent index, polling or per-token work is added.
1060
1060
 
1061
1061
  `privacy-model.mjs` owns verified, optional downloads and a stdio-only child process. The production npm dependency graph is unchanged. Model files are revision/SHA256 pinned; the executable is verified against the fixed component Release's checksum manifest. The downloader reuses the selected npm's network policy. Startup warms only already-downloaded, explicitly enabled protection; opening Settings never downloads a model.
1062
1062
 
1063
- Disabled calls retain their original provider function and body. Enabled calls await a complete check. A frontend check deadline rejects without contacting the provider; shared native work is bounded and may populate the metadata cache for another waiter. Cancellation does not cancel another request's shared work. Native input, jobs, cache and reply buffers have finite budgets; no prompt or mapping database is introduced. The child inherits only required system environment fields, not API keys or sign-in tokens.
1063
+ Disabled calls retain their original provider function and body. Enabled calls await a complete check. A frontend check deadline rejects without contacting the provider; submitted native work retains its completion promise, admission slot and valid cache result even after the last waiter leaves. Whole-text batches commit results independently. Entries without waiters are skipped before submission, and retries share in-flight entries. Results are validated before entering the cache. Native input, jobs, cache and reply buffers have finite budgets; no prompt or mapping database is introduced. The child inherits only required system environment fields, not API keys or sign-in tokens.
1064
1064
 
1065
- The Magpie-derived Go tokenizer/INT8 classifier is built for four macOS/Windows targets, with native CI inference on each target. macOS can use CoreML and otherwise falls back to CPU; Windows uses CPU. The model remains a separate download. The fixed component version and protocol are independent of a client's model ID and of future CCDX code-only updates.
1065
+ The Magpie-derived Go tokenizer/INT8 classifier is built for four macOS/Windows targets, with native CI inference on each target. macOS can use CoreML and otherwise falls back to CPU; Windows uses CPU. Same-host Intel measurements found native int8 substantially faster for short fields but slower for long windows than the padded CoreML CPU program. Only amd64/CoreML-CPU windows below 128 tokens use native int8; longer windows and all unmeasured devices retain the previous cutoff. The model remains a separate download. The fixed component version and protocol are independent of a client's model ID and of future CCDX code-only updates.
1066
1066
 
1067
1067
  Progress and readiness share the existing coalesced activity SSE. The settings controller only reads status while visible and uses a bounded-action fallback when event updates are absent. Main-page preference revisions are refreshed after masking choices change. Protected request details add replacement count and local-check duration; other request rows retain their current layout.
1068
1068
 
1069
- Local privacy failures carry a separate origin. Request-check and response-restoration messages state different outcomes. Explicit failed tool results in the latest Messages input add only a count to request metadata, without retaining their content or changing a successful model response into a claim of tool-workflow success. SDK tests use independent client parsers; native CLI replays execute a local MCP fixture in temporary profiles, return its result and require the following response to complete.
1069
+ Local privacy failures carry a separate origin. Request-check and response-restoration messages state different outcomes. Local wait duration and checked/failed/cancelled state are bounded request metadata; the latest check and effective model readiness also feed controls. Temporary waits alone receive Retry-After. Explicit failed tool results in the latest Messages input add only a count to request metadata, without retaining their content or changing a successful model response into a claim of tool-workflow success. SDK tests use independent client parsers. Native CLI replays execute a local MCP fixture in temporary homes, return its result and require continuation; the native-detector variant additionally exercises an injected wait deadline and cached recovery using the actual component.
1070
+
1071
+ Stream restoration discards delivered text state and retains metadata without a second full delta copy. Incremental UTF-8 byte accounting handles surrogate pairs split across deltas without rescanning accumulated tool arguments. Per-channel unfinished data is capped at 8 MiB; aggregate retained channel data is capped at 32 MiB with at most 1,024 channels. Failed or incomplete tool streams release their buffers without manufacturing completed arguments.
1070
1072
 
1071
1073
  Claude passthrough now holds incomplete SSE frames and validates complete data before forwarding. Malformed tails do not precede the terminal error; valid final JSON without a newline remains deliverable. Capability restoration and replacement writes use the existing ownership journal in one transaction, preserving both files and ownership on failure.
1072
1074
 
@@ -1084,12 +1086,16 @@ Native discovery, configuration and startup environment inspection run in bounde
1084
1086
 
1085
1087
  `messages-system-policy.mjs` selects transformation from the resolved endpoint capability, separately from client alias mapping. M365 declares native inline system support: only leading system messages join the top-level system field; later messages, cache-control blocks and signed history remain in order. Other Claude App API endpoints retain the prior legacy transformation unless their model explicitly declares `mid_conversation_system`; ordinary API passthrough is unchanged. History ownership validation accepts only text in inline system messages and fingerprints conversation turns independently of instruction placement, as it already does for top-level system text. Canonical and legacy journals therefore retain current signed tool continuations across this upgrade; tool and signature checks remain enforced. This is a protocol capability, with no App version or model-name pattern.
1086
1088
 
1087
- M365 count-token capability probes use the existing bounded API count coordinator before privacy detection. One source/model/header scope shares its initial probe; real 404 responses suppress further count probes for 60 seconds. Generation is independent and no estimate is fabricated. Long-text rule detection caches hashed keys and span metadata within 1 MiB/2048 entries. Neural detection still uses its existing separate bounded cache. Last-waiter cancellation stops unused shared detection, while a non-interruptible native job retains its physical admission slot until reply/deadline. Numeric neural secret predictions require an adjacent secret label; deterministic secret rules remain effective.
1089
+ M365 count-token capability probes use the existing bounded API count coordinator before privacy detection. One source/model/header scope shares its initial probe; real 404 responses suppress further count probes for 60 seconds. Generation is independent and no estimate is fabricated. Long-text rule detection caches hashed keys and span metadata within 1 MiB/2048 entries. Neural detection uses its separate bounded cache, committing valid completed batches even after callers leave. Cancellation skips work not submitted, while a non-interruptible native job retains its shared completion and physical admission slot until reply/deadline. Numeric neural secret predictions require an adjacent secret label; deterministic secret rules remain effective.
1090
+
1091
+ Responses records retain explicitly reported zero token counts and derive totals only when both input and output are known. Native cumulative Messages counters merge across sparse events. Identical cache aliases within one report count once; contradictory aliases are excluded from paired cache-rate evidence and marked invalid. Historical raw logs remain unchanged; summaries retain unambiguous observed counts and mark conflicts. Plain/table CLI output and daily analytics distinguish absent counters from explicit zero. Usage recording remains independent of response delivery.
1088
1092
 
1089
- Native components stage under `components/<release>` without replacing a running executable. Current checksums are verified on load; a verified ABI-compatible 1.3.6 component remains usable while a background upgrade is staged. No model mapping or request text is persisted.
1093
+ Native components stage under `components/<release>` without replacing a running executable. Receipts bind the release, SHA256, protocol ABI and model revision; verified older versioned components are considered in descending version order within a bounded set. Known pre-metadata 1.3.6/1.3.9 receipts retain explicit compatibility. A staged component is adopted on the next load only after all physical jobs finish; in-flight work is never killed for an upgrade. Weight caches contain only the three pinned portable files, not architecture-specific CoreML output. No model mapping or request text is persisted.
1090
1094
 
1091
1095
  ### CI and release evidence
1092
1096
 
1093
1097
  Unit suites are automatically discovered on macOS and Windows with Node 22.15 and 24. A temporary HOME and an OS-variable allowlist keep developer credentials and configuration out of unit fixtures. Installer/network replay jobs retain their explicitly configured proxy and certificate policy. Browser theme cases run in four parallel palette groups without reducing the language/theme/viewport matrix. Independent checks continue after another check fails, and any failed check keeps the result failed. Native client versions are pinned; compatibility baseline coverage remains separate.
1094
1098
 
1095
- Publication requires a successful full CI run on the exact tagged commit, downloads its four runtime and four privacy artifacts, and stages one checksummed GitHub release. The same source tarball goes to npm. Downloaded draft bytes, public npm bytes, a fresh native dependency installation and every public GitHub asset are verified. The release receipt is generated from these checks; it does not checksum itself. Failed publication can resume only when an existing npm version has identical integrity.
1099
+ Each native platform build also exercises the actual classifier with fixed Codex and Claude Code clients against an isolated synthetic provider, including timeout/cached recovery and real tool continuation. Simulated-classifier replays remain separately named coverage.
1100
+
1101
+ Publication requires the explicit complete platform/Node/browser CI matrix on the exact tagged commit. It reuses that run's four runtime and four privacy artifacts and records source commit/CI provenance beside the single source tarball. Existing shipping assets are validated before writes; matching assets are preserved and mismatches stop recovery. npm first receives a version-specific verification tag. Public package bytes, a fresh native installation and all public assets are checked before npm latest is promoted without re-uploading. Temporary-tag removal follows verification; an explicit 403 is recorded as denied cleanup without invalidating the verified version or changing permissions. Other unexpected cleanup errors remain failures. The truthful final receipt is downloaded again before GitHub latest is updated. Public npm processing has a finite ten-minute verification window. Recovery selects the original publication artifact and skips npm upload and rebuilding. The generated release receipt does not checksum itself.
package/docs/REFERENCE.md CHANGED
@@ -31,6 +31,8 @@ For installation and first use, start with the [README](../README.md). This refe
31
31
  | `ccdx app codex review status` / `select` | Read or choose the review model |
32
32
  | `ccdx config show [--effective]` | Read saved preferences and effective state |
33
33
  | `ccdx config set <key> <value>` | Save a validated preference |
34
+ | `ccdx config privacy status` | Read model readiness and the latest local check |
35
+ | `ccdx config privacy enable` / `disable` / `remove` | Prepare protection, stop later checks, or delete its model |
34
36
  | `ccdx config terminal` / `animation` | Choose terminal appearance |
35
37
  | `ccdx config limits [--decoded MiB]` | Read or change the decoded request limit |
36
38
  | `ccdx config reset --preview` / `restore` | Preview defaults or restore the pre-reset backup |
@@ -255,6 +257,8 @@ Normal management belongs in the WebUI. CLI provides the same backend operations
255
257
  | Prediction setup/remove/repair/open | `app codex prediction setup/remove/repair/open` | Shared control; App closure may be required |
256
258
  | Images: configure/remove/pause/resume | `app codex image setup/remove/pause/resume` | Shared image configuration transaction; keys never returned by WebUI |
257
259
  | Install a stable update | `update apply --yes` | Same supervisor request; download, verify and idle service handoff |
260
+ | Local masking: prepare/disable/delete | `config privacy enable/disable/remove` | Same verified model lifecycle; existing protected replies retain restoration |
261
+ | Local masking status and personal information | `config privacy status`, `config set privacy_personal true/false` | Read readiness or change the personal-information choice |
258
262
  | Standalone update/recovery | `update github/npm`, `doctor` | Available when service management is unavailable |
259
263
  | Local/network checks, repair and report | `doctor`, `doctor network/report`, `doctor --fix` | Existing checks and configuration repair |
260
264
  | Explicit model compatibility test | `doctor --compat` | Finite Codex Responses/stream/compaction requests; supports vendor IDs; local client credential stays on loopback; WebUI confirms quota use |
@@ -775,7 +779,7 @@ Usage queries share a bounded aggregate checkpoint only when file identities, fi
775
779
 
776
780
  ## Local masking
777
781
 
778
- Settings → Advanced → Local masking is off by default. Enabling it downloads the optional local component and AstrLink Guard 0.1.3, verifies their checksums and loads the model before activating protection. The npm package and ordinary installation do not contain model weights or require Go, Python or CUDA. The model and tokenizer total 38,958,270 bytes; the executable and optional macOS acceleration cache require additional space. Component upgrades stage in a separate version directory. A verified compatible older component keeps serving during a failed download; the staged component takes over on the next engine load. Model weights with matching checksums are reused.
782
+ Settings → Advanced → Local masking is off by default. Enabling it downloads the optional local component and AstrLink Guard 0.1.3, verifies their checksums and loads the model before activating protection. The npm package and ordinary installation do not contain model weights or require Go, Python or CUDA. The model and tokenizer total 38,958,270 bytes; the executable and optional macOS acceleration cache require additional space. Component upgrades stage in a separate version directory. A verified compatible older component keeps serving during a failed download; the staged component takes over at an idle detection boundary. Model weights with matching checksums are reused.
779
783
 
780
784
  Covered text includes conversation instructions, message text, tool results, tool argument values and tool descriptions on Responses, Chat and Messages routes. Protocol identifiers, tool schemas, authentication headers, images, signed thinking and encrypted reasoning retain their current behavior. Masking cannot retroactively remove data already sent to a service or control an agent's file/tool permissions. Personal-information detection is a separate opt-in; detection can miss values or mistake ordinary text.
781
785
 
@@ -783,12 +787,16 @@ Rules and a local model replace detected values with stable placeholders. Replie
783
787
 
784
788
  Tool data is interpreted in its own context: ordinary argument fields named `id`, `signature`, `data` or `type` are restored, while protocol identifiers and signed blocks remain unchanged. Streaming restoration retains SSE event metadata and restores Responses custom-tool text across fragments. Incomplete parameters are discarded when the upstream emits a failure rather than replacing that failure with a restoration error.
785
789
 
786
- Each request pins its masking choice, including compatibility retries. A check exceeding 15 seconds is rejected before any upstream call; bounded local work can continue for up to five minutes so a retry can reuse its complete results. No request is sent using an incomplete model check. Model work is capped at eight jobs and 16 MiB queued input; text input per call is capped at 8 MiB. Detection metadata uses a 5,000-entry/4 MiB memory cache. CPU-only first checks of long histories can take substantially longer than cached checks.
790
+ Each request pins its masking choice, including compatibility retries. A check exceeding 15 seconds is rejected before any upstream call. The submitted native batch continues, validates its results and caches them for a retry; the retry also shares work still in progress. Whole text entries are grouped toward 16 KiB or 64 entries per batch. A larger individual text stays whole. Completed batches remain reusable; later work with no waiting request is skipped. No request is sent using an incomplete model check. A native job has a five-minute processing deadline. Model work remains capped at eight jobs and 16 MiB queued input; text input per call is capped at 8 MiB. Detection metadata uses a 5,000-entry/4 MiB memory cache. CPU-only first checks of long histories can take substantially longer than cached checks.
791
+
792
+ Streaming restoration limits each unfinished value to 8 MiB, total retained channel data to 32 MiB and active channels to 1,024. Completed text is released as it is delivered. A timeout or busy check reports that nothing was sent, with `Retry-After` for temporary waits. Model readiness and the latest check are separate: a loaded model does not establish that a request or client tool completed.
787
793
 
788
794
  Turning masking off affects subsequent requests. Existing protected replies keep their restoration mappings until they finish. The downloaded component can then be deleted separately. Settings reset backs up and resets masking choices while keeping accounts, model selections, client connections, images and prediction access. Older settings backups inherit masking off.
789
795
 
796
+ WebUI controls and `ccdx config privacy` use the same preparation transaction. While the service runs, `config set privacy_enabled true/false` and the personal-information preference use these same controls. Offline preference writes and backup restoration retain saved intent; they do not prove model readiness or download a missing model. Unavailable configured protection holds requests back. Use Enable/Retry or `config privacy enable` to prepare it.
797
+
790
798
  Try locally sends sample text only to the local component. Request records show the number of replacements and elapsed local-check time, never the original values. Initial setup failures keep protection off; failed component upgrades retain verified compatible protection. Configured but unavailable protection refuses covered requests. Downloads retain the selected npm's proxy, certificate and offline policy, with no automatic policy relaxation or alternate downloader.
791
799
 
792
800
  Privacy failures have a separate local diagnostic origin. Response-restoration failures report that the response was stopped; request-check failures report that nothing was sent. When the latest Messages input explicitly contains failed tool results, request details show their count without retaining their content. HTTP success describes the model response, not proof that a client executed its tools successfully.
793
801
 
794
- The optional component targets the v1.3.9 Release; later code-only updates can reuse it. A verified ABI-compatible v1.3.6 installation can continue serving while the new component is staged. Its source and license notices are in `native/privacy-guard` and `src/privacy-notices.txt`. AstrLink Guard model files use their publisher's Apache-2.0 license.
802
+ The optional component targets the v1.3.10 Release; later code-only updates can reuse it. Verified 1.3.6 and 1.3.9 installations remain compatible. New component receipts bind their protocol ABI and model revision before older versioned components can be reused. On Intel Macs where CoreML selects CPU, windows below 128 tokens use the existing native int8 reader; longer windows, GPU, Neural Engine and ARM selection retain their prior policy. Its source and license notices are in `native/privacy-guard` and `src/privacy-notices.txt`. AstrLink Guard model files use their publisher's Apache-2.0 license.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.9",
3
+ "version": "1.3.11",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -224,6 +224,8 @@ export function createAdapterHandler(options = {}) {
224
224
  snapshot.routing = { ...snapshot.routing, responses: providers.codex_provider };
225
225
  snapshot.models = { ...snapshot.models, provider: providers.codex_provider, source: "configured", models: source?.codex_model_count || 0, refresh_in_flight: false };
226
226
  }
227
+ try { snapshot.local_privacy = privacy.snapshot(); }
228
+ catch { snapshot.local_privacy = { state: "error", error: "ccdx_privacy_settings_invalid" }; }
227
229
  return { ...snapshot, http_errors: httpErrors.snapshot(), ...(providers ? { providers } : {}) };
228
230
  },
229
231
  });
@@ -270,6 +270,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
270
270
  context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
271
271
  if (outcome === "cancelled") return;
272
272
  if (!res.headersSent) {
273
+ if (error.origin === "privacy" && Number.isInteger(error.retryAfter) && error.retryAfter > 0) res.setHeader("Retry-After", String(error.retryAfter));
273
274
  const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
274
275
  if (rejectionReason) value.error.reason = rejectionReason;
275
276
  if (diagnostic) value.error.diagnostic = diagnostic;
@@ -149,6 +149,9 @@ export const MANAGED_COMMANDS = [
149
149
  })),
150
150
  command("config show", "Show service and terminal preferences", { ...read, "--effective": "flag" }),
151
151
  command("config set <key> <value>", "Save a validated service preference", confirm),
152
+ command("config privacy status", "Show local masking readiness and the latest check", read),
153
+ ...["enable", "disable", "remove"].map(action => command(`config privacy ${action}`,
154
+ action === "enable" ? "Download, verify and prepare local masking before activation" : action === "remove" ? "Disable masking and delete its local model" : "Disable masking for later requests", { ...read, ...confirm })),
152
155
  command("config terminal", "Choose terminal color", {}),
153
156
  command("config animation", "Choose terminal animation", {}, () => ({ command: "animation" })),
154
157
  command("config limits", "Show or set decoded-body limits", { "--decoded": "value" }, flags => ({
@@ -134,6 +134,17 @@ export async function runManagementCommand(command, options = {}) {
134
134
  const { dashboardUpdateStatus } = await import("./dashboard-updates.mjs");return print(await dashboardUpdateStatus());
135
135
  }
136
136
  if (group === "config") {
137
+ const changePrivacy = async (operation, extra = {}) => {
138
+ const state = await request({ path: "privacy" });
139
+ if (typeof state.revision !== "string") throw new Error("Update the running CCDX service to manage local masking.");
140
+ return request({ path: "privacy", body: { action: operation, revision: state.revision, ...extra } });
141
+ };
142
+ if (path[1] === "privacy") {
143
+ if (action === "status") return print(await request({ path: "privacy" }));
144
+ if (flags.preview) return print({ operation: action, saved: false, effect: action === "enable" ? "Download and prepare before activation" : "Existing protected replies retain restoration" });
145
+ await confirm(action === "enable" ? "Download and prepare local masking before enabling it?" : action === "remove" ? "Disable masking and delete its downloaded component and model?" : "Disable masking for later requests?");
146
+ return print(await changePrivacy(action));
147
+ }
137
148
  const preferenceOptions = { ...options, backupScope: "service" }, local = settingsPreferencesSnapshot(preferenceOptions);
138
149
  const effective = live => Object.fromEntries(Object.entries(live.effective || {}).filter(([key]) => Object.hasOwn(local.defaults, key)));
139
150
  if (action === "show") {
@@ -163,8 +174,10 @@ export async function runManagementCommand(command, options = {}) {
163
174
  if (!/not running/.test(error.message)) throw error;
164
175
  }
165
176
  if (running && operation !== "preferences") { await connection();requireManagement(); }
166
- const risk = values?.nightly_updates ? "Overnight updates can interrupt task continuation. Save this preference?" : "Save these service preferences?";
177
+ const risk = values?.privacy_enabled ? "Download and prepare local masking before enabling it?" : values?.nightly_updates ? "Overnight updates can interrupt task continuation. Save this preference?" : "Save these service preferences?";
167
178
  await confirm(risk);
179
+ if (running && values && Object.hasOwn(values, "privacy_enabled")) return print(await changePrivacy(values.privacy_enabled ? "enable" : "disable"));
180
+ if (running && values && Object.hasOwn(values, "privacy_personal")) return print(await changePrivacy("personal", { personal: values.privacy_personal }));
168
181
  const body = { action: operation, revision: local.revision, ...(values ? { values } : { backup_id, scope: "service" }) };
169
182
  if (running) { const result = await request({ path: "settings", body });return print({ saved: result.preferences.values, effective: effective(result), nightly_update: result.nightly_update, effect: "Saved; restart requirements are shown in effective state" }); }
170
183
  writeSettingsPreferences(body, preferenceOptions);return print({ saved: settingsPreferencesSnapshot(preferenceOptions).values, effect: "Saved for the next CCDX start; no service was started" });
@@ -42,6 +42,9 @@
42
42
  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", "下载并开启"],
43
43
  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"],
44
44
  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.", "本地检查失败。未向模型来源发送文本。"],
45
+ privacy_busy: ["Local detection is busy. Nothing was sent; retry shortly.", "本地检测繁忙,未发送请求。请稍后重试。"],
46
+ privacy_wait_timeout: ["Detection is still running. Nothing was sent; retry shortly to reuse its results.", "检测仍在进行,未发送请求。稍后重试可复用检测结果。"],
47
+ privacy_invalid_result: ["The detector returned an invalid result. Nothing was sent; retry or check these settings.", "检测结果无效,未发送请求。请重试或检查设置。"],
45
48
  "client_key_encrypted_kept": ["Key kept encrypted; access not checked.", "密钥保持加密,访问未验证。"],
46
49
  "context_tabs": ["Usage view", "统计视图"],
47
50
  "context_unknown_window": ["Unknown", "未知"],
@@ -22,8 +22,10 @@
22
22
  el("privacy-remove").hidden = busy || state.state === "not_downloaded";el("privacy-remove").disabled = pending;
23
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
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 || "";
25
+ el("privacy-device").textContent = state.backend ? state.device && state.device !== state.backend ? `${state.backend} · ${state.device}` : state.backend : "";
26
+ const check = state.enabled && state.last_check?.state === "failed" ? state.last_check : null;
26
27
  if (state.error) words("privacy-error", state.error.includes("download") ? "privacy_download_error" : "privacy_error");
28
+ else if (check) words("privacy-error", check.code === "ccdx_privacy_busy" ? "privacy_busy" : check.code === "ccdx_privacy_check_timeout" && check.continuing ? "privacy_wait_timeout" : check.code === "ccdx_privacy_engine_invalid" ? "privacy_invalid_result" : "privacy_error");
27
29
  else { el("privacy-error").textContent = "";el("privacy-error").removeAttribute("data-i18n"); }
28
30
  clearTimeout(timer);
29
31
  if (busy && visible()) timer = setTimeout(() => { if (Date.now() - pushed > 2500) void load();else render(); }, 3000);
@@ -34,10 +36,10 @@
34
36
  }
35
37
  async function act(action, extra = {}) {
36
38
  if (!state || pending) return;
37
- pending = true;render();
39
+ pending = true;render();let reload = false;
38
40
  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
+ catch (error) { reload = true;words("privacy-error", error.code === "ccdx_privacy_settings_changed" ? "privacy_changed" : "privacy_error"); }
42
+ finally { pending = false;render();if (reload) await load(); }
41
43
  }
42
44
  function enable() { el("privacy-dialog").showModal(); }
43
45
  el("privacy-enabled").addEventListener("change", () => {
@@ -271,6 +271,7 @@ export function sendJsonError(res, err, fallbackStatus = 400) {
271
271
  context?.onHttpError?.({ code: err?.code || err?.jsonBody?.error?.code,
272
272
  origin: context.errorOrigin || (statusCode < 500 ? "client_validation" : "local_transport") });
273
273
  const headers = { "Content-Type": "application/json" };
274
+ if (err?.origin === "privacy" && Number.isInteger(err.retryAfter) && err.retryAfter > 0) headers["Retry-After"] = String(err.retryAfter);
274
275
  if (statusCode === 408 || statusCode === 413) headers.Connection = "close";
275
276
  res.writeHead(statusCode, headers);
276
277
  res.end(JSON.stringify(err?.jsonBody || { error: err?.message || "Request failed" }));
@@ -6,7 +6,7 @@ import { withFileLockSync } from "./lock.mjs";
6
6
  import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
7
7
  import { createChangeSignal } from "./activity-events.mjs";
8
8
  import { createPrivacyModel, privacyFailure } from "./privacy-model.mjs";
9
- import { maskPrivacyRequest, protectPrivacyResponse, createPrivacyRuleCache } from "./privacy-transform.mjs";
9
+ import { maskPrivacyRequest, protectPrivacyResponse, createPrivacyRuleCache, validatePrivacyFindings } from "./privacy-transform.mjs";
10
10
  import { markRequestObservation } from "./stream-performance.mjs";
11
11
 
12
12
  export function createLocalPrivacy(options = {}) {
@@ -14,13 +14,16 @@ export function createLocalPrivacy(options = {}) {
14
14
  const model = options.model || createPrivacyModel({ ...options, changed: changes.changed });
15
15
  const rules = createPrivacyRuleCache();
16
16
  let cacheBytes = 0, generation = 0, pending = null, disposed = false;
17
- let keyLoaded = false, actionError = null;
17
+ let keyLoaded = false, actionError = null, lastCheck = null;
18
18
  const settings = () => {
19
19
  const saved = readUserSettings({ ...options, strict: true });
20
20
  return { enabled: saved.privacy_enabled === true, personal: saved.privacy_personal === true };
21
21
  };
22
22
  const revision = saved => createHash("sha256").update(JSON.stringify(saved)).digest("hex");
23
- const snapshot = () => { const saved = settings();return { ...model.snapshot(), ...saved, rule_cache: rules.stats(), ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
23
+ const snapshot = () => { const saved = settings(), detector = model.snapshot();return { ...detector, ...saved,
24
+ effective_enabled: saved.enabled && detector.state === "ready", last_check: lastCheck && { ...lastCheck,
25
+ ...(lastCheck.continuing ? { continuing: flights.size > 0 || detector.pending_checks > 0 } : {}) }, rule_cache: rules.stats(),
26
+ ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
24
27
  function loadKey() {
25
28
  if (keyLoaded) return;
26
29
  const file = path.join(path.dirname(userSettingsPath(options)), "privacy-key");fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
@@ -38,47 +41,80 @@ export function createLocalPrivacy(options = {}) {
38
41
  });changes.changed();
39
42
  }
40
43
  async function find(texts, { signal } = {}) {
41
- const waiting = [], fresh = [], entries = [], batches = new Set();
42
- const batch = { controller: new AbortController(), waiters: 0, settled: false };
44
+ if (signal?.aborted) throw signal.reason;
45
+ const waiting = [], fresh = [], entries = [];
43
46
  for (const text of texts) {
44
47
  const key = createHash("sha256").update(text).digest("hex");
45
48
  if (cache.has(key)) {
46
49
  const saved = cache.get(key);cache.delete(key);cache.set(key, saved);waiting.push(Promise.resolve(saved.found));
47
- } else if (flights.has(key) && !flights.get(key).batch.controller.signal.aborted) { const entry = flights.get(key);waiting.push(entry.promise);batches.add(entry.batch); }
48
- else {
49
- const entry = Promise.withResolvers();entry.key = key;entry.batch = batch;flights.set(key, entry);batches.add(batch);
50
- waiting.push(entry.promise);fresh.push(text);entries.push(entry);
50
+ } else {
51
+ let entry = flights.get(key);
52
+ if (!entry) {
53
+ entry = Promise.withResolvers();Object.assign(entry, { key, text, waiters: 0, done: false });
54
+ flights.set(key, entry);fresh.push(entry);
55
+ }
56
+ entry.waiters++;entries.push(entry);waiting.push(entry.promise);
51
57
  }
52
58
  }
53
- for (const work of batches) work.waiters++;
54
- if (fresh.length) void model.find(fresh, { signal: batch.controller.signal }).then(found => {
55
- if (batch.controller.signal.aborted) throw privacyFailure("cancelled");
56
- if (!Array.isArray(found) || found.length !== fresh.length) throw privacyFailure("engine_invalid");
57
- for (let i = 0; i < found.length; i++) {
58
- const cost = Buffer.byteLength(JSON.stringify(found[i] || [])) + 128, entry = entries[i];
59
- if (cost <= 1024 * 1024) {
60
- const previous = cache.get(entry.key);if (previous) cacheBytes -= previous.bytes;
61
- cache.set(entry.key, { found: found[i] || [], bytes: cost });cacheBytes += cost;
62
- while (cache.size > 5000 || cacheBytes > 4 * 1024 * 1024) { const oldest = cache.keys().next().value;cacheBytes -= cache.get(oldest).bytes;cache.delete(oldest); }
59
+ const finish = (entry, value, error) => {
60
+ if (entry.done) return;
61
+ entry.done = true;entry.text = null;
62
+ if (flights.get(entry.key) === entry) flights.delete(entry.key);
63
+ if (error) entry.reject(error);else entry.resolve(value);
64
+ };
65
+ const run = async () => {
66
+ let at = 0;
67
+ try {
68
+ while (at < fresh.length) {
69
+ const batch = [];let bytes = 0;
70
+ while (at < fresh.length && batch.length < 64) {
71
+ const entry = fresh[at];
72
+ if (!entry.waiters) { finish(entry, null, privacyFailure("cancelled"));at++;continue; }
73
+ const size = Buffer.byteLength(entry.text);
74
+ if (batch.length && bytes + size > (options.batchBytes ?? 16 * 1024)) break;
75
+ batch.push(entry);bytes += size;at++;
76
+ }
77
+ if (!batch.length) continue;
78
+ // A submitted batch finishes even if its callers leave. Whole text
79
+ // entries keep their context; later batches can yield unused work.
80
+ const input = batch.map(entry => entry.text), found = validatePrivacyFindings(input, await model.find(input));
81
+ for (let i = 0; i < found.length; i++) {
82
+ const cost = Buffer.byteLength(JSON.stringify(found[i])) + 128, entry = batch[i];
83
+ if (cost <= 1024 * 1024) {
84
+ const previous = cache.get(entry.key);if (previous) cacheBytes -= previous.bytes;
85
+ cache.set(entry.key, { found: found[i], bytes: cost });cacheBytes += cost;
86
+ while (cache.size > 5000 || cacheBytes > 4 * 1024 * 1024) { const oldest = cache.keys().next().value;cacheBytes -= cache.get(oldest).bytes;cache.delete(oldest); }
87
+ }
88
+ finish(entry, found[i]);
89
+ }
63
90
  }
64
- entry.resolve(found[i] || []);
91
+ } catch (error) {
92
+ for (const entry of fresh) finish(entry, null, error);
65
93
  }
66
- }).catch(error => entries.forEach(entry => entry.reject(error))).finally(() => { batch.settled = true;entries.forEach(entry => { if (flights.get(entry.key) === entry) flights.delete(entry.key); }); });
94
+ };
95
+ if (fresh.length) void run();
67
96
  let listener;
68
97
  const aborted = new Promise((_, reject) => { listener = () => reject(signal.reason);if (signal?.aborted) listener();else signal?.addEventListener("abort", listener, { once: true }); });
69
98
  try { return await (signal ? Promise.race([Promise.all(waiting), aborted]) : Promise.all(waiting)); }
70
- finally { signal?.removeEventListener("abort", listener);for (const work of batches) if (--work.waiters === 0 && !work.settled) work.controller.abort(privacyFailure("cancelled")); }
99
+ finally { signal?.removeEventListener("abort", listener);for (const entry of entries) entry.waiters--; }
71
100
  }
72
101
  async function prepare(body, { protocol, client, signal, res, policy } = {}) {
73
102
  const saved = policy || settings();if (!saved.enabled) return body;
74
103
  if (disposed) throw privacyFailure("engine_unavailable");
75
104
  loadKey();
76
105
  const start = performance.now();
77
- const deadline = AbortSignal.timeout(15000);let session;
106
+ const deadline = AbortSignal.timeout(options.checkTimeoutMs ?? 15000);let session;
78
107
  try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, rules: rules.find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
79
- catch (error) { if (deadline.aborted && !signal?.aborted) throw privacyFailure("check_timeout");throw error; }
108
+ catch (error) {
109
+ const failure = deadline.aborted && !signal?.aborted ? privacyFailure("check_timeout", "waiting") : error;
110
+ const elapsed = Math.round(performance.now() - start), cancelled = signal?.aborted === true;
111
+ lastCheck = { state: cancelled ? "cancelled" : "failed", at: new Date().toISOString(), elapsed_ms: elapsed,
112
+ code: /^ccdx_privacy_[a-z_]+$/.test(failure?.code || "") ? failure.code : cancelled ? "ccdx_privacy_cancelled" : "ccdx_privacy_unavailable", continuing: !cancelled && failure?.retryAfter === 5 };
113
+ markRequestObservation({ privacy_ms: elapsed, privacy_state: cancelled ? "cancelled" : "failed" });changes.changed();throw failure;
114
+ }
80
115
  if (signal?.aborted) { session.release();throw signal.reason; }
81
116
  markRequestObservation({ privacy_count: session.count, privacy_ms: Math.round(performance.now() - start), privacy_state: "checked" });
117
+ actionError = null;lastCheck = { state: "checked", at: new Date().toISOString(), elapsed_ms: Math.round(performance.now() - start), count: session.count };changes.changed();
82
118
  if (res && session.count) {
83
119
  let current = responses.get(res);
84
120
  if (!current) {
@@ -111,7 +147,7 @@ export function createLocalPrivacy(options = {}) {
111
147
  const current = ++generation;
112
148
  const work = (async () => {
113
149
  actionError = null;loadKey();
114
- if (!await model.installed({ current: true })) await model.download();
150
+ if (!await model.installed({ current: true })) await model.download({ background: model.snapshot().state === "ready" });
115
151
  if (current !== generation) return;
116
152
  await model.load();if (current !== generation) return;
117
153
  save({ privacy_enabled: true }, input.revision);
@@ -5,10 +5,11 @@ import os from "node:os";
5
5
  import { createHash, randomUUID } from "node:crypto";
6
6
  import { spawn, execFile } from "node:child_process";
7
7
  import { promisify } from "node:util";
8
- import { createNpmReleaseFetch, releaseBytes, releaseChecksum, RELEASE_BASE } from "./release-install.mjs";
8
+ import { createNpmReleaseFetch, releaseBytes, releaseChecksum, RELEASE_BASE, stableVersion } from "./release-install.mjs";
9
9
 
10
10
  export const PRIVACY_MODEL_REVISION = "7216b6a3b897ef903d4b1ba367ae6fb95b0fa5e4";
11
- export const PRIVACY_COMPONENT_RELEASE = "1.3.9";
11
+ export const PRIVACY_COMPONENT_RELEASE = "1.3.10";
12
+ export const PRIVACY_COMPONENT_ABI = 1;
12
13
  export const PRIVACY_MODEL_FILES = Object.freeze([
13
14
  { name: "model_int8.onnx", bytes: 330781, sha256: "0a070d3113615e33ba3b84d6bd486f663a377c04c4b056e7381732179f51832a" },
14
15
  { name: "model_int8.onnx_data", bytes: 37124608, sha256: "0ba34216ceead01e0ae2dfd8e46d52b67e7aee80b04f722d9b758613a91c0067" },
@@ -17,16 +18,21 @@ export const PRIVACY_MODEL_FILES = Object.freeze([
17
18
  export const PRIVACY_DOWNLOAD_BYTES = PRIVACY_MODEL_FILES.reduce((n, file) => n + file.bytes, 0);
18
19
  export function privacyFailure(code, phase = "check") {
19
20
  const message = phase === "response" ? "Local privacy response restoration failed. The response was stopped; review Settings."
21
+ : phase === "waiting" ? "Local privacy detection is still running. Nothing was sent; retry shortly to reuse its results."
22
+ : code === "busy" ? "Local privacy detection is busy. Nothing was sent; retry shortly."
23
+ : code === "engine_invalid" ? "The local privacy detector returned an invalid result. Nothing was sent; retry or check Settings."
24
+ : code === "check_timeout" ? "The local privacy detector reached its processing deadline. Nothing was sent; check Settings."
20
25
  : "Local privacy check could not finish. Nothing was sent; review Settings.";
21
26
  return Object.assign(new Error(message), { code: `ccdx_privacy_${code}`, statusCode: 503, origin: "privacy",
27
+ ...(phase === "waiting" || code === "busy" ? { retryAfter: 5 } : {}),
22
28
  jsonBody: { error: { type: "api_error", code: `ccdx_privacy_${code}`, message } } });
23
29
  }
24
30
  const digest = bytes => createHash("sha256").update(bytes).digest("hex");
25
31
  export function privacyPaths({ home = os.homedir(), env = process.env, platform = process.platform, arch = process.arch } = {}) {
26
32
  const root = path.join(env.XDG_CACHE_HOME || (platform === "win32" ? env.LOCALAPPDATA || path.join(home, "AppData", "Local") : path.join(home, ".cache")), "codex-copilot-dx", "privacy");
27
- const name = `ccdx-privacy-guard-1-${platform}-${arch}${platform === "win32" ? ".exe" : ""}`;
28
- const component = path.join(root, "components", PRIVACY_COMPONENT_RELEASE);
29
- return { root, model: path.join(root, PRIVACY_MODEL_REVISION), name, runner: path.join(component, name), receipt: path.join(component, name + ".json"), legacyRunner: path.join(root, name), legacyReceipt: path.join(root, name + ".json") };
33
+ const name = `ccdx-privacy-guard-${PRIVACY_COMPONENT_ABI}-${platform}-${arch}${platform === "win32" ? ".exe" : ""}`;
34
+ const components = path.join(root, "components"), component = path.join(components, PRIVACY_COMPONENT_RELEASE);
35
+ return { root, components, model: path.join(root, PRIVACY_MODEL_REVISION), name, runner: path.join(component, name), receipt: path.join(component, name + ".json"), legacyRunner: path.join(root, name), legacyReceipt: path.join(root, name + ".json") };
30
36
  }
31
37
  async function downloader(env) {
32
38
  const names = [env.npm_execpath];
@@ -52,14 +58,27 @@ export function createPrivacyModel(options = {}) {
52
58
  let state = { state: "not_downloaded", downloaded_bytes: 0, download_bytes: PRIVACY_DOWNLOAD_BYTES, backend: null, device: null, error: null };
53
59
  const jobs = new Map();
54
60
  const set = next => { state = { ...state, ...next };changed(); };
61
+ const compareVersions = (a, b) => { const x = a.split(".").map(Number), y = b.split(".").map(Number);return x[0] - y[0] || x[1] - y[1] || x[2] - y[2]; };
62
+ function candidates(current = false) {
63
+ const result = [[paths.runner, paths.receipt, PRIVACY_COMPONENT_RELEASE]];
64
+ if (current) return result;
65
+ try {
66
+ const versions = fsSync.readdirSync(paths.components, { withFileTypes: true }).filter(entry => (entry.isDirectory() || entry.isSymbolicLink())
67
+ && stableVersion(entry.name) === entry.name && compareVersions(entry.name, PRIVACY_COMPONENT_RELEASE) < 0)
68
+ .map(entry => entry.name).sort((a, b) => compareVersions(b, a)).slice(0, 16);
69
+ for (const version of versions) { const runner = path.join(paths.components, version, paths.name);result.push([runner, runner + ".json", version]); }
70
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
71
+ result.push([paths.legacyRunner, paths.legacyReceipt, "1.3.6"]);return result;
72
+ }
55
73
  async function installed({ current = false } = {}) {
56
74
  try {
57
75
  for (const file of modelFiles) if (digest(await fs.readFile(path.join(paths.model, file.name))) !== file.sha256) return false;
58
- const candidates = [[paths.runner, paths.receipt, PRIVACY_COMPONENT_RELEASE], ...(!current ? [[paths.legacyRunner, paths.legacyReceipt, "1.3.6"]] : [])];
59
- for (const [runner, receiptFile, release] of candidates) {
76
+ for (const [runner, receiptFile, release] of candidates(current)) {
60
77
  try {
61
78
  const receipt = JSON.parse(await fs.readFile(receiptFile, "utf8"));
62
79
  if (!/^[a-f0-9]{64}$/.test(receipt.sha256) || receipt.release !== release || digest(await fs.readFile(runner)) !== receipt.sha256) continue;
80
+ const legacy = PRIVACY_COMPONENT_ABI === 1 && ["1.3.6", "1.3.9"].includes(release) && receipt.abi === undefined && receipt.model_revision === undefined;
81
+ if (!legacy && (receipt.abi !== PRIVACY_COMPONENT_ABI || receipt.model_revision !== PRIVACY_MODEL_REVISION)) continue;
63
82
  if (!child) { activeRunner = runner;componentRelease = release; }
64
83
  return true;
65
84
  } catch { /* Missing targets never hide a verified ABI-compatible legacy component. */ }
@@ -84,7 +103,8 @@ export function createPrivacyModel(options = {}) {
84
103
  const tempRunner = paths.runner + "." + randomUUID();
85
104
  try { await fs.writeFile(tempRunner, runner, { mode: 0o700, flag: "wx" });await fs.rename(tempRunner, paths.runner); }
86
105
  finally { await fs.rm(tempRunner, { force: true }); }
87
- await fs.writeFile(paths.receipt, JSON.stringify({ release: PRIVACY_COMPONENT_RELEASE, sha256: expected }) + "\n", { mode: 0o600 });
106
+ await fs.writeFile(paths.receipt, JSON.stringify({ release: PRIVACY_COMPONENT_RELEASE, abi: PRIVACY_COMPONENT_ABI,
107
+ model_revision: PRIVACY_MODEL_REVISION, sha256: expected }) + "\n", { mode: 0o600 });
88
108
  for (const file of modelFiles) {
89
109
  const target = path.join(paths.model, file.name);
90
110
  try { if (digest(await fs.readFile(target)) === file.sha256) { report({ downloaded_bytes: state.downloaded_bytes + file.bytes });continue; } } catch {}
@@ -114,12 +134,13 @@ export function createPrivacyModel(options = {}) {
114
134
  jobs.clear();set({ state: stopped ? "installed" : "error", error: stopped ? null : "ccdx_privacy_engine_unavailable" });
115
135
  }
116
136
  function load() {
137
+ if (child && state.state === "ready" && !install && !jobs.size && componentRelease !== PRIVACY_COMPONENT_RELEASE && state.component_update === "staged") stop();
117
138
  stopped = false;
118
139
  if (ready) return ready;
119
140
  ready = (async () => {
120
141
  if (!await installed()) { set({ state: "not_downloaded" });throw privacyFailure("not_downloaded"); }
121
142
  if (stopped) throw privacyFailure("cancelled");
122
- set({ state: "loading", error: null });
143
+ set({ state: "loading", error: null, ...(componentRelease === PRIVACY_COMPONENT_RELEASE ? { component_update: null, component_update_error: null } : {}) });
123
144
  return new Promise((resolve, reject) => {
124
145
  const timer = setTimeout(() => { reject(privacyFailure("load_timeout"));fail(); }, 60000);
125
146
  const workerEnv = Object.fromEntries(["PATH", "SystemRoot", "WINDIR", "TMP", "TEMP", "TMPDIR", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "GOMAXPROCS"].filter(key => typeof env[key] === "string").map(key => [key, env[key]]));
@@ -164,7 +185,8 @@ export function createPrivacyModel(options = {}) {
164
185
  function snapshot() {
165
186
  if (!child && !install && ["installed", "not_downloaded"].includes(state.state)) {
166
187
  try {
167
- const stat = fsSync.lstatSync(fsSync.existsSync(paths.runner) ? paths.runner : paths.legacyRunner);
188
+ const runner = candidates().find(([file]) => fsSync.existsSync(file))?.[0];
189
+ const stat = fsSync.lstatSync(runner || paths.runner);
168
190
  const cached = stat.isFile() && stat.size > 0 && stat.size <= 16 * 1024 * 1024 && modelFiles.every(file => fsSync.lstatSync(path.join(paths.model, file.name)).size === file.bytes);
169
191
  state = { ...state, state: cached ? "installed" : "not_downloaded" };
170
192
  } catch { state = { ...state, state: "not_downloaded" }; }
@@ -99,6 +99,20 @@ function modelSpanFits(text, start, end, label) {
99
99
  && /\b(?:function|class|const|let|var)\s+$/.test(text.slice(Math.max(0, start - 32), start))) return false;
100
100
  return true;
101
101
  }
102
+ export function validatePrivacyFindings(texts, found) {
103
+ if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
104
+ return found.map((items, index) => {
105
+ if (items === null) return [];
106
+ if (!Array.isArray(items)) throw privacyFailure("engine_invalid");
107
+ const bytes = Buffer.byteLength(texts[index]);
108
+ for (const span of items) {
109
+ if (!span || !Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start
110
+ || span.end > bytes || !Number.isFinite(span.score) || span.score < 0 || span.score > 1 || typeof span.label !== "string") throw privacyFailure("engine_invalid");
111
+ }
112
+ return items;
113
+ });
114
+ }
115
+
102
116
  export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, rules = ruleSpans }) {
103
117
  const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
104
118
  if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
@@ -154,14 +168,16 @@ function rewritePrivacyFrame(wire, value, named = false) {
154
168
  return named && !/^event:/m.test(wire) ? `event: ${value.type}\n${lines}` : lines;
155
169
  }
156
170
 
157
- export function createPrivacyStream(session) {
171
+ export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 1024, maxChannels = 1024 } = {}) {
158
172
  const fail = code => privacyFailure(code, "response");
159
- let pending = "", bytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
173
+ let pending = "", bytes = 0, bufferedBytes = 0;const channels = new Map(), decoder = new StringDecoder("utf8");
174
+ const forget = id => { bufferedBytes -= channels.get(id)?.bytes || 0;channels.delete(id); };
175
+ const clear = () => { channels.clear();bufferedBytes = 0; };
160
176
  function transform(wire) {
161
177
  const data = wire.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
162
178
  if (!data || data === "[DONE]") return wire;
163
179
  let event;try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
164
- if (["error", "response.failed", "response.incomplete"].includes(event.type)) { channels.clear();return rewritePrivacyFrame(wire, session.restoreValue(event)); }
180
+ if (["error", "response.failed", "response.incomplete"].includes(event.type)) { clear();return rewritePrivacyFrame(wire, session.restoreValue(event)); }
165
181
  if (["thinking_delta", "signature_delta"].includes(event.delta?.type) || /\.reasoning(?:_|\.)/.test(event.type || "")) return wire;
166
182
  const isMessages = event.type === "content_block_delta", delta = isMessages ? event.delta : event;
167
183
  const tool = delta?.type === "input_json_delta" || event.type === "response.function_call_arguments.delta";
@@ -171,18 +187,31 @@ export function createPrivacyStream(session) {
171
187
  if (tool || text) {
172
188
  const field = tool ? isMessages ? "partial_json" : "delta" : isMessages ? "text" : "delta";
173
189
  if (typeof delta[field] !== "string") throw fail("stream_invalid");
174
- const channel = channels.get(key) || { tail: "", tool, field };channel.template = event;channel.wire = wire;
190
+ const channel = channels.get(key) || { tail: "", tool, field };
191
+ const last = channel.tail.charCodeAt(channel.tail.length - 1), first = delta[field].charCodeAt(0);
192
+ const joinsPair = last >= 0xD800 && last <= 0xDBFF && first >= 0xDC00 && first <= 0xDFFF;
193
+ const valueBytes = (channel.tailBytes || 0) + Buffer.byteLength(delta[field]) - (joinsPair ? 2 : 0);
175
194
  let value = channel.tail + delta[field];
176
- if (Buffer.byteLength(value) > 8 * 1024 * 1024) throw fail("stream_limit");
177
- if (tool) { channel.tail = value;channels.set(key, channel);return ""; }
195
+ if (valueBytes > 8 * 1024 * 1024) throw fail("stream_limit");
196
+ if (tool) { channel.tail = value;channel.tailBytes = valueBytes; }
178
197
  else {
179
198
  let cut = value.length;
180
199
  const at = value.lastIndexOf("{{CCDX_");
181
200
  if (at >= 0 && !value.slice(at).includes("}}")) cut = at;
182
201
  else for (let n = 1; n < TOKEN_START.length; n++) if (value.endsWith(TOKEN_START.slice(0, n))) cut = value.length - n;
183
202
  channel.tail = value.slice(cut);delta[field] = session.restoreText(value.slice(0, cut));
203
+ channel.tailBytes = cut === 0 ? valueBytes : Buffer.byteLength(channel.tail);
184
204
  }
185
- channels.set(key, channel);
205
+ if (tool || channel.tail) {
206
+ // Retain metadata and the unfinished value once, rather than retaining
207
+ // the full latest delta in both the template and its original frame.
208
+ channel.template = isMessages ? { ...event, delta: { ...delta, [field]: "" } } : { ...event, [field]: "" };
209
+ channel.wire = rewritePrivacyFrame(wire, channel.template);
210
+ const cost = channel.tailBytes + Buffer.byteLength(channel.wire) + Buffer.byteLength(JSON.stringify(channel.template));
211
+ bufferedBytes += cost - (channel.bytes || 0);channel.bytes = cost;channels.set(key, channel);
212
+ if (bufferedBytes > maxBufferedBytes || channels.size > maxChannels) throw fail("stream_limit");
213
+ } else forget(key);
214
+ if (tool) return "";
186
215
  }
187
216
  const stopKey = event.type === "content_block_stop" ? `m:${event.index}` : /\.done$/.test(event.type || "") ? key : null;
188
217
  const terminal = ["message_stop", "response.completed", "response.incomplete", "error", "response.failed"].includes(event.type);
@@ -193,19 +222,26 @@ export function createPrivacyStream(session) {
193
222
  catch { throw fail("stream_invalid"); }
194
223
  before += rewritePrivacyFrame(channel.wire, value, true);
195
224
  }
196
- channels.delete(id);
225
+ forget(id);
197
226
  }
198
227
  event = session.restoreValue(event);
199
228
  return before + rewritePrivacyFrame(wire, event);
200
229
  }
201
230
  return {
202
231
  push(chunk) {
232
+ try {
203
233
  pending += decoder.write(chunk);bytes += chunk.length;if (bytes > 8 * 1024 * 1024) throw fail("stream_limit");
204
234
  let output = "", match;
205
235
  while ((match = /\r?\n\r?\n/.exec(pending))) { const end = match.index + match[0].length;output += transform(pending.slice(0, end));pending = pending.slice(end);bytes = Buffer.byteLength(pending); }
206
236
  return output;
237
+ } catch (error) { clear();pending = "";bytes = 0;throw error; }
238
+ },
239
+ finish() {
240
+ try {
241
+ pending += decoder.end();const output = pending ? transform(pending + "\n\n") : "";pending = "";
242
+ if (channels.size) throw fail("stream_incomplete");return output;
243
+ } finally { clear();pending = "";bytes = 0; }
207
244
  },
208
- finish() { pending += decoder.end();if (pending) { const output = transform(pending + "\n\n");pending = "";return output; }if (channels.size) throw fail("stream_incomplete");return ""; },
209
245
  };
210
246
  }
211
247
 
@@ -23,11 +23,13 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
23
23
  try { imageConfigured = Boolean(readImages()); } catch {}
24
24
  try { predictionConfigured = readPrediction().enabled === true; } catch {}
25
25
  const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
26
- return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: providerRuntime?.privacy?.snapshot(),
26
+ const localPrivacy = providerRuntime?.privacy?.snapshot();
27
+ return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
27
28
  features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: featureSnapshot(imageSetupSummary) },
28
29
  decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
29
30
  nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
30
31
  effective: {
32
+ privacy_enabled: { value: localPrivacy?.effective_enabled === true, state: !localPrivacy ? "unavailable" : !localPrivacy.enabled ? "off" : localPrivacy.state === "ready" ? "ready" : "not_ready" },
31
33
  terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
32
34
  state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
33
35
  open_webui: { value: saved.open_webui, state: "next_start" },
@@ -61,6 +63,10 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
61
63
  if (decodedBodyLimitPreference(options).source === "environment") throw new Error("Request limit is controlled by the launch environment");
62
64
  writeDecodedBodyLimitMib(input.mib, options);
63
65
  } else if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
66
+ if (input.action === "preferences" && Object.hasOwn(input.values || {}, "privacy_enabled")
67
+ && input.values.privacy_enabled !== settingsPreferencesSnapshot(options).values.privacy_enabled) {
68
+ throw Object.assign(new Error("Use local masking controls to prepare or disable protection"), { code: "ccdx_settings_privacy_action_required", statusCode: 400 });
69
+ }
64
70
  const before = nightlyUpdatePreference(options);
65
71
  writeSettingsPreferences(input, options);
66
72
  if (input.action !== "preferences" || Object.keys(input.values || {}).some(key => key.startsWith("privacy_"))) providerRuntime?.privacy?.settingsChanged();
@@ -342,8 +342,9 @@ 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", "privacy_count", "privacy_ms", "client_tool_errors_received"]) {
345
+ for (const key of [...Object.keys(context), "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "client_tool_errors_received"]) {
346
346
  const value = values[key];
347
+ if (key === "privacy_state") { if (["checked", "failed", "cancelled"].includes(value)) context[key] = value;continue; }
347
348
  if (["capability_revision", "capability_constraints"].includes(key)) {
348
349
  if (typeof value === "string" && /^[a-z0-9_,]{1,80}$/.test(value)) context[key] = value;continue;
349
350
  }
@@ -46,7 +46,8 @@ export function projectTerminalState(data = {}) {
46
46
  if (lastFailure) {
47
47
  const app = TERMINAL_CLIENT_NAMES[appIds[lastFailure.application]] || "Unidentified client";
48
48
  const source = connection?.providers?.find(item => item.id === lastFailure.provider)?.name || ({ github: "GitHub Copilot", m365: "Microsoft 365" }[lastFailure.provider]) || lastFailure.provider || "Unknown source";
49
- const causes = { m365_network_error: "Network request failed", m365_catalog_http_403: "Model catalog access denied", ccdx_api_model_unavailable: "Selected model is unavailable", ccdx_client_source_disabled: "Model access is paused" };
49
+ const causes = { m365_network_error: "Network request failed", m365_catalog_http_403: "Model catalog access denied", ccdx_api_model_unavailable: "Selected model is unavailable", ccdx_client_source_disabled: "Model access is paused",
50
+ ccdx_privacy_busy: "Local masking is busy; nothing was sent", ccdx_privacy_check_timeout: "Local masking check timed out; nothing was sent", ccdx_privacy_engine_invalid: "Local masking result was invalid; nothing was sent" };
50
51
  const message = causes[lastFailure.code] || (lastFailure.route === "messages_count_tokens" ? "Token-count check failed" : lastFailure.http_status === 401 ? "Sign-in was rejected" : lastFailure.http_status === 403 ? "Access was denied" : lastFailure.http_status === 429 ? "Request limit reached" : "Request failed");
51
52
  issue = { label: `${terminalCell(app)} / ${terminalCell(source)}: ${message}`, request_id: lastFailure.request_id, application: lastFailure.application };
52
53
  }
@@ -29,9 +29,10 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
29
29
  function row(values = {}) {
30
30
  return {
31
31
  requests: values.requests || 0,
32
- input_tokens: values.input_tokens || 0,
33
- output_tokens: values.output_tokens || 0,
34
- total_tokens: values.total_tokens ?? (values.input_tokens || 0) + (values.output_tokens || 0),
32
+ input_tokens: values.input_tokens ?? (values.requests ? null : 0),
33
+ output_tokens: values.output_tokens ?? (values.requests ? null : 0),
34
+ total_tokens: values.total_tokens ?? (!values.tokens_partial && Number.isFinite(values.input_tokens) && Number.isFinite(values.output_tokens)
35
+ ? values.input_tokens + values.output_tokens : values.requests ? null : 0),
35
36
  cache_read_tokens: cacheReadTokens(values) ?? null,
36
37
  cache_write_input_tokens: values.cache_write_input_tokens ?? null,
37
38
  cache_hit_rate: usageCacheHitRate(values),
@@ -71,18 +71,19 @@ function hasPositiveTokenValue(usage) {
71
71
 
72
72
  function normalizeResponsesUsage(usage) {
73
73
  if (!usage || typeof usage !== "object") return undefined;
74
+ const count = value => Number.isFinite(value) && value >= 0 ? value : undefined;
74
75
  const cachedInput = numberOrUndefined(usage.cached_input_tokens ?? usage.input_tokens_details?.cached_tokens);
75
76
  const out = compactObject({
76
- input_tokens: positiveNumber(usage.input_tokens),
77
+ input_tokens: count(usage.input_tokens),
77
78
  cached_input_tokens: cachedInput >= 0 ? cachedInput : undefined,
78
- output_tokens: positiveNumber(usage.output_tokens),
79
- reasoning_output_tokens: positiveNumber(usage.reasoning_output_tokens ?? usage.output_tokens_details?.reasoning_tokens),
80
- total_tokens: positiveNumber(usage.total_tokens),
79
+ output_tokens: count(usage.output_tokens),
80
+ reasoning_output_tokens: count(usage.reasoning_output_tokens ?? usage.output_tokens_details?.reasoning_tokens),
81
+ total_tokens: count(usage.total_tokens),
81
82
  });
82
- if (out.total_tokens === undefined && (out.input_tokens !== undefined || out.output_tokens !== undefined)) {
83
- out.total_tokens = (out.input_tokens || 0) + (out.output_tokens || 0);
83
+ if (out.total_tokens === undefined && out.input_tokens !== undefined && out.output_tokens !== undefined) {
84
+ out.total_tokens = out.input_tokens + out.output_tokens;
84
85
  }
85
- return hasPositiveTokenValue(out) ? out : undefined;
86
+ return Object.keys(out).length ? out : undefined;
86
87
  }
87
88
 
88
89
  function normalizeCopilotUsage(copilotUsage) {
@@ -330,7 +331,12 @@ export function summarizeUsage(records, { provider = "" } = {}) {
330
331
  if (provider && provider !== source) continue;
331
332
  summary.providers[source] = (summary.providers[source] || 0) + 1;
332
333
  summary.requests += 1;
333
- addUsageTotals(summary.totals, record.usage);
334
+ let observed = record.usage;
335
+ if (observed?.cached_input_tokens != null && observed?.cache_read_input_tokens != null) {
336
+ observed = { ...observed };delete observed.cache_read_input_tokens;
337
+ if (cacheReadTokens(record.usage) === undefined) delete observed.cached_input_tokens;
338
+ }
339
+ addUsageTotals(summary.totals, observed);
334
340
  if (record.copilot_usage) {
335
341
  summary.totals.copilot_total_tokens = (summary.totals.copilot_total_tokens || 0) + (record.copilot_usage.total_tokens || 0);
336
342
  summary.totals.total_nano_aiu = (summary.totals.total_nano_aiu || 0) + (record.copilot_usage.total_nano_aiu || 0);
@@ -339,12 +345,12 @@ export function summarizeUsage(records, { provider = "" } = {}) {
339
345
  if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
340
346
  const modelTotals = summary.byModel[model];
341
347
  modelTotals.requests += 1;
342
- addUsageTotals(modelTotals, record.usage);
348
+ addUsageTotals(modelTotals, observed);
343
349
  const qualified = `${source} / ${model}`;
344
350
  if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
345
351
  const sourceTotals = summary.bySourceModel[qualified];
346
352
  sourceTotals.requests++;
347
- addUsageTotals(sourceTotals, record.usage);
353
+ addUsageTotals(sourceTotals, observed);
348
354
  for (const target of [summary.totals, modelTotals, sourceTotals]) {
349
355
  addCacheEvidence(target, record.usage || {});
350
356
  }
@@ -426,6 +432,11 @@ export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = con
426
432
  }
427
433
 
428
434
  export function cacheReadTokens(usage = {}) {
435
+ if (usage.cached_input_tokens != null && usage.cache_read_input_tokens != null
436
+ && usage.cache_hit_known_requests === undefined && usage.cache_hit_unknown_requests === undefined) {
437
+ return Number.isFinite(usage.cached_input_tokens) && usage.cached_input_tokens >= 0
438
+ && usage.cached_input_tokens === usage.cache_read_input_tokens ? usage.cached_input_tokens : undefined;
439
+ }
429
440
  const values = [usage.cache_read_input_tokens, usage.cached_input_tokens]
430
441
  .filter((value) => Number.isFinite(value));
431
442
  const value = values.length > 0 ? values.reduce((total, current) => total + current, 0) : undefined;
@@ -460,6 +471,7 @@ function usageCacheEvidence(usage) {
460
471
  const input = usage.input_tokens, cached = cacheReadTokens(usage);
461
472
  const unknown = !Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input;
462
473
  const invalid = (input != null && (!Number.isFinite(input) || input < 0))
474
+ || (usage.cached_input_tokens != null && usage.cache_read_input_tokens != null && cached === undefined)
463
475
  || [usage.cached_input_tokens, usage.cache_read_input_tokens].some(value => value != null && (!Number.isFinite(value) || value < 0))
464
476
  || (Number.isFinite(input) && Number.isFinite(cached) && cached > input);
465
477
  return { cached, unknown, invalid };
package/src/usage.mjs CHANGED
@@ -28,7 +28,7 @@ function fmt(n) {
28
28
  return Number.isFinite(n) ? n.toLocaleString("en-US") : "0";
29
29
  }
30
30
 
31
- const writeTokens = n => Number.isFinite(n) ? fmt(n) : "—";
31
+ const tokenCount = n => Number.isFinite(n) ? fmt(n) : "—";
32
32
 
33
33
  function tableNumber(n) {
34
34
  return Number.isFinite(n) ? n.toLocaleString("en-US") : undefined;
@@ -55,13 +55,13 @@ function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {
55
55
  }
56
56
  lines.push(
57
57
  `Records: ${fmt(summary.requests)}`,
58
- `Tokens: input=${fmt(summary.totals.input_tokens)} cache_read=${fmt(cacheReadTokens(summary.totals))} cache_write=${writeTokens(summary.totals.cache_write_input_tokens)} output=${fmt(summary.totals.output_tokens)} total=${fmt(summary.totals.total_tokens)}`,
58
+ `Tokens: input=${tokenCount(summary.totals.input_tokens)} cache_read=${tokenCount(cacheReadTokens(summary.totals))} cache_write=${tokenCount(summary.totals.cache_write_input_tokens)} output=${tokenCount(summary.totals.output_tokens)} total=${tokenCount(summary.totals.total_tokens)}`,
59
59
  `Cache hit: ${cacheHitPercent(summary.totals)} (cached/input tokens; valid paired records only)`,
60
60
  "",
61
61
  "By model:",
62
62
  );
63
63
  for (const [model, row] of Object.entries(usageModelGroups(summary))) {
64
- lines.push(` ${terminalCell(model)}: records=${fmt(row.requests)} input=${fmt(row.input_tokens)} cache_read=${fmt(cacheReadTokens(row))} cache_write=${writeTokens(row.cache_write_input_tokens)} output=${fmt(row.output_tokens)} total=${fmt(row.total_tokens)} cache_hit=${cacheHitPercent(row)}`);
64
+ lines.push(` ${terminalCell(model)}: records=${fmt(row.requests)} input=${tokenCount(row.input_tokens)} cache_read=${tokenCount(cacheReadTokens(row))} cache_write=${tokenCount(row.cache_write_input_tokens)} output=${tokenCount(row.output_tokens)} total=${tokenCount(row.total_tokens)} cache_hit=${cacheHitPercent(row)}`);
65
65
  }
66
66
  return (sanitize ? lines.map((line) => terminalCell(line, { fallback: "" })) : lines).join("\n");
67
67
  }
@@ -87,7 +87,7 @@ function usageTableRow(model, usage) {
87
87
  }
88
88
 
89
89
  function usageDetailLine(model, usage) {
90
- return `${terminalCell(model)}: input=${fmt(usage.input_tokens)} cache_read=${fmt(cacheReadTokens(usage))} cache_write=${writeTokens(usage.cache_write_input_tokens)} output=${fmt(usage.output_tokens)} cache_hit=${cacheHitPercent(usage)}`;
90
+ return `${terminalCell(model)}: input=${tokenCount(usage.input_tokens)} cache_read=${tokenCount(cacheReadTokens(usage))} cache_write=${tokenCount(usage.cache_write_input_tokens)} output=${tokenCount(usage.output_tokens)} cache_hit=${cacheHitPercent(usage)}`;
91
91
  }
92
92
 
93
93
  function formatTableUsageSummary(summary, filePath, output) {
@@ -128,8 +128,8 @@ function formatTableUsageSummary(summary, filePath, output) {
128
128
  }
129
129
  const lines = [`Usage log: ${safePath}`, ...providerSummaryLines(summary), "", table.output];
130
130
  if (writeOmitted && !table.compact && Number.isFinite(totalUsage.cache_write_input_tokens)) {
131
- lines.push("", "Cache writes:", `TOTAL: ${writeTokens(totalUsage.cache_write_input_tokens)}`,
132
- ...modelUsage.filter(({ row }) => Number.isFinite(row.cache_write_input_tokens)).map(({ model, row }) => `${terminalCell(model)}: ${writeTokens(row.cache_write_input_tokens)}`));
131
+ lines.push("", "Cache writes:", `TOTAL: ${tokenCount(totalUsage.cache_write_input_tokens)}`,
132
+ ...modelUsage.filter(({ row }) => Number.isFinite(row.cache_write_input_tokens)).map(({ model, row }) => `${terminalCell(model)}: ${tokenCount(row.cache_write_input_tokens)}`));
133
133
  }
134
134
  if (table.compact) {
135
135
  lines.push(