codex-copilot-dx 1.3.8 → 1.3.10

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
@@ -17,8 +17,8 @@ ccdx
17
17
 
18
18
  Without Node.js, download and run the installer for your system:
19
19
 
20
- - macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.8/install.sh), then `sh install.sh`.
21
- - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.8/install.ps1), then `./install.ps1` under your current shell policy.
20
+ - macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/latest/download/install.sh), then `sh install.sh`.
21
+ - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/latest/download/install.ps1), then `./install.ps1` under your current shell policy.
22
22
 
23
23
  The installer reuses a compatible Node.js or installs a private, verified copy. Git and a compiler are not required. Complete platform packages include their dependencies. Company registry, proxy, certificate and shell policies are kept.
24
24
 
@@ -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.
@@ -521,7 +521,7 @@ projects the optional lightweight response; full status stays the default public
521
521
  contract. Hidden status regions defer DOM updates, and summary rendering never
522
522
  replaces the full request/history cache.
523
523
 
524
- `dashboard/usage.js` owns bar/curve geometry and viewport-gated, one-shot Web Animations. The two views share retained analytics and accessible day buttons; their paths never connect unavailable history or overshoot adjacent values. View-only changes leave the calendar nodes intact. The UI lifecycle cancels motion on hidden/suspended views and reduced-motion changes; no animation timer or chart dependency is added. `usage-store.mjs` shares cache-evidence validation between retained summaries and process-local totals; runtime snapshots expose the weighted cache ratio plus a partial-evidence flag, without new persistence or log scans. The Overview renderer formats that snapshot and preserves unknown/invalid values.
524
+ `dashboard/usage.js` owns bar/curve geometry and viewport-gated, one-shot Web Animations. The two views share retained analytics and accessible day buttons; their paths never connect unavailable history or overshoot adjacent values. View-only changes leave the calendar nodes intact. The UI lifecycle cancels motion on hidden/suspended views and reduced-motion changes; no animation timer or chart dependency is added. `usage-store.mjs` shares cache-evidence validation between retained summaries and process-local totals. It keeps paired input/cache-read sums and known/unknown record counts separate from full token totals; CLI/TUI, WebUI and daily analytics use those same sums for the weighted rate and partial-coverage flag. Aggregate snapshots expose that basis without new persistence or log scans. The Overview renderer formats that snapshot and preserves unknown/invalid values.
525
525
 
526
526
  `dashboard-updates.mjs` is loaded only by the protected update-information route. It projects bounded public stable-release metadata and publication dates, with process-local single-flight, five-minute success and one-minute failure caches. Its asynchronous npm network-configuration read reuses the installer's existing policy-preserving downloader; it adds no runtime dependency, credentials or synchronous child process on the service event loop. Metadata has a four-second per-request deadline and 128 KiB decoded-body bound. It never installs or restarts anything and does not alter startup's independent web-redirect lookup. `dashboard/updates.js` renders current/available/unknown states and validated, pinned installation command text; `refresh.js` owns its visible Settings refresh cadence. Failed checks preserve explicitly labeled prior metadata. No provider authentication or inference is involved.
527
527
 
@@ -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
 
@@ -1079,3 +1081,21 @@ Claude passthrough now holds incomplete SSE frames and validates complete data b
1079
1081
  The existing supervisor accepts a bounded manual update request as well as its optional nightly scheduler. Both use the same staged package verification, immutable worker, state-transfer, installation commit and rollback path. Manual and scheduled updates are mutually exclusive; settings operations contribute to busy state and image configuration and stable prediction intent/trust participate in the state fingerprint; native port allocation and App stat bookkeeping do not. Warm handoff suppresses first-time prediction setup and pending display writes. Explicit prediction reconfiguration replaces the old bridge after committing trust. An unowned installation falls back to the existing standalone launch and exposes that self-update is unavailable. No inference protocol, privacy transport or native authentication path is changed by these controls.
1080
1082
 
1081
1083
  Native discovery, configuration and startup environment inspection run in bounded temporary `prediction-operations.mjs` workers. PowerShell, certificate and filesystem work do not block the gateway event loop. Registered-App discovery precedes default trust/proxy setup; missing Apps leave core startup available. Private environment results feed only bridge initialization and are not returned by WebUI actions.
1084
+
1085
+ ### Stable Messages prefixes and bounded privacy work
1086
+
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.
1088
+
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.
1092
+
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.
1094
+
1095
+ ### CI and release evidence
1096
+
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.
1098
+
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; the temporary tag is removed. 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 |
@@ -106,7 +108,7 @@ Catalog diagnostics distinguish local cached data from an online response and ex
106
108
  - **Local checks:** `doctor` is read-only by default. `--online` checks access; `--compat` sends minimal inference and consumes usage. `--fix` backs up owned configuration and performs bounded repairs. It does not enable optional features, change company policy or force-restart apps. Partial repairs exit 1.
107
109
  - **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
108
110
 
109
- Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input, with unknown/partial data indicated. It is not a request-based cache rate or a billing receipt.
111
+ Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input from records with valid counts for both. Unknown/invalid records remain in token totals but are excluded from both sides of the rate, with partial coverage indicated. It is not a request-based cache rate or a billing receipt.
110
112
 
111
113
  ## Settings and appearance
112
114
 
@@ -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 |
@@ -684,7 +688,13 @@ When upstream responses contain usage fields, CCDX records token counts, model n
684
688
  ccdx usage
685
689
  ```
686
690
 
687
- The summary covers the current log and its single rotated backup, not an unbounded lifetime history. It reports recorded responses and per-model input, cache-read, output, and total token metadata.
691
+ The summary covers the current log and its single rotated backup, not an unbounded lifetime history. It reports recorded responses and per-model input, cache-read, cache-write, output, and total token metadata.
692
+
693
+ M365 preserves system instructions at their original mid-conversation position. This avoids moving each new reminder ahead of the already cached history. Other Claude App API endpoints keep legacy behavior unless the model's `mid_conversation_system` capability is explicitly true. A false override selects legacy hoisting; Responses and Chat use their existing paths. This preserves instruction priority rather than converting system messages to user text.
694
+
695
+ Messages input is the sum of Anthropic uncached input, cache-read and cache-creation tokens. Cache creation is new input, not a cache hit; output tokens, including thinking output, are not added to the cache-hit denominator. M365 follows this same protocol accounting. Cache writes are shown separately when reported; missing write counts remain unknown. Stream usage updates replace cumulative counters, preserve earlier values when a later field is null or absent, and retain explicit zero. Each gateway request writes at most one usage row; forwarded usage is unchanged.
696
+
697
+ CLI/TUI, WebUI totals and daily analytics use the same paired evidence for cache rates. Aggregate JSON exposes `cache_hit_known_requests`, `cache_hit_unknown_requests`, `cache_hit_input_tokens` and `cache_hit_read_tokens` so the rate and its coverage can be checked. `~` marks incomplete coverage; a rate without a positive known input basis remains unknown. Historical logs are re-aggregated without rewriting their records, and unknown cache values are never filled with zero.
688
698
 
689
699
  Usage writes are asynchronous and batched under the existing cross-process rotation lock. Pending and in-flight records share a 4096-record / 4 MiB ceiling. If either ceiling is reached, new excess records are dropped with a warning and a status counter; inference does not wait or retry. Normal records and per-record rotation boundaries are unchanged. The bounded shutdown flush remains 1.5 seconds; disk failures and shutdown deadlines can prevent persistence, so usage is diagnostic rather than a billing ledger.
690
700
 
@@ -769,7 +779,7 @@ Usage queries share a bounded aggregate checkpoint only when file identities, fi
769
779
 
770
780
  ## Local masking
771
781
 
772
- 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.
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.
773
783
 
774
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.
775
785
 
@@ -777,12 +787,16 @@ Rules and a local model replace detected values with stable placeholders. Replie
777
787
 
778
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.
779
789
 
780
- 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.
781
793
 
782
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.
783
795
 
784
- 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. Download failures keep protection off; 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.
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
+
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.
785
799
 
786
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.
787
801
 
788
- The optional component is pinned to the v1.3.6 Release; later code-only updates can reuse it. 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.8",
3
+ "version": "1.3.10",
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",
@@ -38,7 +38,7 @@
38
38
  "node": ">=22.15.0"
39
39
  },
40
40
  "scripts": {
41
- "test": "node --test",
41
+ "test": "node scripts/run-tests.mjs",
42
42
  "test:smoke": "node scripts/offline-smoke.mjs && node scripts/sse-idle-replay.mjs",
43
43
  "test:package": "node scripts/package-lifecycle-smoke.mjs",
44
44
  "test:nightly-package": "node scripts/nightly-package-replay.mjs",
@@ -47,7 +47,7 @@
47
47
  "bench:payload": "node scripts/benchmark.mjs --large-payload",
48
48
  "bench:check": "node scripts/benchmark.mjs --check",
49
49
  "pack:check": "npm pack --dry-run --json",
50
- "verify": "npm test && npm run test:smoke && npm run bench:check && npm run pack:check",
50
+ "verify": "node scripts/verify.mjs",
51
51
  "prepublishOnly": "npm run verify",
52
52
  "release:pack": "node scripts/release-artifacts.mjs",
53
53
  "release:runtime": "node scripts/runtime-package.mjs",
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
  });
@@ -17,6 +17,8 @@ import { operationErrorDetails, transportErrorDetails } from "./operation-error.
17
17
  import { requestApplication } from "./request-application.mjs";
18
18
  import { observeContextSession } from "./context-metrics.mjs";
19
19
  import { catalogCapabilities } from "./model-capabilities.mjs";
20
+ import { applyMessagesSystemPolicy } from "./messages-system-policy.mjs";
21
+ import { createApiTokenCounter } from "./providers/api-token-count.mjs";
20
22
 
21
23
  function observeMessagesWindow(provider, model, capability, entry) {
22
24
  try {
@@ -39,19 +41,6 @@ function send(res, code, value) {
39
41
  const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
40
42
  const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
41
43
  || typeof block.text === "string" && block.text.length || typeof block.thinking === "string" && block.thinking.length));
42
- function desktopMessages(body) {
43
- const messages = [], instructions = [];
44
- const blocks = content => {
45
- if (typeof content === "string") return [{ type: "text", text: content }];
46
- if (Array.isArray(content) && content.every(block => block?.type === "text" && typeof block.text === "string")) return content;
47
- throw Object.assign(new Error("System instructions must contain text"), { code: "ccdx_messages_system_invalid", statusCode: 400 });
48
- };
49
- for (const message of body.messages) {
50
- if (message?.role === "system") instructions.push(...blocks(message.content));
51
- else messages.push(message);
52
- }
53
- return instructions.length ? { ...body, system: [...(body.system === undefined ? [] : blocks(body.system)), ...instructions], messages } : body;
54
- }
55
44
  function authenticated(headers, key) {
56
45
  const candidates = [headers["x-api-key"], typeof headers.authorization === "string" ? /^Bearer (.+)$/i.exec(headers.authorization)?.[1] : null];
57
46
  const expected = Buffer.from(key);
@@ -106,12 +95,13 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
106
95
  finish() { output = [];consume(decoder.decode());if (fragments.length) line(fragments.join(""), false);if (wire.length && !/\r?\n\r?\n$/.test(wire.join(""))) wire.push("\n\n");frame();return output; } };
107
96
  }
108
97
 
109
- export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
98
+ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
110
99
  resolveRequest, privacy, privacyClient = "claude", record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
111
100
  if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
112
101
  const config = loadRuntimeConfig(env), performance = sharedPerformance || createStreamPerformanceMetrics({ routeNames: ["messages"] });
113
102
  const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
114
103
  const stats = { total: 0, active: 0, completed: 0, incomplete: 0, failed: 0, cancelled: 0, last_request_at: null, last_model: null };
104
+ const countCoordinators = new WeakMap();
115
105
  async function dispatch(req, res) {
116
106
  let selectedProvider = provider, finishProvider = () => {};
117
107
  if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers.host === undefined || !isLoopbackHostHeader(req.headers.host)
@@ -162,7 +152,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
162
152
  body = { ...body, model: configuredModel };tracker?.setProvider(selectedProvider.id);
163
153
  const context = currentRequestContext();if (context) context.provider = selectedProvider.id;
164
154
  }
165
- if (desktopAliases) body = desktopMessages(body);
155
+ const inlineSystem = selectedCapability?.values?.mid_conversation_system;
156
+ body = applyMessagesSystemPolicy(body, inlineSystem === true ? "native" : inlineSystem === false ? "legacy" : selectedProvider.messagesSystemMode ?? messagesSystemMode);
166
157
  model = body.model;streamed = !countTokens && body.stream === true;
167
158
  if (!resolveRequest && (provider.configuredModels || desktopAliases)) {
168
159
  selectedModel = resolveClaudeModel(provider.models("claude"), model, { desktopAliases });
@@ -181,7 +172,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
181
172
  if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
182
173
  terminalOrigin = "transport";
183
174
  const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
184
- const upstream = await call(body, { headers: req.headers, countTokens, signal: abort.signal,
175
+ const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
185
176
  onCountObservation(value) {
186
177
  context.countObservation = { ...context.countObservation, ...value };
187
178
  if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
@@ -191,7 +182,16 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
191
182
  const timeout = streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs;
192
183
  if (countTokens) countDeadline ??= Date.now() + timeout;
193
184
  abort.setTimeout(countTokens ? Math.max(1, countDeadline - Date.now()) : timeout, "upstream_timeout");
194
- } });
185
+ } };
186
+ let upstream;
187
+ if (countTokens && selectedProvider.coordinateMessagesCounts) {
188
+ let counter = countCoordinators.get(selectedProvider);
189
+ if (!counter) {
190
+ counter = createApiTokenCounter({ request: (value, options) => options.perform(value, options) });
191
+ countCoordinators.set(selectedProvider, counter);
192
+ }
193
+ upstream = await counter.count(body, { ...callOptions, perform: call });
194
+ } else upstream = await call(body, callOptions);
195
195
  body = null;
196
196
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
197
197
  tracker?.upstreamHeaders(upstream.status);
@@ -234,7 +234,10 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
234
234
  || event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) conversation?.commit?.({ tool: event.content_block?.type === "tool_use" });
235
235
  if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
236
236
  if (event.type === "content_block_delta" && isMessagesOutputDelta(event.delta)) tracker?.firstOutput();
237
- if (event.type === "message_delta") { usage = { ...usage, ...event.usage };stopReason = event.delta?.stop_reason || stopReason; }
237
+ if (event.type === "message_delta") {
238
+ usage = { ...usage, ...Object.fromEntries(Object.entries(event.usage || {}).filter(([, value]) => value != null)) };
239
+ stopReason = event.delta?.stop_reason || stopReason;
240
+ }
238
241
  if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
239
242
  }, config.maxSseBufferBytes, clientModel);
240
243
  const reader = upstream.body.getReader();
@@ -267,6 +270,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
267
270
  context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
268
271
  if (outcome === "cancelled") return;
269
272
  if (!res.headersSent) {
273
+ if (error.origin === "privacy" && Number.isInteger(error.retryAfter) && error.retryAfter > 0) res.setHeader("Retry-After", String(error.retryAfter));
270
274
  const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
271
275
  if (rejectionReason) value.error.reason = rejectionReason;
272
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" });
@@ -1477,6 +1477,7 @@ export function createConnectionRuntime({
1477
1477
  log,
1478
1478
  performance: legacy.claudePerformance,
1479
1479
  desktopAliases: id === "claude_app",
1480
+ messagesSystemMode: id === "claude_app" ? "legacy" : "passthrough",
1480
1481
  resolveRequest(body) {
1481
1482
  const record = resolveDeployment(id, body.model),
1482
1483
  finish = track(record.provider);
@@ -178,7 +178,7 @@
178
178
  const note = node("p", undefined, "hint");words(note, "cap_metadata_scope");advanced.append(note);
179
179
  const fields = node("div", undefined, "connection-fields");
180
180
  const numeric = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max"];
181
- const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output"];
181
+ const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output", "mid_conversation_system"];
182
182
  const arrays = ["reasoning_efforts", "thinking_modes", "input_modalities", "web_search"];
183
183
  for (const key of [...numeric, ...flags, ...arrays, "reasoning_format"]) {
184
184
  const label = node("label"), title = node("span");words(title, "cap_field_" + key);label.append(title);
@@ -1,6 +1,6 @@
1
1
  (() => {
2
2
  function create({ element: el, change, localize }) {
3
- let saved = null, imageDirty = false;
3
+ let saved = null, imageDirty = false, limitDirty = false;
4
4
  const prediction = operation => change({ action: "prediction", operation }, el("prediction-continue"));
5
5
  el("setting-prediction_enabled").addEventListener("change", () => void prediction(el("setting-prediction_enabled").checked ? "enable" : "disable"));
6
6
  el("prediction-continue").addEventListener("click", () => void prediction(saved?.features?.prediction?.enabled ? "enable" : "disable"));
@@ -31,8 +31,13 @@
31
31
  const data = await change({ action: "image", operation: "remove" }, el("image-setup-remove"));
32
32
  if (data) { imageDirty = false;el("image-setup-key").value = "";render(data); }
33
33
  });
34
- el("decoded-limit-save").addEventListener("click", () => void change({ action: "decoded_limit", mib: Number(el("decoded-limit").value) }, el("decoded-limit-save")));
35
- el("decoded-limit-default").addEventListener("click", () => void change({ action: "decoded_limit", mib: null }, el("decoded-limit-default")));
34
+ el("decoded-limit").addEventListener("input", () => { limitDirty = true; });
35
+ const saveLimit = async mib => {
36
+ const data = await change({ action: "decoded_limit", mib }, el(mib === null ? "decoded-limit-default" : "decoded-limit-save"));
37
+ if (data?.decoded_body) { limitDirty = false;render(data); }
38
+ };
39
+ el("decoded-limit-save").addEventListener("click", () => void saveLimit(Number(el("decoded-limit").value)));
40
+ el("decoded-limit-default").addEventListener("click", () => void saveLimit(null));
36
41
  el("install-update").addEventListener("click", () => {
37
42
  if (window.confirm(globalThis.ccdxLanguage.format("update_install_confirm"))) void change({ action: "update", confirmed: true }, el("install-update"));
38
43
  });
@@ -55,7 +60,7 @@
55
60
  }
56
61
  el("image-setup-remove").disabled = !image?.configured;
57
62
  const limit = data.decoded_body;
58
- if (document.activeElement !== el("decoded-limit")) el("decoded-limit").value = limit?.bytes / 1048576 || 128;
63
+ if (!limitDirty && document.activeElement !== el("decoded-limit")) el("decoded-limit").value = limit?.bytes / 1048576 || 128;
59
64
  el("decoded-limit").disabled = el("decoded-limit-save").disabled = el("decoded-limit-default").disabled = !limit || limit.source === "environment";
60
65
  localize(el("decoded-limit-note"), limit?.source === "environment" ? "controlled_by_environment" : "next_ccdx_start");
61
66
  el("install-update").disabled = !data.manual_update?.available;
@@ -69,7 +69,7 @@
69
69
  <summary class="panel-heading"><h2 data-i18n="client_connections">APP SETUP</h2><span data-i18n="configuration_observation">SETUP AND ACTIVITY</span></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
- <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 / input tokens. ~ Partial counts. — Unknown or invalid.">—</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>
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>
73
73
  </div>
74
74
  <div data-view="codex" hidden>
75
75
  <div id="codex-model-management"> <section class="connection-access" id="connection-clients">
@@ -127,8 +127,7 @@
127
127
  <p id="prediction-note" class="hint">—</p>
128
128
 
129
129
 
130
- <div class="section-actions"><button id="fix-prediction" type="button" data-i18n="check_and_repair">Check and repair</button></div>
131
- <button id="prediction-setup" type="button" data-i18n="prediction_setup_again">Set up again</button><button id="prediction-remove" type="button" data-i18n="feature_remove">Remove setup</button>
130
+ <div class="section-actions"><button id="fix-prediction" type="button" data-i18n="check_and_repair">Check and repair</button><button id="prediction-setup" type="button" data-i18n="prediction_setup_again">Set up again</button><button id="prediction-remove" type="button" data-i18n="feature_remove">Remove setup</button></div>
132
131
  </details>
133
132
  </details>
134
133
  <details class="panel dashboard-section" id="additional-capabilities">
@@ -314,9 +313,9 @@
314
313
  <summary class="panel-heading"><h2 data-i18n="usage_totals">USAGE TOTALS</h2><span id="usage-state" data-i18n="reading_log">COUNTING</span></summary>
315
314
  <div class="section-actions"><button id="clear-usage-day" type="button" hidden data-i18n="all_history">Show all</button></div>
316
315
  <p id="usage-note" class="table-note" data-i18n="aggregating_local_usage_metadata">Counting local usage…</p>
317
- <div class="table-wrap"><table class="usage-table"><thead><tr><th scope="col" data-i18n="model">MODEL</th><th scope="col" data-i18n="calls">REQUESTS</th><th scope="col" data-i18n="input">INPUT USAGE</th><th scope="col" data-i18n="cache_read">REUSED INPUT</th><th scope="col" data-i18n="output">OUTPUT USAGE</th><th scope="col" data-i18n="total">TOTAL</th><th scope="col" data-i18n="cache_hit">REUSE RATE</th></tr></thead><tbody id="usage-body"><tr><td colspan="7" data-i18n="loading">Loading…</td></tr></tbody></table></div>
318
- <p class="hint" data-i18n="cache_hit_recorded_cached_input_tokens_incomplete_history_unavai">Unit: Token. Reused input is part of input.
319
- ~ Partial records. — Unknown or invalid.</p>
316
+ <div class="table-wrap"><table class="usage-table"><thead><tr><th scope="col" data-i18n="model">MODEL</th><th scope="col" data-i18n="calls">REQUESTS</th><th scope="col" data-i18n="input">INPUT USAGE</th><th scope="col" data-i18n="cache_read">REUSED INPUT</th><th scope="col" data-i18n="cache_write">CACHE WRITE</th><th scope="col" data-i18n="output">OUTPUT USAGE</th><th scope="col" data-i18n="total">TOTAL</th><th scope="col" data-i18n="cache_hit">REUSE RATE</th></tr></thead><tbody id="usage-body"><tr><td colspan="8" data-i18n="loading">Loading…</td></tr></tbody></table></div>
317
+ <p class="hint" data-i18n="cache_hit_recorded_cached_input_tokens_incomplete_history_unavai">Unit: Token. Reused input is part of input. Rate uses records with valid input and cache-read counts.
318
+ ~ Partial coverage. — No valid input basis.</p>
320
319
 
321
320
  </details>
322
321
  </div>
@@ -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", "未知"],
@@ -302,6 +305,7 @@
302
305
  "cap_field_parallel_tools": ["Parallel tool calls", "并行工具调用"],
303
306
  "cap_field_streaming": ["Streaming", "流式输出"],
304
307
  "cap_field_structured_output": ["Structured output", "结构化输出"],
308
+ "cap_field_mid_conversation_system": ["Native mid-conversation system messages", "原位中途系统消息"],
305
309
  "cap_field_web_search": ["Native search APIs (messages, responses, chat)", "原生搜索接口(messages、responses、chat)"],
306
310
 
307
311
  "api_add": ["Add API", "添加 API"],
@@ -565,7 +569,7 @@
565
569
  "bar_chart": ["Bar chart", "柱状图"],
566
570
  "line_chart": ["Line chart", "曲线图"],
567
571
  "approx_cache_hit_rate": ["Approx. cache hit rate", "粗略缓存命中率"],
568
- "runtime_cache_hit_basis": ["Reused input / input tokens. ~ Partial counts. — Unknown or invalid.", "复用输入 ÷ 输入 Token。\n~:数据不完整。—:未知或无效。"],
572
+ "runtime_cache_hit_basis": ["Reused / input tokens from records with valid counts for both. ~ Partial coverage. — No valid input basis.", "仅按输入和缓存读取均有效的记录计算。\n~:覆盖不完整。—:没有有效的输入依据。"],
569
573
  "provider_status_scope": ["Source and application status", "模型来源与应用状态"],
570
574
  "version_updates": ["VERSION & UPDATES", "版本与更新"],
571
575
  "copy_command": ["Copy command", "复制指令"],
@@ -892,11 +896,12 @@
892
896
  "aggregating_local_usage_metadata": ["Counting local usage…", "正在统计本机用量。"],
893
897
  "calls": ["REQUESTS", "请求次数"],
894
898
  "input": ["INPUT USAGE", "输入用量"],
899
+ "cache_write": ["CACHE WRITE", "缓存写入"],
895
900
  "cache_read": ["REUSED INPUT", "复用输入"],
896
901
  "output": ["OUTPUT USAGE", "输出用量"],
897
902
  "total": ["TOTAL", "总用量"],
898
903
  "cache_hit": ["REUSE RATE", "复用比例"],
899
- "cache_hit_recorded_cached_input_tokens_incomplete_history_unavai": ["Unit: Token. Reuse is included in input. ~ Partial; — Unknown.", "单位 Token;复用已计入输入。~ 为部分记录,— 为未知。"],
904
+ "cache_hit_recorded_cached_input_tokens_incomplete_history_unavai": ["Unit: Token. Reuse is included in input. Rate uses records with valid input and cache-read counts. ~ Partial coverage; — Unknown.", "单位 Token;复用已计入输入。比例仅按输入和缓存读取均有效的记录计算。~ 为覆盖不完整,— 为未知。"],
900
905
  "usage_analytics": ["USAGE TRENDS", "用量趋势"],
901
906
  "model_5e2c6": ["Model", "模型"],
902
907
  "all_models": ["All models", "全部模型"],
@@ -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", () => {
@@ -11,7 +11,7 @@
11
11
  function usageValues(row) {
12
12
  const rate = Number.isFinite(row.cache_hit_rate) && row.cache_hit_rate >= 0 && row.cache_hit_rate <= 1
13
13
  ? `${row.cache_hit_rate_partial ? "~" : ""}${(row.cache_hit_rate * 100).toFixed(1)}%` : "—";
14
- return [row.model, number(row.requests), number(row.input_tokens), number(row.cache_read_tokens), number(row.output_tokens), number(row.total_tokens), rate];
14
+ return [row.model, number(row.requests), number(row.input_tokens), number(row.cache_read_tokens), number(row.cache_write_input_tokens), number(row.output_tokens), number(row.total_tokens), rate];
15
15
  }
16
16
 
17
17
  let usageData = null;
@@ -112,7 +112,7 @@
112
112
  if (total.requests > 0) {
113
113
  body.append(tableRow(usageValues(total), { total: true }));
114
114
  for (const row of rows) body.append(tableRow(usageValues(row)));
115
- } else { emptyTable("usage-body", 7, "no_usage_records"); }
115
+ } else { emptyTable("usage-body", 8, "no_usage_records"); }
116
116
  element("clear-usage-day").hidden = !day;
117
117
  text("usage-state", day ? day.date : "local_log");
118
118
  text("usage-note", "records_records_shown_of_models_models_shown_day", {
@@ -95,7 +95,12 @@ function usageRow(model, values) {
95
95
  requests: finite(values.requests),
96
96
  input_tokens: finite(values.input_tokens),
97
97
  cache_read_tokens: cacheReadTokens(values) ?? null,
98
+ cache_write_input_tokens: values.cache_write_input_tokens ?? null,
98
99
  cache_hit_rate: usageCacheHitRate(values),
100
+ cache_hit_known_requests: values.cache_hit_known_requests ?? null,
101
+ cache_hit_unknown_requests: values.cache_hit_unknown_requests || 0,
102
+ cache_hit_input_tokens: values.cache_hit_input_tokens ?? null,
103
+ cache_hit_read_tokens: values.cache_hit_read_tokens ?? null,
99
104
  cache_hit_rate_partial: values.cache_hit_unknown_requests > 0,
100
105
  output_tokens: finite(values.output_tokens),
101
106
  total_tokens: finite(values.total_tokens),
@@ -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" }));