codex-copilot-dx 1.3.11 → 1.3.12

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
@@ -2,9 +2,9 @@
2
2
 
3
3
  Use your model services in **Codex App, Claude App and Claude Code** through one local gateway.
4
4
 
5
- Connect GitHub Copilot, Microsoft 365 or your own API. Choose which apps can use each source, then select their models. CCDX supports **macOS and Windows**, on Apple Silicon/ARM64 and x64.
5
+ Connect GitHub Copilot, Microsoft 365 or your own API. Choose which apps can use each source, then select their models. CI and prebuilt releases cover **macOS on Apple Silicon** and **Windows on x64/ARM64**. Intel Mac code remains available, without CI coverage or new prebuilt assets.
6
6
 
7
- Optional local masking is off by default. Enable it in Settings → Advanced to download the model and component. Checks run locally and may add delay or mistake ordinary text; an unfinished check holds the request back. See [local masking](docs/REFERENCE.md#local-masking).
7
+ Optional local masking is off by default. Enable it in Settings → Local masking to download the model and component. Checks run locally and may add delay or mistake ordinary text; an unfinished check holds the request back. See [local masking](docs/REFERENCE.md#local-masking).
8
8
 
9
9
  ## Install and start
10
10
 
@@ -994,7 +994,7 @@ restart controller, transport policy or production dependency is introduced.
994
994
 
995
995
  ### 1.3 scope and state orchestration
996
996
 
997
- CCDX ships only for macOS and Windows (x64/ARM64). CI and complete-package builders use those four targets. The macOS bootstrap rejects unsupported systems before downloads. `ccdx` is the only package command; old CLI roots and aliases are removed without resetting accounts, keys, selected models or client-owned files.
997
+ CI and prebuilt releases cover macOS ARM64 and Windows x64/ARM64. `scripts/release-targets.mjs` limits publication asset collection and verification to those three targets. Intel Mac runtime, installer, updater and manual build paths remain unchanged; CI no longer tests Intel Macs or builds their runtime/privacy assets. The macOS bootstrap still rejects unsupported operating systems before downloads. `ccdx` is the only package command; old CLI roots and aliases are removed without resetting accounts, keys, selected models or client-owned files.
998
998
 
999
999
  Startup presentation classifies each formatted line independently. Normal checks are transient; mixed-message warnings and sign-in instructions remain visible. The live region labels the Web UI address and renders enabled sources once. `preserved` remains an internal configuration result and is displayed as `Unchanged`.
1000
1000
 
@@ -1056,19 +1056,19 @@ changes, rotation, incomplete tails, warnings and oversized results rebuild thro
1056
1056
  the original full scan. No persistent index, polling or per-token work is added.
1057
1057
  ### Local masking boundary
1058
1058
 
1059
- `local-privacy.mjs` owns explicit consent, per-request policy snapshots, a private placeholder seed and bounded shared detection metadata. It wraps provider calls after authorization/model resolution without changing the prepared request used by local history. Completed history records restore client-visible values while signed and encrypted state stays opaque. `privacy-transform.mjs` projects supported text fields, including Responses Lite inline tool descriptions. Tool data has its own recursive restoration context, so field names and values that resemble protocol state do not exempt ordinary arguments. Restored SSE fragments retain their wire metadata; Responses custom tool input shares text's cross-fragment restoration. Tool JSON is emitted once complete, before its terminal block, and incomplete parameters are discarded on an upstream failure. It does not take ownership of credentials or select providers.
1059
+ `local-privacy.mjs` owns explicit consent, per-request policy snapshots, a private placeholder seed and bounded shared detection metadata. It wraps provider calls after authorization/model resolution without changing the prepared request used by local history. Completed history records restore client-visible values while signed and encrypted state stays opaque. `privacy-transform.mjs` projects supported text fields, including Responses Lite inline tool descriptions. Tool data has its own recursive restoration context, so field names and values that resemble protocol state do not exempt ordinary arguments. Restored SSE fragments retain their wire metadata; Responses custom tool input shares text's cross-fragment restoration. `privacy-stream.mjs` restores argument fragments with a value-free incremental JSON validator, original event frames and bounded placeholder tails. Complete snapshots are authoritative; initial partial snapshots seed the same channel, and output indices correlate variant item IDs without rewriting opaque identities. Error terminals release unfinished state and do not manufacture tool completion. Inserted literal-tail deltas maintain increasing Responses sequence numbers. It does not take ownership of credentials or select providers.
1060
1060
 
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.
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 retains the existing preflight for already-downloaded, explicitly enabled protection; opening Settings never downloads a model. Accelerator initialization remains lazy. Cold and startup-plus-cold performance are independently reported. A native plan is capability-negotiated and carries only a text index and pending/total window counts. It cannot resolve a native job or release its admission slot. Shared waiters receive plans independently, including callers joining an existing flight.
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; 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.
1063
+ Disabled calls retain their original provider function and body. Enabled calls await a complete check. A frontend wait rejects without contacting the provider; it is normally 15 seconds and up to 60 seconds for plans with a 16 KiB pending batch or more than one pending native window. `privacy-detection.mjs` owns complete-text aliases, shared in-flight entries and two bounded native turns. Larger text entries remain whole; the new native component caches its exact token-window predictions by token IDs, without additional byte-piece overlaps. Non-O labels and exact scores stay within a separate 4 MiB/5,000-entry cache, without retaining text or token IDs. Original offsets and natural-window margin decoding remain unchanged. Supporting components acknowledge cancellation only after current windows are cached; a waiter joining a canceling job resumes after its acknowledgement. Older verified components retain their prior completion behavior. Submitted native work retains its completion promise, admission slot and valid cache result even after the last waiter leaves. 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. 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.
1065
+ The Magpie-derived Go tokenizer/INT8 classifier retains build support for four macOS/Windows targets; CI builds, native inference checks and publication cover macOS ARM64 and Windows x64/ARM64 only. 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. CPU inference allocates its intermediate matrix workspace once per window and overwrites it across layers without changing quantization, attention or residual arithmetic. CoreML holds one C-owned input provider per model under the existing prediction mutex. Buffers are cleared after success and error; no Go pointer or request text is retained by this reuse. 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
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
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.
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 raw argument data is capped at 8 MiB; retained tails, event metadata and incremental validator state share a 32 MiB budget with at most 1,024 channels. Failed or incomplete tool streams release their buffers without manufacturing completed arguments.
1072
1072
 
1073
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.
1074
1074
 
@@ -1098,4 +1098,8 @@ Unit suites are automatically discovered on macOS and Windows with Node 22.15 an
1098
1098
 
1099
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
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.
1101
+ Publication requires the explicit complete platform/Node/browser CI matrix on the exact tagged commit. It reuses that run's three runtime and three 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.
1102
+
1103
+ WebUI copy keeps its existing layout, controls, fonts and icons. Redundant branding and Codex-only tags are omitted in their existing contexts. Switches retain pending/error and saved-versus-effective distinctions; applicable scope, restart prerequisites and operation consequences remain visible. Local-masking sections use localized accessible names after the redundant category heading is removed. TUI/CLI commands retain explicit states and share the same control service.
1104
+
1105
+ Performance comparison is separate from runtime logic and reports paired timing without blocking publication. Each paired sample runs its JS detector and native helper in fresh processes, with copied model files at the same owned path. An exact binomial interval on paired medians retains uncertain and regressing observations. Classifier-result and reuse assertions remain blocking. The separate qualification workflow is manual only. Completely cached detection bypasses waiting machinery; uncached work retains its original bounded wait and physical acknowledgement.
package/docs/REFERENCE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # CCDX reference
2
2
 
3
- For installation and first use, start with the [README](../README.md). This reference covers operations and the limits that affect them. Supported systems are macOS and Windows, x64 and ARM64.
3
+ For installation and first use, start with the [README](../README.md). This reference covers operations and the limits that affect them. CI and prebuilt releases cover macOS ARM64 and Windows x64/ARM64. Intel Mac code and runtime paths remain available, without CI coverage or new prebuilt assets.
4
4
 
5
5
  ## Commands
6
6
 
@@ -31,7 +31,7 @@ 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 |
34
+ | `ccdx config privacy status` | Read model readiness, detection work, wait budget and latest reply failure |
35
35
  | `ccdx config privacy enable` / `disable` / `remove` | Prepare protection, stop later checks, or delete its model |
36
36
  | `ccdx config terminal` / `animation` | Choose terminal appearance |
37
37
  | `ccdx config limits [--decoded MiB]` | Read or change the decoded request limit |
@@ -128,6 +128,8 @@ Desktop spacing keeps existing fonts, palettes, navigation and disclosure anchor
128
128
 
129
129
  Use the installers linked in the [README](../README.md) when Node.js is unavailable. They support macOS and Windows on x64/ARM64, reuse a compatible Node.js, or install verified Node 24.22.0 privately. They do not install Git, compilers or system package managers, or change company registry/proxy/certificate/shell policy.
130
130
 
131
+ New complete Release packages and privacy binaries are published for macOS ARM64 and Windows x64/ARM64. Intel Macs retain the source-package installation path and can reuse verified compatible privacy components or build locally; new Intel binaries and CI validation are not provided.
132
+
131
133
  Complete Release packages include locked runtime dependencies. The updater verifies package identity, version and digests before installation, backs up the discovered package and launchers, and restores them on installation/runtime-check failure. A busy installation fails in place. Lock errors include the lock path; do not delete a lock held by another install.
132
134
 
133
135
  `ccdx update github` uses the latest stable Release. Normal source-package installation uses the configured registry. After npm EALLOWREMOTE, the updater can use a verified same-version complete platform package without relaxing npm policy. Other failures are not retried across arbitrary sources. Explicit `--allow-remote` grants URL downloads to that installation's whole dependency tree, not one hostname; use it only if policy permits. No persistent npm setting changes.
@@ -779,7 +781,7 @@ Usage queries share a bounded aggregate checkpoint only when file identities, fi
779
781
 
780
782
  ## Local masking
781
783
 
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.
784
+ Settings → 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.
783
785
 
784
786
  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.
785
787
 
@@ -787,9 +789,9 @@ Rules and a local model replace detected values with stable placeholders. Replie
787
789
 
788
790
  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.
789
791
 
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.
792
+ Each request pins its masking choice, including compatibility retries. Checks normally wait up to 15 seconds; a plan with at least one 16 KiB batch of uncached or in-flight text, or more than one pending native window, receives a bounded 60-second wait. A request still exceeding its wait is rejected before any upstream call. Submitted native batches finish and remain reusable; callers share in-flight work, and unused queued work stops. The 1.3.12 component reuses exact natural token-window predictions. Sparse non-O labels and exact scores use a separate 4 MiB/5,000-entry memory cache; original tokenization, window overlaps and current-text byte offsets are unchanged. Up to two text batches run concurrently, toward 16 KiB or 64 entries, keeping a larger individual text whole. Exact completed texts retain hot aliases. When the last waiter leaves, supporting components finish current windows, cache them and acknowledge cancellation before releasing the native slot. A waiter joining during cancellation resumes after acknowledgement; older compatible components finish whole batches as before. No request uses an incomplete model check. A native job retains its five-minute deadline and the native eight-job/16 MiB limits; the detection queue adds a 16 MiB/8,192-entry bound. Cache metadata remains within 5,000 entries/4 MiB, without storing detection history on disk. Cold-check cost and recovery are measured separately from hot reuse. Fully cached checks do not create native-work wait timers or cancellation listeners; they still honor caller cancellation before returning. CPU intermediate matrices are reused only within one inference. CoreML reuses one C-owned input array/provider per model under its existing mutex and clears its buffers after every successful or failed prediction. Go input memory is not retained by CoreML; classification mathematics and thread budgets are unchanged.
791
793
 
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.
794
+ Streaming restoration emits argument fragments incrementally with JSON string escaping, keeps protocol identities and signed state opaque, and validates completion against argument snapshots or incremental JSON syntax. Only unfinished placeholder tails and structural metadata are retained; raw argument bytes per channel remain capped at 8 MiB, retained tails/metadata/validator state at 32 MiB and active channels at 1,024. Added tail deltas preserve increasing Responses sequence numbers. An incomplete or failed upstream response does not manufacture a completed tool call. Successful frame bytes remain unchanged when restoration is unnecessary. A timeout or busy check reports that nothing was sent, with `Retry-After` for temporary waits. Model readiness, the latest check and the latest protected reply are separate. WebUI and `ccdx config privacy status` report pending detection and reply-restoration errors; the CLI retains explicit enabled/disabled values, while graphical switches omit duplicate normal-state labels; request details retain bounded error/event/channel codes and buffer quantities, never their values. A loaded model or HTTP 200 does not establish that a request or client tool completed.
793
795
 
794
796
  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.
795
797
 
@@ -799,4 +801,6 @@ Try locally sends sample text only to the local component. Request records show
799
801
 
800
802
  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.
801
803
 
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.
804
+ The optional component is pinned to v1.3.12. Verified older components, including 1.3.10, retain their original whole-text behavior. ABI 1 is unchanged; window reuse, advisory window plans and acknowledged cancellation are advertised capabilities. Plans contain only text indices and window counts, never request text. Startup retains its previous inexpensive preflight; accelerator initialization remains lazy. Native CI checks both cold detection and startup-plus-cold cost. 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.
805
+
806
+ Paired timing comparisons report cold, startup-plus-first-check, append and hot-check observations without blocking publication. Classifier correctness, byte verification and reuse assertions remain blocking. Real-use request records expose local-check duration and errors for observation after upgrading; fixed-machine results do not establish sustained real-use performance.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.11",
3
+ "version": "1.3.12",
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",
@@ -149,7 +149,7 @@ 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),
152
+ command("config privacy status", "Show masking readiness, detection work, wait budget and the latest reply failure", read),
153
153
  ...["enable", "disable", "remove"].map(action => command(`config privacy ${action}`,
154
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 })),
155
155
  command("config terminal", "Choose terminal color", {}),
@@ -130,7 +130,7 @@
130
130
  for (const key of ["terminal_animation_enabled", "open_webui", "image_enabled"]) {
131
131
  const input = el(`setting-${key}`), effective = data.effective[key];
132
132
  input.checked = data.saved[key];input.disabled = Boolean(effective.locked);
133
- label(el(`effect-${key}`), data.saved[key] === effective.value && !effective.locked ? "preference_effect" : "saved_saved_effective_effective_state", {
133
+ label(el(`effect-${key}`), data.saved[key] === effective.value && !effective.locked ? states[effective.state] || effective.state : "saved_saved_effective_effective_state", {
134
134
  saved: { key: data.saved[key] ? "on" : "off" }, effective: { key: effective.value ? "on" : "off" },
135
135
  state: { key: effective.locked ? "controlled_by_environment" : states[effective.state] || effective.state } });
136
136
  }
@@ -52,7 +52,8 @@
52
52
  el("prediction-open").disabled = !value?.configured;
53
53
  el("prediction-remove").disabled = !value?.configured;
54
54
  if (notes) localize(el("prediction-action-note"), !value ? "feature_unavailable" : value.status === "unavailable" ? "feature_read_failed" : pending ? "prediction_quit_continue" : value.enabled && value.bridge !== "running" ? "prediction_bridge_missing" : value.enabled ? "prediction_ready" : "prediction_disabled");
55
- localize(el("effect-prediction_enabled"), pending ? "feature_pending" : value?.enabled ? "on" : "off");
55
+ el("effect-prediction_enabled").hidden = !pending;
56
+ if (pending) localize(el("effect-prediction_enabled"), "feature_pending");
56
57
  const image = data.features?.image;
57
58
  if (!imageDirty) {
58
59
  el("image-setup-endpoint").value = image?.endpoint || "";
@@ -33,7 +33,7 @@
33
33
  <body>
34
34
  <div class="shell">
35
35
  <aside class="sidebar">
36
- <a class="sidebar-brand" href="#overview"><svg id="status-icon" class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg><span class="brand-name">CCDX</span><span class="brand-caption" data-i18n="local_control">LOCAL CONTROL</span></a>
36
+ <a class="sidebar-brand" href="#overview"><svg id="status-icon" class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg><span class="brand-name">CCDX</span></a>
37
37
  <nav aria-label="Navigation" data-i18n-label="main_navigation">
38
38
  <a href="#overview" data-route="overview" aria-current="page"><svg class="nav-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg><span data-i18n="overview">Overview</span></a>
39
39
  <span class="nav-group" data-i18n="clients">Apps</span>
@@ -48,7 +48,7 @@
48
48
  </aside>
49
49
 
50
50
  <header class="topbar">
51
- <div class="brand">CCDX <span class="brand-detail" data-i18n="local_status">/ DASHBOARD</span></div>
51
+ <div class="brand">CCDX </div>
52
52
  <div class="topbar-actions"><span id="connection" class="badge neutral" role="status" data-i18n="reading">READING</span><button id="theme-toggle" class="icon-button" type="button" aria-label="Switch to light mode" title="Switch to light mode"><svg class="icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42"/></svg><svg class="icon-moon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" focusable="false"><path d="M12 3A9 9 0 1 0 21 12 7 7 0 0 1 12 3Z"/></svg></button><button id="language-toggle" class="icon-button language-button" type="button" aria-label="Switch to Chinese" title="Switch to Chinese">中文</button><button id="auto-refresh" type="button" aria-pressed="true" data-i18n-title="activity_updates_live" title="Activity updates live. Catalogs and retained usage refresh on demand or every 30 minutes while open."><span class="auto-refresh-measure" aria-hidden="true" data-i18n="auto_refresh_off">Auto refresh · OFF</span><span id="auto-refresh-label" data-i18n="auto_refresh_on">Auto refresh · ON</span></button><button id="refresh" type="button" data-i18n="refresh">Refresh</button></div>
53
53
  </header>
54
54
 
@@ -66,7 +66,7 @@
66
66
  </div>
67
67
  <section class="overview" aria-label="Overview" data-i18n-label="overview"><article class="card"><h2 data-i18n="adapter">SERVICE</h2><strong id="version">—</strong><p id="uptime">—</p><p id="updated" class="refresh-time" data-i18n="reading_status">Reading status…</p></article><article class="card"><h2 data-i18n="sources">SOURCES</h2><strong id="source-summary">—</strong><p id="source-detail">—</p></article></section>
68
68
  <details class="panel dashboard-section" id="client-features" open>
69
- <summary class="panel-heading"><h2 data-i18n="client_connections">APP SETUP</h2><span data-i18n="configuration_observation">SETUP AND ACTIVITY</span></summary>
69
+ <summary class="panel-heading"><h2 data-i18n="client_connections">APP SETUP</h2></summary>
70
70
  <div class="table-wrap"><table><thead><tr><th data-i18n="client">APP</th><th data-i18n="current_source">Current source</th><th data-i18n="connection_setup" data-i18n-title="configured_not_successful">Setup</th><th data-i18n="local_bridge">Local service</th><th data-i18n="last_request">LAST REQUEST</th></tr></thead><tbody id="provider-clients"></tbody></table></div>
71
71
  </details>
72
72
  <section class="panel dashboard-section"><h2 data-i18n="this_run_usage">THIS RUN</h2><p id="runtime-usage" class="table-note"></p><p class="table-note"><span data-i18n="approx_cache_hit_rate">Approx. cache hit rate</span>: <strong id="runtime-cache-hit" data-i18n-title="runtime_cache_hit_basis" title="Reused / input tokens from records with valid counts for both. ~ Partial coverage. — No valid input basis.">—</strong></p><p class="hint" data-i18n="updated_from_returned_usage_not_a_live_bill_pending_usage_is_not">Counts returned usage only. Pending usage is not included. This is not a live bill.</p></section>
@@ -119,7 +119,7 @@
119
119
  <p id="review-control-note" class="hint" role="status"></p>
120
120
  </section>
121
121
  <details class="panel dashboard-section" id="prediction-settings" open>
122
- <summary class="panel-heading"><h2 data-i18n="codex_input_predictions">INPUT SUGGESTIONS</h2><span data-i18n="codex_only">CODEX ONLY</span></summary>
122
+ <summary class="panel-heading"><h2 data-i18n="codex_input_predictions">INPUT SUGGESTIONS</h2></summary>
123
123
  <div class="setting-row"><label for="setting-prediction_enabled" data-i18n="predictions_enable">Input suggestions</label><input id="setting-prediction_enabled" type="checkbox" role="switch" disabled><span id="effect-prediction_enabled" class="hint" role="status"></span></div>
124
124
  <p id="prediction-action-note" class="hint" role="status"></p><div class="section-actions"><button id="prediction-continue" type="button" data-i18n="feature_continue" hidden>Continue setup</button><button id="prediction-open" type="button" data-i18n="prediction_open">Open Codex</button></div>
125
125
  <details class="tool-details"><summary data-i18n="status_and_repair">Status and repair</summary>
@@ -131,7 +131,7 @@
131
131
  </details>
132
132
  </details>
133
133
  <details class="panel dashboard-section" id="additional-capabilities">
134
- <summary class="panel-heading"><h2 data-i18n="codex_image_generation">IMAGE GENERATION</h2><span data-i18n="codex_only">CODEX ONLY</span></summary>
134
+ <summary class="panel-heading"><h2 data-i18n="codex_image_generation">IMAGE GENERATION</h2></summary>
135
135
  <strong id="image">—</strong><p id="image-detail" class="hint">—</p>
136
136
  <div class="setting-row"><label for="setting-image_enabled" data-i18n="allow_new_image_calls">Allow image requests</label><input id="setting-image_enabled" type="checkbox" role="switch" disabled><span id="effect-image_enabled" class="hint" role="status"></span></div>
137
137
  <p class="hint" data-i18n="pause_keeps_the_provider_configuration_running_calls_can_finish_">Existing image requests can finish after pausing.</p>
@@ -437,8 +437,7 @@
437
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>
438
438
  </details></details><p id="update-copy-note" class="hint" role="status"></p>
439
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>
440
+ <section class="panel dashboard-section" id="privacy-settings" aria-label="Local masking" data-i18n-label="privacy_enable">
442
441
  <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
442
  <p class="hint" data-i18n="privacy_scope">Conversation and tool text. Images and predictions keep their current behavior.</p>
444
443
  <div id="privacy-options" hidden>
@@ -22,7 +22,7 @@
22
22
  image_setup_saved: ["Image generation configured. Existing App tasks may need to refresh their tools.", "图片生成已配置。现有 App 任务可能需要刷新工具。"],
23
23
  feature_unavailable: ["Restart the updated CCDX to use these controls.", "重启更新后的 CCDX 以使用这些控制。"],
24
24
  prediction_quit_continue: ["Quit Codex, then continue setup here. No terminal command is needed.", "请退出 Codex,再在此继续配置。无需终端命令。"],
25
- prediction_ready: ["Enabled. App and thread eligibility still apply.", "已开启。仍受 App 与会话适用条件限制。"],
25
+ prediction_ready: ["App and thread eligibility still apply.", "仍受 App 与会话适用条件限制。"],
26
26
  prediction_disabled: ["Disabled. Cached suggestions may require a normal App restart to clear.", "已关闭。缓存建议可能需要正常重开 App 才会清除。"],
27
27
  feature_pending: ["Waiting for Codex to close", "等待 Codex 退出"],
28
28
  update_external_launch: ["This launch cannot update itself. Use the installer or the installed CCDX command.", "此启动方式无法自行更新。请使用安装器或已安装的 CCDX 命令。"],
@@ -37,10 +37,11 @@
37
37
  api_remove_source: ["Delete API", "删除 API"],
38
38
  api_remove_source_confirm: ["Delete this disabled API and its saved key?", "删除此已停用 API 及其保存的密钥?"],
39
39
 
40
- 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", "已开启 · 本地检查中"],
40
+ privacy_heading: ["ADVANCED", "高级"], privacy_enable: ["Local masking", "本地脱敏"], privacy_scope: ["Conversation and tool text. Images and predictions keep their current behavior.", "检查对话和工具文本。图片与预测保持原有行为。"], privacy_state_checking: ["Checking locally", "本地检查中"],
41
41
  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", "删除模型"],
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
- 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"],
43
+ privacy_state_off: ["Off", "已关闭"], privacy_state_downloading: ["Downloading · {percent}%", "下载中 · {percent}%"], privacy_state_loading: ["Loading locally", "本地加载中"], privacy_state_ready: ["Keys and passwords", "密钥与密码"], privacy_state_error: ["Not ready", "尚未就绪"], privacy_state_installed: ["Downloaded · off", "已下载 · 已关闭"], privacy_result: ["{count} values masked · {ms} ms", "脱敏 {count} 项 · {ms} ms"],
44
+ privacy_response_error: ["Reply restoration failed ({code}). The reply was stopped.", "回复还原失败({code}),回复已停止。"],
44
45
  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
46
  privacy_busy: ["Local detection is busy. Nothing was sent; retry shortly.", "本地检测繁忙,未发送请求。请稍后重试。"],
46
47
  privacy_wait_timeout: ["Detection is still running. Nothing was sent; retry shortly to reuse its results.", "检测仍在进行,未发送请求。稍后重试可复用检测结果。"],
@@ -22,9 +22,11 @@
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-status").hidden = status === "off";
25
26
  el("privacy-device").textContent = state.backend ? state.device && state.device !== state.backend ? `${state.backend} · ${state.device}` : state.backend : "";
26
27
  const check = state.enabled && state.last_check?.state === "failed" ? state.last_check : null;
27
28
  if (state.error) words("privacy-error", state.error.includes("download") ? "privacy_download_error" : "privacy_error");
29
+ else if (state.enabled && state.last_response?.state === "failed") words("privacy-error", "privacy_response_error", { code: state.last_response.privacy_error || "ccdx_privacy_response_invalid" });
28
30
  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");
29
31
  else { el("privacy-error").textContent = "";el("privacy-error").removeAttribute("data-i18n"); }
30
32
  clearTimeout(timer);
@@ -10,7 +10,7 @@ html { scrollbar-gutter: stable; }
10
10
  .shell { max-width: 1220px; margin: 0 auto; padding: 0 24px; }
11
11
  .topbar { min-height: 68px; display: flex; justify-content: space-between; align-items: center; gap: 20px; border-bottom: 1px solid var(--top-border); }
12
12
  .brand { color: var(--accent); font-size: 16px; font-weight: 750; letter-spacing: .07em; white-space: nowrap; }
13
- .brand-detail { color: var(--subtle); font-size: 11px; font-weight: 500; letter-spacing: .03em; }
13
+
14
14
  .topbar-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: 20px; }
15
15
  .badge { color: var(--badge); white-space: nowrap; font-size: 11px; font-weight: 650; text-transform: uppercase; }
16
16
  .badge::before { content: "●"; margin-right: 8px; }
@@ -203,7 +203,7 @@ footer { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; color:
203
203
  @media (max-width: 1000px) { .overview { grid-template-columns: repeat(2, minmax(0, 1fr)); } .details { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
204
204
  @media (max-width: 680px) { .animation-options { grid-template-columns: 1fr; } }
205
205
  @media (max-width: 620px) { .snapshot-meta { justify-content: flex-start; margin-top: 9px; } }
206
- @media (max-width: 620px) { .shell { padding: 0 16px; } .topbar { min-height: 60px; } .brand-detail { display: none; } .topbar-actions { gap: 11px; } .intro { display: block; padding: 29px 0 21px; } .intro p { margin-top: 9px; } .overview, .details { grid-template-columns: 1fr; } .details .panel:last-child { grid-column: auto; } .card { min-height: 122px; } .card strong { margin-top: 14px; } .lower li { display: block; } .lower li span { display: block; margin-top: 5px; } }
206
+ @media (max-width: 620px) { .shell { padding: 0 16px; } .topbar { min-height: 60px; } .topbar-actions { gap: 11px; } .intro { display: block; padding: 29px 0 21px; } .intro p { margin-top: 9px; } .overview, .details { grid-template-columns: 1fr; } .details .panel:last-child { grid-column: auto; } .card { min-height: 122px; } .card strong { margin-top: 14px; } .lower li { display: block; } .lower li span { display: block; margin-top: 5px; } }
207
207
  @media (max-width: 460px) { .topbar { flex-wrap: wrap; padding: 12px 0; gap: 10px; } .topbar-actions { gap: 9px; } .panel-heading { flex-wrap: wrap; } .heading-actions { gap: 10px; } .failure-detail { grid-template-columns: 1fr; gap: 3px; } .failure-detail dd { margin-bottom: 7px; } select { max-width: 210px; } }
208
208
  .timing-stats { grid-template-columns: 1fr; }
209
209
  .timing-stats dt { white-space: nowrap; }
@@ -233,7 +233,7 @@ footer { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; color:
233
233
  .shell { max-width: 1520px; min-height: 100vh; display: grid; grid-template-columns: 204px minmax(0, 1fr); grid-template-rows: 64px minmax(0, 1fr) auto; column-gap: 34px; padding: 0 28px; }
234
234
  .sidebar { grid-row: 1 / 4; position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; padding: 28px 22px 24px 0; border-right: 1px solid var(--border); }
235
235
  .sidebar-brand { display: grid; grid-template-columns: 44px minmax(0, 1fr); align-items: center; column-gap: 12px; color: var(--accent); text-decoration: none; font-size: 23px; font-weight: 750; letter-spacing: .04em; }
236
- .sidebar-brand .brand-caption { display: block; color: var(--muted); font-size: 10px; font-weight: 500; letter-spacing: .1em; margin-top: 8px; }
236
+
237
237
  .sidebar nav { display: flex; flex-direction: column; gap: 5px; margin-top: 28px; }
238
238
  .sidebar nav a { color: var(--muted); text-decoration: none; padding: 8px 12px; font-size: 13px; border-left: 2px solid transparent; }
239
239
  .sidebar nav a:hover { background: var(--option-hover); color: var(--text); }
@@ -287,7 +287,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
287
287
  #process-queues { overflow-wrap: anywhere; font-size: 11px; }
288
288
  @media (max-width: 1100px) { .topbar .brand { display: none; } .topbar { justify-content: flex-end; } }
289
289
  @media (max-width: 900px) { .shell { grid-template-columns: 170px minmax(0, 1fr); column-gap: 20px; padding: 0 20px; } .setting-row { grid-template-columns: minmax(0, 1fr) 44px; } .setting-row .hint { grid-column: 1 / -1; } .overview { grid-template-columns: 1fr; } .shell { grid-template-rows: 96px minmax(0, 1fr) auto; } .topbar { height: 96px; } .topbar-actions { display: grid; grid-template-columns: 32px 40px max-content max-content; justify-content:end; gap: 8px 9px; width: 100%; } .topbar-actions #connection { grid-column: 1 / -1; width: auto; } .topbar-actions #auto-refresh { width: auto; min-width: 0; padding-inline: 8px; } }
290
- @media (max-width: 640px) { .shell { display: block; padding: 0 16px; } .sidebar { position: static; height: auto; padding: 20px 0 14px; border-right: 0; border-bottom: 1px solid var(--border); } .sidebar-brand { font-size: 20px; width: fit-content; } .sidebar-brand .brand-caption { margin-top: 4px; } .sidebar nav { display: flex; flex-direction: row; flex-wrap: wrap; gap: 4px; margin-top: 16px; } .sidebar nav a { padding: 9px 10px; font-size: 12px; border-left: 0; border-bottom: 2px solid transparent; } .sidebar nav a[aria-current="page"] { border-bottom-color: var(--accent); } .nav-group { display: none; } .topbar { min-height: 62px; justify-content: flex-start; } .topbar-actions { justify-content: flex-start; gap: 9px; } .intro { padding: 24px 0 18px; } .panel, .lower { padding: 17px; } .section-actions > label { width: 100%; } .stats { gap: 12px; } }
290
+ @media (max-width: 640px) { .shell { display: block; padding: 0 16px; } .sidebar { position: static; height: auto; padding: 20px 0 14px; border-right: 0; border-bottom: 1px solid var(--border); } .sidebar-brand { font-size: 20px; width: fit-content; } .sidebar nav { display: flex; flex-direction: row; flex-wrap: wrap; gap: 4px; margin-top: 16px; } .sidebar nav a { padding: 9px 10px; font-size: 12px; border-left: 0; border-bottom: 2px solid transparent; } .sidebar nav a[aria-current="page"] { border-bottom-color: var(--accent); } .nav-group { display: none; } .topbar { min-height: 62px; justify-content: flex-start; } .topbar-actions { justify-content: flex-start; gap: 9px; } .intro { padding: 24px 0 18px; } .panel, .lower { padding: 17px; } .section-actions > label { width: 100%; } .stats { gap: 12px; } }
291
291
 
292
292
  /* Keep forms aligned with the existing dashboard controls. */
293
293
  .dashboard-section + .client-overview { margin-top: 10px; }
@@ -369,7 +369,8 @@ export function createRequestAbort(req, res) {
369
369
 
370
370
  export function logRequestFailure(label, err, abort) {
371
371
  if (!isAbortLikeError(err) && !abort?.reason) {
372
- console.error(status("err", `${label} request failed: ${redactDiagnosticText(err.message)}`));
372
+ const privacyCode = err.origin === "privacy" && /^ccdx_privacy_[a-z_]+$/.test(err.code || "") ? err.code + ": " : "";
373
+ console.error(status("err", `${label} request failed: ${privacyCode}${redactDiagnosticText(err.message)}`));
373
374
  return;
374
375
  }
375
376
 
@@ -6,14 +6,16 @@ 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, validatePrivacyFindings } from "./privacy-transform.mjs";
9
+ import { maskPrivacyRequest, protectPrivacyResponse, createPrivacyRuleCache } from "./privacy-transform.mjs";
10
+ import { createPrivacyDetection, PRIVACY_BATCH_BYTES } from "./privacy-detection.mjs";
10
11
  import { markRequestObservation } from "./stream-performance.mjs";
11
12
 
12
13
  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 changes = createChangeSignal(), secret = randomBytes(32), responses = new WeakMap(), policies = new WeakMap();
14
15
  const model = options.model || createPrivacyModel({ ...options, changed: changes.changed });
15
16
  const rules = createPrivacyRuleCache();
16
- let cacheBytes = 0, generation = 0, pending = null, disposed = false;
17
+ const detection = createPrivacyDetection(model, options);
18
+ let generation = 0, pending = null, disposed = false, lastResponse = null;
17
19
  let keyLoaded = false, actionError = null, lastCheck = null;
18
20
  const settings = () => {
19
21
  const saved = readUserSettings({ ...options, strict: true });
@@ -22,7 +24,7 @@ export function createLocalPrivacy(options = {}) {
22
24
  const revision = saved => createHash("sha256").update(JSON.stringify(saved)).digest("hex");
23
25
  const snapshot = () => { const saved = settings(), detector = model.snapshot();return { ...detector, ...saved,
24
26
  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(),
27
+ ...(lastCheck.continuing ? { continuing: detection.busy() || detector.pending_checks > 0 } : {}) }, last_response: lastResponse && { ...lastResponse }, detection: detection.snapshot(), rule_cache: rules.stats(),
26
28
  ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
27
29
  function loadKey() {
28
30
  if (keyLoaded) return;
@@ -40,81 +42,36 @@ export function createLocalPrivacy(options = {}) {
40
42
  atomicWriteFileIfChangedSync(file, JSON.stringify({ ...saved, ...values }, null, 2) + "\n", { mode: 0o600 });
41
43
  });changes.changed();
42
44
  }
43
- async function find(texts, { signal } = {}) {
44
- if (signal?.aborted) throw signal.reason;
45
- const waiting = [], fresh = [], entries = [];
46
- for (const text of texts) {
47
- const key = createHash("sha256").update(text).digest("hex");
48
- if (cache.has(key)) {
49
- const saved = cache.get(key);cache.delete(key);cache.set(key, saved);waiting.push(Promise.resolve(saved.found));
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);
57
- }
58
- }
59
- const finish = (entry, value, error) => {
60
- if (entry.done) return;
61
- entry.done = true;entry.text = null;
62
- if (flights.get(entry.key) === entry) flights.delete(entry.key);
63
- if (error) entry.reject(error);else entry.resolve(value);
64
- };
65
- const run = async () => {
66
- let at = 0;
67
- try {
68
- while (at < fresh.length) {
69
- const batch = [];let bytes = 0;
70
- while (at < fresh.length && batch.length < 64) {
71
- const entry = fresh[at];
72
- if (!entry.waiters) { finish(entry, null, privacyFailure("cancelled"));at++;continue; }
73
- const size = Buffer.byteLength(entry.text);
74
- if (batch.length && bytes + size > (options.batchBytes ?? 16 * 1024)) break;
75
- batch.push(entry);bytes += size;at++;
76
- }
77
- if (!batch.length) continue;
78
- // A submitted batch finishes even if its callers leave. Whole text
79
- // entries keep their context; later batches can yield unused work.
80
- const input = batch.map(entry => entry.text), found = validatePrivacyFindings(input, await model.find(input));
81
- for (let i = 0; i < found.length; i++) {
82
- const cost = Buffer.byteLength(JSON.stringify(found[i])) + 128, entry = batch[i];
83
- if (cost <= 1024 * 1024) {
84
- const previous = cache.get(entry.key);if (previous) cacheBytes -= previous.bytes;
85
- cache.set(entry.key, { found: found[i], bytes: cost });cacheBytes += cost;
86
- while (cache.size > 5000 || cacheBytes > 4 * 1024 * 1024) { const oldest = cache.keys().next().value;cacheBytes -= cache.get(oldest).bytes;cache.delete(oldest); }
87
- }
88
- finish(entry, found[i]);
89
- }
90
- }
91
- } catch (error) {
92
- for (const entry of fresh) finish(entry, null, error);
93
- }
94
- };
95
- if (fresh.length) void run();
96
- let listener;
97
- const aborted = new Promise((_, reject) => { listener = () => reject(signal.reason);if (signal?.aborted) listener();else signal?.addEventListener("abort", listener, { once: true }); });
98
- try { return await (signal ? Promise.race([Promise.all(waiting), aborted]) : Promise.all(waiting)); }
99
- finally { signal?.removeEventListener("abort", listener);for (const entry of entries) entry.waiters--; }
100
- }
45
+ const find = (texts, options) => detection.find(texts, options);
101
46
  async function prepare(body, { protocol, client, signal, res, policy } = {}) {
102
47
  const saved = policy || settings();if (!saved.enabled) return body;
103
48
  if (disposed) throw privacyFailure("engine_unavailable");
104
49
  loadKey();
105
50
  const start = performance.now();
106
- const deadline = AbortSignal.timeout(options.checkTimeoutMs ?? 15000);let session;
107
- try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, rules: rules.find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
51
+ const deadline = new AbortController();let session, timer, budget = options.checkTimeoutMs ?? 15000;
52
+ const arm = () => {
53
+ clearTimeout(timer);timer = setTimeout(() => deadline.abort(privacyFailure("check_timeout", "waiting")), Math.max(1, budget - (performance.now() - start)));
54
+ timer.unref?.();
55
+ };
56
+ const onPlan = plan => {
57
+ const previous = budget;
58
+ if (options.checkTimeoutMs === undefined && (plan.pending_bytes >= PRIVACY_BATCH_BYTES || plan.pending_windows > 1)) budget = 60000;
59
+ if ((budget !== previous && timer) || (!timer && (plan.texts > 0 || plan.pending_windows > 0))) arm();
60
+ markRequestObservation({ ...(Number.isSafeInteger(plan.pending_bytes) ? { privacy_pending_bytes: plan.pending_bytes, privacy_new_bytes: plan.new_bytes } : {}),
61
+ ...(Number.isSafeInteger(plan.pending_windows) ? { privacy_pending_windows: plan.pending_windows } : {}), privacy_wait_budget_ms: budget });
62
+ };
63
+ try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, rules: rules.find, onPlan,
64
+ signal: signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal }); }
108
65
  catch (error) {
109
- const failure = deadline.aborted && !signal?.aborted ? privacyFailure("check_timeout", "waiting") : error;
66
+ const failure = deadline.signal.aborted && !signal?.aborted ? privacyFailure("check_timeout", "waiting") : error;
110
67
  const elapsed = Math.round(performance.now() - start), cancelled = signal?.aborted === true;
111
68
  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 };
69
+ code: /^ccdx_privacy_[a-z_]+$/.test(failure?.code || "") ? failure.code : cancelled ? "ccdx_privacy_cancelled" : "ccdx_privacy_unavailable", continuing: !cancelled && failure?.retryAfter === 5, wait_budget_ms: budget };
113
70
  markRequestObservation({ privacy_ms: elapsed, privacy_state: cancelled ? "cancelled" : "failed" });changes.changed();throw failure;
114
- }
71
+ } finally { clearTimeout(timer); }
115
72
  if (signal?.aborted) { session.release();throw signal.reason; }
116
73
  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();
74
+ actionError = null;lastCheck = { state: "checked", at: new Date().toISOString(), elapsed_ms: Math.round(performance.now() - start), count: session.count, wait_budget_ms: budget };changes.changed();
118
75
  if (res && session.count) {
119
76
  let current = responses.get(res);
120
77
  if (!current) {
@@ -124,7 +81,10 @@ export function createLocalPrivacy(options = {}) {
124
81
  restoreValue: value => sessions.reduce((text, item) => item.restoreValue(text), value),
125
82
  restoreToolValue: value => sessions.reduce((text, item) => item.restoreToolValue(text), value),
126
83
  release: () => { sessions.forEach(item => item.release());sessions.length = 0;responses.delete(res); } };
127
- responses.set(res, current);sessions.push(session);protectPrivacyResponse(res, current);
84
+ responses.set(res, current);sessions.push(session);protectPrivacyResponse(res, current, {
85
+ onFailure(details) { lastResponse = { state: "failed", at: new Date().toISOString(), ...details };changes.changed(); },
86
+ onComplete() { lastResponse = { state: "completed", at: new Date().toISOString() };changes.changed(); },
87
+ });
128
88
  } else current.sessions.push(session);
129
89
  }
130
90
  return session.body;
@@ -140,7 +100,7 @@ export function createLocalPrivacy(options = {}) {
140
100
  if (input.action === "personal") {
141
101
  if (typeof input.personal !== "boolean") throw privacyFailure("action_invalid");save({ privacy_personal: input.personal }, input.revision);
142
102
  } else if (input.action === "disable" || input.action === "remove") {
143
- generation++;actionError = null;save({ privacy_enabled: false }, input.revision);model.stop();
103
+ generation++;actionError = null;save({ privacy_enabled: false }, input.revision);detection.cancelQueued();model.stop();
144
104
  if (input.action === "remove") await model.remove();
145
105
  } else if (input.action === "enable") {
146
106
  if (pending) return snapshot();
@@ -158,7 +118,7 @@ export function createLocalPrivacy(options = {}) {
158
118
  }
159
119
  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(); }); }
160
120
  try { warm(); } catch { /* Invalid preferences remain visible and are never rewritten. */ }
161
- return { snapshot, action, prepare, subscribe: changes.subscribe, busy: () => Boolean(pending || flights.size || model.busy()),
121
+ return { snapshot, action, prepare, subscribe: changes.subscribe, busy: () => Boolean(pending || detection.busy() || model.busy()),
162
122
  wrap(fn, context) {
163
123
  if (!fn) return fn;
164
124
  const policy = context.res && policies.get(context.res) || settings();if (context.res) policies.set(context.res, policy);
@@ -172,5 +132,5 @@ export function createLocalPrivacy(options = {}) {
172
132
  },
173
133
  restoreResponse: (res, value) => responses.get(res)?.restoreValue(value) || value,
174
134
  settingsChanged() { actionError = null;if (!settings().enabled) { generation++;model.stop(); }else warm();changes.changed(); },
175
- close() { disposed = true;generation++;model.close();cache.clear();rules.clear();cacheBytes = 0;secret.fill(0); } };
135
+ close() { disposed = true;generation++;detection.close();model.close();rules.clear();secret.fill(0); } };
176
136
  }