codex-copilot-dx 1.3.8 → 1.3.9

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
 
@@ -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
 
@@ -1079,3 +1079,17 @@ Claude passthrough now holds incomplete SSE frames and validates complete data b
1079
1079
  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
1080
 
1081
1081
  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.
1082
+
1083
+ ### Stable Messages prefixes and bounded privacy work
1084
+
1085
+ `messages-system-policy.mjs` selects transformation from the resolved endpoint capability, separately from client alias mapping. M365 declares native inline system support: only leading system messages join the top-level system field; later messages, cache-control blocks and signed history remain in order. Other Claude App API endpoints retain the prior legacy transformation unless their model explicitly declares `mid_conversation_system`; ordinary API passthrough is unchanged. History ownership validation accepts only text in inline system messages and fingerprints conversation turns independently of instruction placement, as it already does for top-level system text. Canonical and legacy journals therefore retain current signed tool continuations across this upgrade; tool and signature checks remain enforced. This is a protocol capability, with no App version or model-name pattern.
1086
+
1087
+ M365 count-token capability probes use the existing bounded API count coordinator before privacy detection. One source/model/header scope shares its initial probe; real 404 responses suppress further count probes for 60 seconds. Generation is independent and no estimate is fabricated. Long-text rule detection caches hashed keys and span metadata within 1 MiB/2048 entries. Neural detection still uses its existing separate bounded cache. Last-waiter cancellation stops unused shared detection, while a non-interruptible native job retains its physical admission slot until reply/deadline. Numeric neural secret predictions require an adjacent secret label; deterministic secret rules remain effective.
1088
+
1089
+ Native components stage under `components/<release>` without replacing a running executable. Current checksums are verified on load; a verified ABI-compatible 1.3.6 component remains usable while a background upgrade is staged. No model mapping or request text is persisted.
1090
+
1091
+ ### CI and release evidence
1092
+
1093
+ Unit suites are automatically discovered on macOS and Windows with Node 22.15 and 24. A temporary HOME and an OS-variable allowlist keep developer credentials and configuration out of unit fixtures. Installer/network replay jobs retain their explicitly configured proxy and certificate policy. Browser theme cases run in four parallel palette groups without reducing the language/theme/viewport matrix. Independent checks continue after another check fails, and any failed check keeps the result failed. Native client versions are pinned; compatibility baseline coverage remains separate.
1094
+
1095
+ Publication requires a successful full CI run on the exact tagged commit, downloads its four runtime and four privacy artifacts, and stages one checksummed GitHub release. The same source tarball goes to npm. Downloaded draft bytes, public npm bytes, a fresh native dependency installation and every public GitHub asset are verified. The release receipt is generated from these checks; it does not checksum itself. Failed publication can resume only when an existing npm version has identical integrity.
package/docs/REFERENCE.md CHANGED
@@ -106,7 +106,7 @@ Catalog diagnostics distinguish local cached data from an online response and ex
106
106
  - **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
107
  - **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
108
108
 
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.
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 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
110
 
111
111
  ## Settings and appearance
112
112
 
@@ -684,7 +684,13 @@ When upstream responses contain usage fields, CCDX records token counts, model n
684
684
  ccdx usage
685
685
  ```
686
686
 
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.
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, cache-write, output, and total token metadata.
688
+
689
+ 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.
690
+
691
+ 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.
692
+
693
+ 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
694
 
689
695
  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
696
 
@@ -769,7 +775,7 @@ Usage queries share a bounded aggregate checkpoint only when file identities, fi
769
775
 
770
776
  ## Local masking
771
777
 
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.
778
+ Settings → Advanced → Local masking is off by default. Enabling it downloads the optional local component and AstrLink Guard 0.1.3, verifies their checksums and loads the model before activating protection. The npm package and ordinary installation do not contain model weights or require Go, Python or CUDA. The model and tokenizer total 38,958,270 bytes; the executable and optional macOS acceleration cache require additional space. Component upgrades stage in a separate version directory. A verified compatible older component keeps serving during a failed download; the staged component takes over on the next engine load. Model weights with matching checksums are reused.
773
779
 
774
780
  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
781
 
@@ -781,8 +787,8 @@ Each request pins its masking choice, including compatibility retries. A check e
781
787
 
782
788
  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
789
 
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.
790
+ 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
791
 
786
792
  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
793
 
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.
794
+ The optional component targets the v1.3.9 Release; later code-only updates can reuse it. A verified ABI-compatible v1.3.6 installation can continue serving while the new component is staged. Its source and license notices are in `native/privacy-guard` and `src/privacy-notices.txt`. AstrLink Guard model files use their publisher's Apache-2.0 license.
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.9",
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",
@@ -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();
@@ -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>
@@ -302,6 +302,7 @@
302
302
  "cap_field_parallel_tools": ["Parallel tool calls", "并行工具调用"],
303
303
  "cap_field_streaming": ["Streaming", "流式输出"],
304
304
  "cap_field_structured_output": ["Structured output", "结构化输出"],
305
+ "cap_field_mid_conversation_system": ["Native mid-conversation system messages", "原位中途系统消息"],
305
306
  "cap_field_web_search": ["Native search APIs (messages, responses, chat)", "原生搜索接口(messages、responses、chat)"],
306
307
 
307
308
  "api_add": ["Add API", "添加 API"],
@@ -565,7 +566,7 @@
565
566
  "bar_chart": ["Bar chart", "柱状图"],
566
567
  "line_chart": ["Line chart", "曲线图"],
567
568
  "approx_cache_hit_rate": ["Approx. cache hit rate", "粗略缓存命中率"],
568
- "runtime_cache_hit_basis": ["Reused input / input tokens. ~ Partial counts. — Unknown or invalid.", "复用输入 ÷ 输入 Token。\n~:数据不完整。—:未知或无效。"],
569
+ "runtime_cache_hit_basis": ["Reused / input tokens from records with valid counts for both. ~ Partial coverage. — No valid input basis.", "仅按输入和缓存读取均有效的记录计算。\n~:覆盖不完整。—:没有有效的输入依据。"],
569
570
  "provider_status_scope": ["Source and application status", "模型来源与应用状态"],
570
571
  "version_updates": ["VERSION & UPDATES", "版本与更新"],
571
572
  "copy_command": ["Copy command", "复制指令"],
@@ -892,11 +893,12 @@
892
893
  "aggregating_local_usage_metadata": ["Counting local usage…", "正在统计本机用量。"],
893
894
  "calls": ["REQUESTS", "请求次数"],
894
895
  "input": ["INPUT USAGE", "输入用量"],
896
+ "cache_write": ["CACHE WRITE", "缓存写入"],
895
897
  "cache_read": ["REUSED INPUT", "复用输入"],
896
898
  "output": ["OUTPUT USAGE", "输出用量"],
897
899
  "total": ["TOTAL", "总用量"],
898
900
  "cache_hit": ["REUSE RATE", "复用比例"],
899
- "cache_hit_recorded_cached_input_tokens_incomplete_history_unavai": ["Unit: Token. Reuse is included in input. ~ Partial; — Unknown.", "单位 Token;复用已计入输入。~ 为部分记录,— 为未知。"],
901
+ "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
902
  "usage_analytics": ["USAGE TRENDS", "用量趋势"],
901
903
  "model_5e2c6": ["Model", "模型"],
902
904
  "all_models": ["All models", "全部模型"],
@@ -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),
@@ -6,12 +6,13 @@ 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 } from "./privacy-transform.mjs";
9
+ import { maskPrivacyRequest, protectPrivacyResponse, createPrivacyRuleCache } from "./privacy-transform.mjs";
10
10
  import { markRequestObservation } from "./stream-performance.mjs";
11
11
 
12
12
  export function createLocalPrivacy(options = {}) {
13
13
  const changes = createChangeSignal(), secret = randomBytes(32), cache = new Map(), flights = new Map(), responses = new WeakMap(), policies = new WeakMap();
14
14
  const model = options.model || createPrivacyModel({ ...options, changed: changes.changed });
15
+ const rules = createPrivacyRuleCache();
15
16
  let cacheBytes = 0, generation = 0, pending = null, disposed = false;
16
17
  let keyLoaded = false, actionError = null;
17
18
  const settings = () => {
@@ -19,7 +20,7 @@ export function createLocalPrivacy(options = {}) {
19
20
  return { enabled: saved.privacy_enabled === true, personal: saved.privacy_personal === true };
20
21
  };
21
22
  const revision = saved => createHash("sha256").update(JSON.stringify(saved)).digest("hex");
22
- const snapshot = () => { const saved = settings();return { ...model.snapshot(), ...saved, ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
23
+ const snapshot = () => { const saved = settings();return { ...model.snapshot(), ...saved, rule_cache: rules.stats(), ...(actionError ? { error: actionError } : {}), revision: revision(saved), action_pending: Boolean(pending), scope: "conversation_text" }; };
23
24
  function loadKey() {
24
25
  if (keyLoaded) return;
25
26
  const file = path.join(path.dirname(userSettingsPath(options)), "privacy-key");fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
@@ -37,18 +38,21 @@ export function createLocalPrivacy(options = {}) {
37
38
  });changes.changed();
38
39
  }
39
40
  async function find(texts, { signal } = {}) {
40
- const waiting = [], fresh = [], entries = [];
41
+ const waiting = [], fresh = [], entries = [], batches = new Set();
42
+ const batch = { controller: new AbortController(), waiters: 0, settled: false };
41
43
  for (const text of texts) {
42
44
  const key = createHash("sha256").update(text).digest("hex");
43
45
  if (cache.has(key)) {
44
46
  const saved = cache.get(key);cache.delete(key);cache.set(key, saved);waiting.push(Promise.resolve(saved.found));
45
- } else if (flights.has(key)) waiting.push(flights.get(key).promise);
47
+ } else if (flights.has(key) && !flights.get(key).batch.controller.signal.aborted) { const entry = flights.get(key);waiting.push(entry.promise);batches.add(entry.batch); }
46
48
  else {
47
- const entry = Promise.withResolvers();entry.key = key;flights.set(key, entry);
49
+ const entry = Promise.withResolvers();entry.key = key;entry.batch = batch;flights.set(key, entry);batches.add(batch);
48
50
  waiting.push(entry.promise);fresh.push(text);entries.push(entry);
49
51
  }
50
52
  }
51
- if (fresh.length) void model.find(fresh).then(found => {
53
+ for (const work of batches) work.waiters++;
54
+ if (fresh.length) void model.find(fresh, { signal: batch.controller.signal }).then(found => {
55
+ if (batch.controller.signal.aborted) throw privacyFailure("cancelled");
52
56
  if (!Array.isArray(found) || found.length !== fresh.length) throw privacyFailure("engine_invalid");
53
57
  for (let i = 0; i < found.length; i++) {
54
58
  const cost = Buffer.byteLength(JSON.stringify(found[i] || [])) + 128, entry = entries[i];
@@ -59,11 +63,11 @@ export function createLocalPrivacy(options = {}) {
59
63
  }
60
64
  entry.resolve(found[i] || []);
61
65
  }
62
- }).catch(error => entries.forEach(entry => entry.reject(error))).finally(() => entries.forEach(entry => { if (flights.get(entry.key) === entry) flights.delete(entry.key); }));
66
+ }).catch(error => entries.forEach(entry => entry.reject(error))).finally(() => { batch.settled = true;entries.forEach(entry => { if (flights.get(entry.key) === entry) flights.delete(entry.key); }); });
63
67
  let listener;
64
68
  const aborted = new Promise((_, reject) => { listener = () => reject(signal.reason);if (signal?.aborted) listener();else signal?.addEventListener("abort", listener, { once: true }); });
65
69
  try { return await (signal ? Promise.race([Promise.all(waiting), aborted]) : Promise.all(waiting)); }
66
- finally { signal?.removeEventListener("abort", listener); }
70
+ finally { signal?.removeEventListener("abort", listener);for (const work of batches) if (--work.waiters === 0 && !work.settled) work.controller.abort(privacyFailure("cancelled")); }
67
71
  }
68
72
  async function prepare(body, { protocol, client, signal, res, policy } = {}) {
69
73
  const saved = policy || settings();if (!saved.enabled) return body;
@@ -71,7 +75,7 @@ export function createLocalPrivacy(options = {}) {
71
75
  loadKey();
72
76
  const start = performance.now();
73
77
  const deadline = AbortSignal.timeout(15000);let session;
74
- try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
78
+ try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, rules: rules.find, signal: signal ? AbortSignal.any([signal, deadline]) : deadline }); }
75
79
  catch (error) { if (deadline.aborted && !signal?.aborted) throw privacyFailure("check_timeout");throw error; }
76
80
  if (signal?.aborted) { session.release();throw signal.reason; }
77
81
  markRequestObservation({ privacy_count: session.count, privacy_ms: Math.round(performance.now() - start), privacy_state: "checked" });
@@ -107,7 +111,7 @@ export function createLocalPrivacy(options = {}) {
107
111
  const current = ++generation;
108
112
  const work = (async () => {
109
113
  actionError = null;loadKey();
110
- if (!await model.installed()) await model.download();
114
+ if (!await model.installed({ current: true })) await model.download();
111
115
  if (current !== generation) return;
112
116
  await model.load();if (current !== generation) return;
113
117
  save({ privacy_enabled: true }, input.revision);
@@ -132,5 +136,5 @@ export function createLocalPrivacy(options = {}) {
132
136
  },
133
137
  restoreResponse: (res, value) => responses.get(res)?.restoreValue(value) || value,
134
138
  settingsChanged() { actionError = null;if (!settings().enabled) { generation++;model.stop(); }else warm();changes.changed(); },
135
- close() { disposed = true;generation++;model.close();cache.clear();cacheBytes = 0;secret.fill(0); } };
139
+ close() { disposed = true;generation++;model.close();cache.clear();rules.clear();cacheBytes = 0;secret.fill(0); } };
136
140
  }
@@ -11,6 +11,7 @@ const digest = value => createHash("sha256").update(JSON.stringify(value, (key,
11
11
  const semanticDigest = value => createHash("sha256").update(JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry)
12
12
  ? Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]])) : entry)).digest("hex");
13
13
  const parts = message => Array.isArray(message?.content) ? message.content : [];
14
+ const historyMessages = messages => messages.filter(message => message?.role !== "system");
14
15
  const thinking = part => ["thinking", "redacted_thinking", "reasoning"].includes(part?.type);
15
16
  const history = body => body.messages.some(message => message?.role === "assistant" || parts(message).some(part => part?.type === "tool_result"))
16
17
  || body.messages.filter(message => message?.role === "user").length > 1;
@@ -44,21 +45,29 @@ function canonicalBlock(block) {
44
45
  function canonicalItems(messages) {
45
46
  const out = [];
46
47
  for (const message of messages) {
47
- if (!message || typeof message !== "object" || !["user", "assistant"].includes(message.role)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
48
+ if (!message || typeof message !== "object" || !["user", "assistant", "system"].includes(message.role)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
48
49
  const { content, cache_control, ...fields } = message;
49
50
  const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
50
51
  if (!Array.isArray(blocks)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
52
+ // Instructions have the same ownership semantics as top-level system text.
53
+ // Keep them on the wire without shifting an existing signed tool prefix.
54
+ if (message.role === "system") {
55
+ if (!blocks.every(block => block?.type === "text" && typeof block.text === "string")) fail("ccdx_history_transfer_content_unsupported", "Inline system instructions must contain text.");
56
+ continue;
57
+ }
51
58
  for (const block of blocks.length ? blocks : [null]) out.push({ ...fields, block: canonicalBlock(block) });
52
59
  }
53
60
  return out;
54
61
  }
55
62
  function checkpoint(owner, messages) {
63
+ messages = historyMessages(messages);
56
64
  const items = canonicalItems(messages), raw = { owner, count: messages.length, prefix: digest(messages) };
57
65
  return { raw, canonical: { owner, count: items.length, prefix: semanticDigest(items), raw_count: raw.count, raw_prefix: raw.prefix } };
58
66
  }
59
67
  function knownPrefix(entry, messages, items) {
60
68
  if (entry.canonical) return items.length >= entry.canonical.count
61
69
  && semanticDigest(items.slice(0, entry.canonical.count)) === entry.canonical.prefix ? { count: entry.canonical.count } : null;
70
+ messages = historyMessages(messages);
62
71
  if (messages.length < entry.count) return null;
63
72
  const prefix = messages.slice(0, entry.count);
64
73
  const forms = [prefix,
@@ -93,7 +102,7 @@ function checkHistory(body, counting) {
93
102
  }
94
103
  const pending = new Set();
95
104
  for (const message of body.messages) {
96
- if (!message || !["user", "assistant"].includes(message.role) || !(typeof message.content === "string" || Array.isArray(message.content))) {
105
+ if (!message || !["user", "assistant", "system"].includes(message.role) || !(typeof message.content === "string" || Array.isArray(message.content))) {
97
106
  fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid. The original conversation was kept.");
98
107
  }
99
108
  if (message.role === "assistant" && pending.size) fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.", "tool_call_pending");
@@ -115,6 +124,7 @@ function checkHistory(body, counting) {
115
124
  function project(body, count) {
116
125
  let removed = 0, index = 0;
117
126
  body.messages = body.messages.map(message => {
127
+ if (message.role === "system") return message;
118
128
  const start = index;index += Array.isArray(message.content) ? Math.max(1, message.content.length) : 1;
119
129
  if (start >= count || message.role !== "assistant") return message;
120
130
  const out = { ...message };delete out.reasoning_content;
@@ -0,0 +1,20 @@
1
+ const invalid = () => Object.assign(new Error("System instructions must contain text"), { code: "ccdx_messages_system_invalid", statusCode: 400 });
2
+ const textBlocks = content => {
3
+ if (typeof content === "string") return [{ type: "text", text: content }];
4
+ if (Array.isArray(content) && content.every(block => block?.type === "text" && typeof block.text === "string")) return content;
5
+ throw invalid();
6
+ };
7
+
8
+ // Alias mapping never selects a content transformation. The resolved endpoint's
9
+ // protocol policy owns it; a model can explicitly override inline-role support.
10
+ export function applyMessagesSystemPolicy(body, mode = "passthrough") {
11
+ if (mode === "passthrough") return body;
12
+ if (!["native", "legacy"].includes(mode)) throw invalid();
13
+ const messages = [], instructions = [];
14
+ let leading = true;
15
+ for (const message of body.messages) {
16
+ if (message?.role === "system" && (mode === "legacy" || leading)) instructions.push(...textBlocks(message.content));
17
+ else { messages.push(message);leading = false; }
18
+ }
19
+ return instructions.length ? { ...body, system: [...(body.system === undefined ? [] : textBlocks(body.system)), ...instructions], messages } : body;
20
+ }
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
3
3
  export const MODEL_PROTOCOLS = Object.freeze(["messages", "responses", "chat"]);
4
4
  export const REASONING_EFFORTS = Object.freeze(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
5
5
  const limits = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max"];
6
- const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output"];
6
+ const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output", "mid_conversation_system"];
7
7
  export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "thinking_modes", "input_modalities", "web_search"]);
8
8
  const object = value => value && typeof value === "object" && !Array.isArray(value);
9
9
  export function validCapabilities(value) {
@@ -39,7 +39,7 @@ export function catalogCapabilities(model) {
39
39
  reasoning: first(typeof caps.reasoning === "boolean" ? caps.reasoning : undefined, supports.reasoning),
40
40
  reasoning_efforts: first(model.reasoning_efforts, supports.reasoning_effort),
41
41
  input_modalities: first(model.input_modalities, caps.input_modalities, supports.vision === true ? ["text", "image"] : undefined),
42
- tools: first(supports.tools, supports.tool_calls), parallel_tools: supports.parallel_tool_calls, streaming: supports.streaming,
42
+ tools: first(supports.tools, supports.tool_calls), parallel_tools: supports.parallel_tool_calls, streaming: supports.streaming, mid_conversation_system: supports.mid_conversation_system,
43
43
  structured_output: first(supports.structured_output, supports.structured_outputs), web_search: first(model.web_search, caps.web_search), thinking_modes: first(model.thinking_modes, caps.thinking_modes),
44
44
  ...Object.fromEntries(["reasoning_required", "reasoning_adaptive", "reasoning_budget_min", "reasoning_budget_max", "reasoning_format"].map(key => [key, first(model[key], caps[key])])),
45
45
  };
@@ -8,7 +8,7 @@ import { promisify } from "node:util";
8
8
  import { createNpmReleaseFetch, releaseBytes, releaseChecksum, RELEASE_BASE } from "./release-install.mjs";
9
9
 
10
10
  export const PRIVACY_MODEL_REVISION = "7216b6a3b897ef903d4b1ba367ae6fb95b0fa5e4";
11
- export const PRIVACY_COMPONENT_RELEASE = "1.3.6";
11
+ export const PRIVACY_COMPONENT_RELEASE = "1.3.9";
12
12
  export const PRIVACY_MODEL_FILES = Object.freeze([
13
13
  { name: "model_int8.onnx", bytes: 330781, sha256: "0a070d3113615e33ba3b84d6bd486f663a377c04c4b056e7381732179f51832a" },
14
14
  { name: "model_int8.onnx_data", bytes: 37124608, sha256: "0ba34216ceead01e0ae2dfd8e46d52b67e7aee80b04f722d9b758613a91c0067" },
@@ -25,7 +25,8 @@ const digest = bytes => createHash("sha256").update(bytes).digest("hex");
25
25
  export function privacyPaths({ home = os.homedir(), env = process.env, platform = process.platform, arch = process.arch } = {}) {
26
26
  const root = path.join(env.XDG_CACHE_HOME || (platform === "win32" ? env.LOCALAPPDATA || path.join(home, "AppData", "Local") : path.join(home, ".cache")), "codex-copilot-dx", "privacy");
27
27
  const name = `ccdx-privacy-guard-1-${platform}-${arch}${platform === "win32" ? ".exe" : ""}`;
28
- return { root, model: path.join(root, PRIVACY_MODEL_REVISION), name, runner: path.join(root, name), receipt: path.join(root, name + ".json") };
28
+ const component = path.join(root, "components", PRIVACY_COMPONENT_RELEASE);
29
+ return { root, model: path.join(root, PRIVACY_MODEL_REVISION), name, runner: path.join(component, name), receipt: path.join(component, name + ".json"), legacyRunner: path.join(root, name), legacyReceipt: path.join(root, name + ".json") };
29
30
  }
30
31
  async function downloader(env) {
31
32
  const names = [env.npm_execpath];
@@ -45,26 +46,36 @@ async function downloader(env) {
45
46
  }
46
47
  export function createPrivacyModel(options = {}) {
47
48
  const env = options.env || process.env, paths = privacyPaths(options), changed = options.changed || (() => {});
49
+ const modelFiles = options.modelFiles || PRIVACY_MODEL_FILES;
50
+ let activeRunner = paths.runner, componentRelease = null, upgradeAttempted = false;
48
51
  let child, serial = 0, ready = null, install = null, downloadAbort, line = "", stopped = false;
49
52
  let state = { state: "not_downloaded", downloaded_bytes: 0, download_bytes: PRIVACY_DOWNLOAD_BYTES, backend: null, device: null, error: null };
50
53
  const jobs = new Map();
51
54
  const set = next => { state = { ...state, ...next };changed(); };
52
- async function installed() {
55
+ async function installed({ current = false } = {}) {
53
56
  try {
54
- const receipt = JSON.parse(await fs.readFile(paths.receipt, "utf8"));
55
- if (!/^[a-f0-9]{64}$/.test(receipt.sha256) || receipt.release !== PRIVACY_COMPONENT_RELEASE) return false;
56
- if (digest(await fs.readFile(paths.runner)) !== receipt.sha256) return false;
57
- for (const file of PRIVACY_MODEL_FILES) if (digest(await fs.readFile(path.join(paths.model, file.name))) !== file.sha256) return false;
58
- return true;
57
+ for (const file of modelFiles) if (digest(await fs.readFile(path.join(paths.model, file.name))) !== file.sha256) return false;
58
+ const candidates = [[paths.runner, paths.receipt, PRIVACY_COMPONENT_RELEASE], ...(!current ? [[paths.legacyRunner, paths.legacyReceipt, "1.3.6"]] : [])];
59
+ for (const [runner, receiptFile, release] of candidates) {
60
+ try {
61
+ const receipt = JSON.parse(await fs.readFile(receiptFile, "utf8"));
62
+ if (!/^[a-f0-9]{64}$/.test(receipt.sha256) || receipt.release !== release || digest(await fs.readFile(runner)) !== receipt.sha256) continue;
63
+ if (!child) { activeRunner = runner;componentRelease = release; }
64
+ return true;
65
+ } catch { /* Missing targets never hide a verified ABI-compatible legacy component. */ }
66
+ }
67
+ return false;
59
68
  } catch { return false; }
60
69
  }
61
- async function download() {
70
+ async function download({ background = false } = {}) {
62
71
  if (install) return install;
63
72
  stopped = false;downloadAbort = new AbortController();const signal = downloadAbort.signal;
73
+ const report = next => background && child ? set({ component_update: next.state, component_update_error: next.error || null }) : set(next);
64
74
  install = (async () => {
65
- set({ state: "downloading", error: null, downloaded_bytes: 0 });
75
+ report({ state: "downloading", error: null, downloaded_bytes: 0 });
66
76
  const fetchImpl = options.fetchImpl || await downloader(env);
67
77
  await fs.mkdir(paths.model, { recursive: true, mode: 0o700 });
78
+ await fs.mkdir(path.dirname(paths.runner), { recursive: true, mode: 0o700 });
68
79
  const base = `${RELEASE_BASE}/v${PRIVACY_COMPONENT_RELEASE}`;
69
80
  const sums = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536, signal });
70
81
  const expected = releaseChecksum(sums, paths.name);
@@ -74,9 +85,9 @@ export function createPrivacyModel(options = {}) {
74
85
  try { await fs.writeFile(tempRunner, runner, { mode: 0o700, flag: "wx" });await fs.rename(tempRunner, paths.runner); }
75
86
  finally { await fs.rm(tempRunner, { force: true }); }
76
87
  await fs.writeFile(paths.receipt, JSON.stringify({ release: PRIVACY_COMPONENT_RELEASE, sha256: expected }) + "\n", { mode: 0o600 });
77
- for (const file of PRIVACY_MODEL_FILES) {
88
+ for (const file of modelFiles) {
78
89
  const target = path.join(paths.model, file.name);
79
- try { if (digest(await fs.readFile(target)) === file.sha256) { set({ downloaded_bytes: state.downloaded_bytes + file.bytes });continue; } } catch {}
90
+ try { if (digest(await fs.readFile(target)) === file.sha256) { report({ downloaded_bytes: state.downloaded_bytes + file.bytes });continue; } } catch {}
80
91
  const response = await fetchImpl(`https://huggingface.co/QuantumNous/astrlink-guard/resolve/${PRIVACY_MODEL_REVISION}/int8/${file.name}`, { signal: AbortSignal.any([signal, AbortSignal.timeout(180000)]), redirect: "follow" });
81
92
  const host = response.url && new URL(response.url);
82
93
  if (!response.ok || host && (host.protocol !== "https:" || !/^(?:huggingface\.co|[a-z0-9.-]+\.(?:huggingface\.co|hf\.co))$/.test(host.hostname))) { await response.body?.cancel();throw privacyFailure("download_unavailable"); }
@@ -85,15 +96,15 @@ export function createPrivacyModel(options = {}) {
85
96
  for await (const bytes of response.body || []) {
86
97
  if (signal.aborted) throw signal.reason;
87
98
  total += bytes.length;if (total > file.bytes) throw privacyFailure("download_invalid");
88
- hash.update(bytes);await output.write(bytes);set({ downloaded_bytes: state.downloaded_bytes + bytes.length });
99
+ hash.update(bytes);await output.write(bytes);report({ downloaded_bytes: state.downloaded_bytes + bytes.length });
89
100
  }
90
101
  if (total !== file.bytes || hash.digest("hex") !== file.sha256) throw privacyFailure("download_invalid");
91
102
  await output.sync();await output.close();await fs.rename(temp, target);
92
103
  } finally { await output.close().catch(() => {});await fs.rm(temp, { force: true }); }
93
104
  }
94
105
  if (signal.aborted || stopped) throw privacyFailure("cancelled");
95
- set({ state: "installed" });
96
- })().catch(error => { if (signal.aborted || stopped) { set({ state: "not_downloaded", error: null });throw privacyFailure("cancelled"); }set({ state: "error", error: error.code?.startsWith("ccdx_privacy_") ? error.code : "ccdx_privacy_download_unavailable" });throw privacyFailure("download_unavailable"); })
106
+ report({ state: background ? "staged" : "installed", error: null });
107
+ })().catch(error => { if (signal.aborted || stopped) { report({ state: "not_downloaded", error: null });throw privacyFailure("cancelled"); }report({ state: "error", error: error.code?.startsWith("ccdx_privacy_") ? error.code : "ccdx_privacy_download_unavailable" });throw privacyFailure("download_unavailable"); })
97
108
  .finally(() => { install = null;downloadAbort = null; });
98
109
  return install;
99
110
  }
@@ -112,7 +123,7 @@ export function createPrivacyModel(options = {}) {
112
123
  return new Promise((resolve, reject) => {
113
124
  const timer = setTimeout(() => { reject(privacyFailure("load_timeout"));fail(); }, 60000);
114
125
  const workerEnv = Object.fromEntries(["PATH", "SystemRoot", "WINDIR", "TMP", "TEMP", "TMPDIR", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "GOMAXPROCS"].filter(key => typeof env[key] === "string").map(key => [key, env[key]]));
115
- const current = child = (options.spawnImpl || spawn)(paths.runner, [paths.model], { env: workerEnv, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
126
+ const current = child = (options.spawnImpl || spawn)(activeRunner, [paths.model], { env: workerEnv, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
116
127
  current.stdout.on("data", bytes => {
117
128
  if (current !== child) return;
118
129
  line += bytes.toString("utf8");if (Buffer.byteLength(line) > 8 * 1024 * 1024) { fail();return; }
@@ -121,7 +132,7 @@ export function createPrivacyModel(options = {}) {
121
132
  const part = line.slice(0, end);line = line.slice(end + 1);
122
133
  try {
123
134
  const value = JSON.parse(part);
124
- if (value.ready === true) { clearTimeout(timer);set({ state: "ready", backend: value.backend === "CoreML" ? "CoreML" : "CPU", device: ["CPU", "GPU", "Neural Engine"].includes(value.device) ? value.device : null });resolve(); }
135
+ if (value.ready === true) { clearTimeout(timer);set({ state: "ready", backend: value.backend === "CoreML" ? "CoreML" : "CPU", device: ["CPU", "GPU", "Neural Engine"].includes(value.device) ? value.device : null });resolve();if (componentRelease !== PRIVACY_COMPONENT_RELEASE && !upgradeAttempted) { upgradeAttempted = true;void download({ background: true }).catch(() => {}); } }
125
136
  else if (jobs.has(value.id)) { const job = jobs.get(value.id);jobs.delete(value.id);clearTimeout(job.timer);job.resolve(value.found);changed();if (stopped && !jobs.size) stop(); }
126
137
  } catch { fail(); }
127
138
  }
@@ -139,7 +150,10 @@ export function createPrivacyModel(options = {}) {
139
150
  if (Buffer.byteLength(input) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
140
151
  if ([...jobs.values()].reduce((n, job) => n + job.bytes, Buffer.byteLength(input)) > 16 * 1024 * 1024) throw privacyFailure("busy");
141
152
  return new Promise((resolve, reject) => {
142
- const cancelled = () => { if (jobs.has(id)) { jobs.delete(id);clearTimeout(timer);reject(signal?.reason || privacyFailure("cancelled")); } };
153
+ // The helper may still be executing after a waiter leaves. Keep its slot
154
+ // and byte budget until its actual reply or deadline, never admit an
155
+ // unbounded queue by reporting cancelled native work as already idle.
156
+ const cancelled = () => { if (jobs.has(id)) { jobs.get(id).cancelled = true;signal?.removeEventListener("abort", cancelled);reject(signal?.reason || privacyFailure("cancelled"));changed(); } };
143
157
  const finish = fn => value => { signal?.removeEventListener("abort", cancelled);fn(value); };
144
158
  const timer = setTimeout(() => { reject(privacyFailure("check_timeout"));fail(); }, 300000);
145
159
  jobs.set(id, { resolve: finish(resolve), reject: finish(reject), timer, bytes: Buffer.byteLength(input) });signal?.addEventListener("abort", cancelled, { once: true });changed();
@@ -150,12 +164,12 @@ export function createPrivacyModel(options = {}) {
150
164
  function snapshot() {
151
165
  if (!child && !install && ["installed", "not_downloaded"].includes(state.state)) {
152
166
  try {
153
- const stat = fsSync.lstatSync(paths.runner);
154
- const cached = stat.isFile() && stat.size > 0 && stat.size <= 16 * 1024 * 1024 && PRIVACY_MODEL_FILES.every(file => fsSync.lstatSync(path.join(paths.model, file.name)).size === file.bytes);
167
+ const stat = fsSync.lstatSync(fsSync.existsSync(paths.runner) ? paths.runner : paths.legacyRunner);
168
+ const cached = stat.isFile() && stat.size > 0 && stat.size <= 16 * 1024 * 1024 && modelFiles.every(file => fsSync.lstatSync(path.join(paths.model, file.name)).size === file.bytes);
155
169
  state = { ...state, state: cached ? "installed" : "not_downloaded" };
156
170
  } catch { state = { ...state, state: "not_downloaded" }; }
157
171
  }
158
- return { ...state, pending_checks: jobs.size };
172
+ return { ...state, component_release: componentRelease, target_component_release: PRIVACY_COMPONENT_RELEASE, pending_checks: jobs.size, cancelled_checks: [...jobs.values()].filter(job => job.cancelled).length };
159
173
  }
160
174
  return { paths, snapshot, installed, download, load, find, stop,
161
175
  async remove() { stop();await install?.catch(() => {});if (jobs.size) throw privacyFailure("busy");await fs.rm(paths.root, { recursive: true, force: true });set({ state: "not_downloaded", downloaded_bytes: 0 }); },
@@ -1,4 +1,4 @@
1
- import { createHmac } from "node:crypto";
1
+ import { createHash, createHmac } from "node:crypto";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { privacyFailure } from "./privacy-model.mjs";
4
4
 
@@ -23,7 +23,7 @@ function leaves(value, add, inArguments = false) {
23
23
  }
24
24
  function requestTexts(body, protocol) {
25
25
  const items = [], nested = [];
26
- const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|token)$/i.test(String(key)) }); };
26
+ const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|secret|token)$/i.test(String(key)) }); };
27
27
  const text = (parent, key) => { if (typeof parent?.[key] === "string") add(parent, key, parent[key]);else if (Array.isArray(parent?.[key])) for (const block of parent[key]) if (["text", "input_text", "output_text"].includes(block?.type)) add(block, "text", block.text); };
28
28
  const args = (parent, key) => {
29
29
  if (typeof parent[key] === "string") {
@@ -69,18 +69,49 @@ function ruleSpans(text, personal) {
69
69
  }
70
70
  return spans;
71
71
  }
72
- export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal }) {
72
+ export function createPrivacyRuleCache({ maxBytes = 1024 * 1024, maxEntries = 2048 } = {}) {
73
+ const entries = new Map();let bytes = 0, hits = 0, scans = 0;
74
+ return {
75
+ find(text, personal) {
76
+ if (text.length < 256) { scans++;return ruleSpans(text, personal); }
77
+ const key = `${personal ? 1 : 0}:` + createHash("sha256").update(text).digest("hex");
78
+ if (entries.has(key)) {
79
+ const entry = entries.get(key);entries.delete(key);entries.set(key, entry);hits++;
80
+ return entry.spans.map(span => ({ ...span }));
81
+ }
82
+ scans++;const spans = ruleSpans(text, personal), cost = Buffer.byteLength(JSON.stringify(spans)) + 128;
83
+ if (cost <= maxBytes) {
84
+ entries.set(key, { spans: spans.map(span => ({ ...span })), cost });bytes += cost;
85
+ while (entries.size > maxEntries || bytes > maxBytes) { const oldest = entries.keys().next().value;bytes -= entries.get(oldest).cost;entries.delete(oldest); }
86
+ }
87
+ return spans;
88
+ },
89
+ clear() { entries.clear();bytes = 0; },
90
+ stats: () => ({ entries: entries.size, bytes, hits, scans, max_bytes: maxBytes }),
91
+ };
92
+ }
93
+ function modelSpanFits(text, start, end, label) {
94
+ const value = text.slice(start, end);
95
+ if (label === "common_secret" && /^\d+$/.test(value)) {
96
+ return /(?:\b(?:api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|password|passwd|passcode|secret|token|pin)|密钥|密码|令牌|口令)["'`]?[\s:=:]*(?:(?:is|was|是|为|為)\s*)?["'`]?$/i.test(text.slice(Math.max(0, start - 96), start));
97
+ }
98
+ if (label === "private_person" && /^[A-Za-z_$][\w$]*$/.test(value)
99
+ && /\b(?:function|class|const|let|var)\s+$/.test(text.slice(Math.max(0, start - 32), start))) return false;
100
+ return true;
101
+ }
102
+ export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, rules = ruleSpans }) {
73
103
  const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
74
104
  if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
75
105
  const found = texts.length ? await find(texts, { signal }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
76
106
  if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
77
107
  for (let i = 0; i < items.length; i++) {
78
- const item = items[i], bytes = Buffer.from(item.text), spans = ruleSpans(item.text, personal);
108
+ const item = items[i], bytes = Buffer.from(item.text), spans = rules(item.text, personal);
79
109
  if (item.secret) spans.push({ start: 0, end: item.text.length, kind: "secret" });
80
110
  for (const span of found[i] || []) {
81
111
  if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start || span.end > bytes.length || !Number.isFinite(span.score)) throw privacyFailure("engine_invalid");
82
112
  if (span.score < 0.8 || span.label !== "common_secret" && !(personal && personalKinds.has(span.label))) continue;
83
113
  const start = bytes.subarray(0, span.start).toString("utf8").length, end = bytes.subarray(0, span.end).toString("utf8").length;
114
+ if (!modelSpanFits(item.text, start, end, span.label)) continue;
84
115
  spans.push({ start, end, kind: span.label === "common_secret" ? "secret" : span.label });
85
116
  }
86
117
  spans.sort((a, b) => a.start - b.start || b.end - a.end);
@@ -126,7 +126,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
126
126
  const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
127
127
  if (serialized !== undefined) requestHeaders["Content-Length"] = String(Buffer.byteLength(serialized));
128
128
  options.onUpstreamStart?.();
129
- if (body) { markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
129
+ if (body) { if (options.observeUpstream !== false) markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
130
130
  try {
131
131
  const send = fetchImpl || await transport(options.signal);
132
132
  const response = await send(`${M365_API_BASE}${endpoint}`, { method: body ? "POST" : "GET", headers: requestHeaders,
@@ -233,12 +233,15 @@ export function createM365Provider({ home, env = process.env, account: accountOv
233
233
  const adjusted = limitM365CacheTtl(body);
234
234
  if (adjusted.changed && !cacheTtlAdjustments) log("info", "Microsoft 365 supports 5m prompt caching; 1h cache retention is capped to 5m. Content and breakpoints are unchanged.");
235
235
  cacheTtlAdjustments += adjusted.changed;
236
- return request(options.countTokens ? "/v1/messages/count_tokens" : "/v1/messages", model.id === adjusted.body.model ? adjusted.body : { ...adjusted.body, model: model.id }, options);
236
+ const requestBody = model.id === adjusted.body.model ? adjusted.body : { ...adjusted.body, model: model.id };
237
+ return request(options.countTokens ? "/v1/messages/count_tokens" : "/v1/messages", requestBody, requestBody === body ? options : { ...options, bodyText: undefined });
237
238
  },
238
239
  runtimeStatus: () => ({ ...auth.snapshot(), account_bound: Boolean(account), upstream_host: new URL(M365_API_BASE).hostname,
239
240
  model_endpoint_cache_entries: catalog?.data.length || 0, model_list_flights: flight ? 1 : 0 }),
240
241
  };
241
242
  return {
243
+ messagesSystemMode: "native",
244
+ coordinateMessagesCounts: true,
242
245
  id: "m365", client, registry, auth, refresh, profileId: profile,
243
246
  models: family => m365Models(catalog, family),
244
247
  catalog: () => catalog?.data || [],
@@ -55,13 +55,13 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
55
55
  const rate = usage.cache_hit_rate;
56
56
  const cacheHit = Number.isFinite(rate) && rate >= 0 && rate <= 1 ? `${usage.cache_hit_rate_partial ? "~" : ""}${(rate * 100).toFixed(1)}%` : "—";
57
57
  const usageRows = [[left < 23 ? "Records" : "Usage records", usage.records ?? null], ["Input", usage.input_tokens ?? null], [left < 23 ? "Reused" : "Reused input", usage.cached_input_tokens ?? null],
58
- ["Output", usage.output_tokens ?? null], [left < 23 ? "Partial" : "Partial records", usage.partial_records ?? null], ["Cache hit", cacheHit]];
58
+ [left < 23 ? "Written" : "Cache write", usage.cache_write_input_tokens ?? null], ["Output", usage.output_tokens ?? null], [left < 23 ? "Partial" : "Partial records", usage.partial_records ?? null], ["Cache hit", cacheHit]];
59
59
  const requestRows = [["Total", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
60
60
  if (sum("unknown")) { usageRows.push(["", ""]);requestRows.push(["Unknown", sum("unknown")]); }
61
61
  const title = compactTitle ? [`┌─ Usage ${"─".repeat(left - 8)}┬─ Requests ${"─".repeat(right - 11)}┐`]
62
62
  : [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell(right < 23 ? "Requests" : "Model requests", undefined, right)), rule("├", "┼", "┤")];
63
63
  return [...title,
64
- ...usageRows.map(([label, value], index) => row(cell(label, value === undefined ? (label ? null : undefined) : value, left), cell(...requestRows[index], right))), rule("└", "┴", "┘")];
64
+ ...usageRows.map(([label, value], index) => row(cell(label, value === undefined ? (label ? null : undefined) : value, left), cell(...(requestRows[index] || ["", undefined]), right))), rule("└", "┴", "┘")];
65
65
  }
66
66
  function render() {
67
67
  if (!running || !supported() || verbose) { frameDelay = 1000;return; }
@@ -3,7 +3,7 @@ import { cacheReadTokens, usageCacheHitRate, usageProvider } from "./usage-store
3
3
  const DAY_MS = 86400000;
4
4
  const DAYS = 365;
5
5
  const MAX_MODELS = 100;
6
- const TOKEN_FIELDS = ["input_tokens", "output_tokens", "total_tokens", "cached_input_tokens", "cache_read_input_tokens", "cache_hit_unknown_requests", "cache_hit_invalid_requests"];
6
+ const TOKEN_FIELDS = ["input_tokens", "output_tokens", "total_tokens", "cached_input_tokens", "cache_read_input_tokens", "cache_write_input_tokens", "cache_hit_unknown_requests", "cache_hit_invalid_requests", "cache_hit_known_requests", "cache_hit_input_tokens", "cache_hit_read_tokens"];
7
7
 
8
8
  export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), qualifyProviders = false } = {}) {
9
9
  const formatter = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
@@ -33,7 +33,12 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
33
33
  output_tokens: values.output_tokens || 0,
34
34
  total_tokens: values.total_tokens ?? (values.input_tokens || 0) + (values.output_tokens || 0),
35
35
  cache_read_tokens: cacheReadTokens(values) ?? null,
36
+ cache_write_input_tokens: values.cache_write_input_tokens ?? null,
36
37
  cache_hit_rate: usageCacheHitRate(values),
38
+ cache_hit_known_requests: values.cache_hit_known_requests || 0,
39
+ cache_hit_unknown_requests: values.cache_hit_unknown_requests || 0,
40
+ cache_hit_input_tokens: values.cache_hit_input_tokens ?? null,
41
+ cache_hit_read_tokens: values.cache_hit_read_tokens ?? null,
37
42
  cache_hit_rate_partial: values.cache_hit_unknown_requests > 0,
38
43
  tokens_partial: values.tokens_partial === true || values.cache_hit_invalid_requests > 0,
39
44
  };
@@ -203,17 +203,16 @@ function scheduleUsageWriteDrain() {
203
203
  export function recordUsage(record) {
204
204
  if (!record) return Promise.resolve();
205
205
  const usage = record.usage || {};
206
- const { cached, unknown, invalid } = usageCacheEvidence(usage);
206
+ const { cached } = usageCacheEvidence(usage);
207
207
  const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 18 ? provider : "other";
208
208
  if (!runtimeUsageByProvider.has(label)) runtimeUsageByProvider.set(label, { records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 });
209
209
  for (const totals of [runtimeUsage, runtimeUsageByProvider.get(label)]) {
210
210
  totals.records++;
211
- for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cached], ["output_tokens", usage.output_tokens]]) {
212
- if (Number.isFinite(value) && value >= 0) totals[target] += value;
211
+ for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cached], ["cache_write_input_tokens", usage.cache_write_input_tokens], ["output_tokens", usage.output_tokens]]) {
212
+ if (Number.isFinite(value) && value >= 0) totals[target] = (totals[target] || 0) + value;
213
213
  }
214
214
  if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cached === undefined) totals.partial_records++;
215
- if (unknown) totals.cache_hit_unknown_requests = (totals.cache_hit_unknown_requests || 0) + 1;
216
- if (invalid) totals.cache_hit_invalid_requests = (totals.cache_hit_invalid_requests || 0) + 1;
215
+ addCacheEvidence(totals, usage);
217
216
  }
218
217
  if (process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
219
218
  const filePath = usageLogPath();
@@ -341,15 +340,13 @@ export function summarizeUsage(records, { provider = "" } = {}) {
341
340
  const modelTotals = summary.byModel[model];
342
341
  modelTotals.requests += 1;
343
342
  addUsageTotals(modelTotals, record.usage);
344
- const { unknown, invalid } = usageCacheEvidence(record.usage || {});
345
343
  const qualified = `${source} / ${model}`;
346
344
  if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
347
345
  const sourceTotals = summary.bySourceModel[qualified];
348
346
  sourceTotals.requests++;
349
347
  addUsageTotals(sourceTotals, record.usage);
350
348
  for (const target of [summary.totals, modelTotals, sourceTotals]) {
351
- if (unknown) target.cache_hit_unknown_requests = (target.cache_hit_unknown_requests || 0) + 1;
352
- if (invalid) target.cache_hit_invalid_requests = (target.cache_hit_invalid_requests || 0) + 1;
349
+ addCacheEvidence(target, record.usage || {});
353
350
  }
354
351
  }
355
352
  return summary;
@@ -436,6 +433,11 @@ export function cacheReadTokens(usage = {}) {
436
433
  }
437
434
 
438
435
  export function usageCacheHitRate(usage = {}) {
436
+ if (usage.cache_hit_known_requests !== undefined || usage.cache_hit_unknown_requests !== undefined) {
437
+ const input = usage.cache_hit_input_tokens, cached = usage.cache_hit_read_tokens;
438
+ return usage.cache_hit_known_requests > 0 && Number.isFinite(input) && input > 0
439
+ && Number.isFinite(cached) && cached >= 0 && cached <= input ? cached / input : null;
440
+ }
439
441
  const input = usage.input_tokens;
440
442
  const cached = cacheReadTokens(usage);
441
443
  if (usage.cache_hit_invalid_requests > 0 || !Number.isFinite(input) || input <= 0
@@ -443,6 +445,17 @@ export function usageCacheHitRate(usage = {}) {
443
445
  return cached / input;
444
446
  }
445
447
 
448
+ function addCacheEvidence(target, usage) {
449
+ const { cached, unknown, invalid } = usageCacheEvidence(usage);
450
+ if (unknown) target.cache_hit_unknown_requests = (target.cache_hit_unknown_requests || 0) + 1;
451
+ else {
452
+ target.cache_hit_known_requests = (target.cache_hit_known_requests || 0) + 1;
453
+ target.cache_hit_input_tokens = (target.cache_hit_input_tokens || 0) + usage.input_tokens;
454
+ target.cache_hit_read_tokens = (target.cache_hit_read_tokens || 0) + cached;
455
+ }
456
+ if (invalid) target.cache_hit_invalid_requests = (target.cache_hit_invalid_requests || 0) + 1;
457
+ }
458
+
446
459
  function usageCacheEvidence(usage) {
447
460
  const input = usage.input_tokens, cached = cacheReadTokens(usage);
448
461
  const unknown = !Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input;
package/src/usage.mjs CHANGED
@@ -28,6 +28,8 @@ function fmt(n) {
28
28
  return Number.isFinite(n) ? n.toLocaleString("en-US") : "0";
29
29
  }
30
30
 
31
+ const writeTokens = n => Number.isFinite(n) ? fmt(n) : "—";
32
+
31
33
  function tableNumber(n) {
32
34
  return Number.isFinite(n) ? n.toLocaleString("en-US") : undefined;
33
35
  }
@@ -53,13 +55,13 @@ function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {
53
55
  }
54
56
  lines.push(
55
57
  `Records: ${fmt(summary.requests)}`,
56
- `Tokens: input=${fmt(summary.totals.input_tokens)} cache_read=${fmt(cacheReadTokens(summary.totals))} output=${fmt(summary.totals.output_tokens)} total=${fmt(summary.totals.total_tokens)}`,
57
- `Cache hit: ${cacheHitPercent(summary.totals)} (cached/input tokens)`,
58
+ `Tokens: input=${fmt(summary.totals.input_tokens)} cache_read=${fmt(cacheReadTokens(summary.totals))} cache_write=${writeTokens(summary.totals.cache_write_input_tokens)} output=${fmt(summary.totals.output_tokens)} total=${fmt(summary.totals.total_tokens)}`,
59
+ `Cache hit: ${cacheHitPercent(summary.totals)} (cached/input tokens; valid paired records only)`,
58
60
  "",
59
61
  "By model:",
60
62
  );
61
63
  for (const [model, row] of Object.entries(usageModelGroups(summary))) {
62
- lines.push(` ${terminalCell(model)}: records=${fmt(row.requests)} input=${fmt(row.input_tokens)} cache_read=${fmt(cacheReadTokens(row))} output=${fmt(row.output_tokens)} total=${fmt(row.total_tokens)} cache_hit=${cacheHitPercent(row)}`);
64
+ lines.push(` ${terminalCell(model)}: records=${fmt(row.requests)} input=${fmt(row.input_tokens)} cache_read=${fmt(cacheReadTokens(row))} cache_write=${writeTokens(row.cache_write_input_tokens)} output=${fmt(row.output_tokens)} total=${fmt(row.total_tokens)} cache_hit=${cacheHitPercent(row)}`);
63
65
  }
64
66
  return (sanitize ? lines.map((line) => terminalCell(line, { fallback: "" })) : lines).join("\n");
65
67
  }
@@ -77,6 +79,7 @@ function usageTableRow(model, usage) {
77
79
  records: tableNumber(usage.requests),
78
80
  input: tableNumber(usage.input_tokens),
79
81
  cacheRead: tableNumber(cacheReadTokens(usage)),
82
+ cacheWrite: tableNumber(usage.cache_write_input_tokens),
80
83
  output: tableNumber(usage.output_tokens),
81
84
  total: tableNumber(usage.total_tokens),
82
85
  cacheHit: cacheHitPercent(usage),
@@ -84,7 +87,7 @@ function usageTableRow(model, usage) {
84
87
  }
85
88
 
86
89
  function usageDetailLine(model, usage) {
87
- return `${terminalCell(model)}: input=${fmt(usage.input_tokens)} cache_read=${fmt(cacheReadTokens(usage))} output=${fmt(usage.output_tokens)} cache_hit=${cacheHitPercent(usage)}`;
90
+ return `${terminalCell(model)}: input=${fmt(usage.input_tokens)} cache_read=${fmt(cacheReadTokens(usage))} cache_write=${writeTokens(usage.cache_write_input_tokens)} output=${fmt(usage.output_tokens)} cache_hit=${cacheHitPercent(usage)}`;
88
91
  }
89
92
 
90
93
  function formatTableUsageSummary(summary, filePath, output) {
@@ -95,10 +98,11 @@ function formatTableUsageSummary(summary, filePath, output) {
95
98
  { key: "records", label: "RECORDS", align: "right" },
96
99
  { key: "input", label: "INPUT", align: "right" },
97
100
  { key: "cacheRead", label: "CACHE READ", align: "right" },
101
+ { key: "cacheWrite", label: "CACHE WRITE", align: "right" },
98
102
  { key: "output", label: "OUTPUT", align: "right" },
99
103
  { key: "total", label: "TOTAL", align: "right" },
100
104
  ];
101
- const compactColumns = [columns[0], columns[1], columns[5]];
105
+ const compactColumns = [columns[0], columns[1], columns[6]];
102
106
  const modelUsage = Object.entries(usageModelGroups(summary))
103
107
  .map(([model, row]) => ({ model, row }))
104
108
  .sort(compareModelUsage);
@@ -111,6 +115,11 @@ function formatTableUsageSummary(summary, filePath, output) {
111
115
  width: cliOutputWidth(output),
112
116
  gap: 1,
113
117
  });
118
+ const writeOmitted = table.compact || table.overflow;
119
+ if (writeOmitted) {
120
+ columns.splice(columns.findIndex(column => column.key === "cacheWrite"), 1);
121
+ table = formatResponsiveCliTable({ columns: [...columns, { key: "cacheHit", label: "HIT %", align: "right" }], compactColumns: columns, rows, width: cliOutputWidth(output), gap: 1 });
122
+ }
114
123
  const rateFits = !table.compact;
115
124
  if (table.overflow) {
116
125
  table = formatResponsiveCliTable({ columns, compactColumns, rows, width: cliOutputWidth(output), gap: 1 });
@@ -118,6 +127,10 @@ function formatTableUsageSummary(summary, filePath, output) {
118
127
  table.compact = false;
119
128
  }
120
129
  const lines = [`Usage log: ${safePath}`, ...providerSummaryLines(summary), "", table.output];
130
+ if (writeOmitted && !table.compact && Number.isFinite(totalUsage.cache_write_input_tokens)) {
131
+ lines.push("", "Cache writes:", `TOTAL: ${writeTokens(totalUsage.cache_write_input_tokens)}`,
132
+ ...modelUsage.filter(({ row }) => Number.isFinite(row.cache_write_input_tokens)).map(({ model, row }) => `${terminalCell(model)}: ${writeTokens(row.cache_write_input_tokens)}`));
133
+ }
121
134
  if (table.compact) {
122
135
  lines.push(
123
136
  "",