codex-copilot-dx 1.3.5 → 1.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,6 +4,8 @@ Use your model services in **Codex App, Claude App and Claude Code** through one
4
4
 
5
5
  Connect GitHub Copilot, Microsoft 365 or your own API. Choose which apps can use each source, then select their models. CCDX supports **macOS and Windows**, on Apple Silicon/ARM64 and x64.
6
6
 
7
+ Optional local masking is off by default. Enable it in Settings → Advanced to download the model and component. Checks run locally and may add delay or mistake ordinary text; an unfinished check holds the request back. See [local masking](docs/REFERENCE.md#local-masking).
8
+
7
9
  ## Install and start
8
10
 
9
11
  With Node.js **22.15+** and npm:
@@ -15,8 +17,8 @@ ccdx
15
17
 
16
18
  Without Node.js, download and run the installer for your system:
17
19
 
18
- - macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.5/install.sh), then `sh install.sh`.
19
- - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.5/install.ps1), then `./install.ps1` under your current shell policy.
20
+ - macOS: [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.6/install.sh), then `sh install.sh`.
21
+ - Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.6/install.ps1), then `./install.ps1` under your current shell policy.
20
22
 
21
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.
22
24
 
@@ -1054,3 +1054,16 @@ non-rotating appends queue delta lines (at most 256 KiB per checkpoint). Queries
1054
1054
  apply those records without rescanning history. Other-process writes, unknown
1055
1055
  changes, rotation, incomplete tails, warnings and oversized results rebuild through
1056
1056
  the original full scan. No persistent index, polling or per-token work is added.
1057
+ ### Local masking boundary
1058
+
1059
+ `local-privacy.mjs` owns explicit consent, per-request policy snapshots, a private placeholder seed and bounded shared detection metadata. It wraps provider calls after authorization/model resolution without changing the prepared request used by local history. Completed history records restore client-visible values while signed and encrypted state stays opaque. `privacy-transform.mjs` projects only supported text fields and restores complete reply events, including JSON-escaped tool arguments. It does not take ownership of credentials or select providers.
1060
+
1061
+ `privacy-model.mjs` owns verified, optional downloads and a stdio-only child process. The 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
+
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.
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.
1066
+
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
+
1069
+ 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.
package/docs/README.md CHANGED
@@ -4,6 +4,7 @@
4
4
  - [Reference](REFERENCE.md): commands, settings, diagnostics, images and native suggestions.
5
5
  - [Architecture](ARCHITECTURE.md): module ownership and runtime boundaries.
6
6
  - [State orchestration](STATE_REFACTOR_PLAN.md): implemented boundaries, preservation checks and deferred work.
7
+ - [1.3.6](RELEASE_1.3.6.md): optional local masking, complete stream frames and atomic capability updates.
7
8
  - [1.3.5](RELEASE_1.3.5.md): protocol-first App checks, bounded prediction transport and incremental usage analytics.
8
9
  - [1.3.4](RELEASE_1.3.4.md): centered Auto refresh labels at compact control heights.
9
10
  - [1.3.3](RELEASE_1.3.3.md): live activity updates and compact WebUI spacing.
package/docs/REFERENCE.md CHANGED
@@ -736,4 +736,20 @@ Internal supervisor and installer environment fields are not user settings.
736
736
 
737
737
  Diagnostic presentation omits input longer than 16,384 UTF-16 code units before normalization or credential scanning. Ordinary identifiers/messages retain budgets of 200/500 UTF-16 code units (400 for operation details), clipped only at complete surrogate boundaries. Oversized diagnostics retain structured status, error and request identifiers; original HTTP/SSE payloads are not changed. The general-purpose credential recognizer keeps its original semantics.
738
738
 
739
- Usage queries for recently written logs may share an in-flight aggregate only when observed device/inode/size/mtime/ctime identities and query filters match. Those results are not kept after the scan. The existing two-second settled-file rule and bounded caches remain. Appends, rewrites, replacement, rotation, provider filters, time zone and calendar date retain independent identities. Custom warning callbacks bypass sharing. Cancelling one waiter does not stop other waiters; a bounded scan already started may complete without retaining its result.
739
+ Usage queries share a bounded aggregate checkpoint only when file identities, filters, time zone and calendar date match. Only appends witnessed inside CCDX's writer lock can advance it incrementally. Other-process writes, rewrites, replacement, rotation and unsafe tails trigger a full read. Custom warning callbacks bypass sharing. Cancelling one waiter does not stop another waiter.
740
+
741
+ ## Local masking
742
+
743
+ 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.
744
+
745
+ 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.
746
+
747
+ Rules and a local model replace detected values with stable placeholders. Replies and tool arguments restore their values before delivery. The placeholder seed is private local configuration; original-value mappings live only with the request and are never added to CCDX logs or backups. A restart retains the seed, not the mappings. Local history keeps client-visible text rather than placeholders.
748
+
749
+ 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.
750
+
751
+ 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.
752
+
753
+ 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.
754
+
755
+ 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.5",
3
+ "version": "1.3.6",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  import { createRequestId, runWithRequestContext, currentRequestContext } from "./request-context.mjs";
12
12
  import { requestApplication } from "./request-application.mjs";
13
13
  import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
14
+ import { createLocalPrivacy } from "./local-privacy.mjs";
14
15
  import { status } from "./status.mjs";
15
16
  import { exportResponseHistory, importResponseHistory } from "./response-history.mjs";
16
17
  import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
@@ -175,8 +176,10 @@ export function createAdapterHandler(options = {}) {
175
176
  const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics();
176
177
  const imagePressure = options.imagePressure || createResponsesImagePressureController();
177
178
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
179
+ const privacy = options.privacy || options.providerRuntime?.privacy || createLocalPrivacy({ env: options.env, home: options.dashboardOptions?.home });
178
180
  const httpErrors = createHttpFailureDiagnostics();
179
181
  const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
182
+ privacy,
180
183
  contextSnapshotFn: () => {
181
184
  const snapshots = [streamPerformanceMetrics.contextSnapshot?.(), options.providerRuntime?.claudePerformance?.contextSnapshot?.()];
182
185
  const combine = name => snapshots.flatMap((data, index) => (data?.[name] || []).map(entry => ({ ...entry, id: `${index}-${entry.id}` })));
@@ -188,12 +191,12 @@ export function createAdapterHandler(options = {}) {
188
191
  providerAccountsFn: () => options.providerRuntime.action({ action: "accounts" }),
189
192
  connectionsFn: input => options.providerRuntime.manageConnections(input) } : {}) } });
190
193
  const activityEvents = createActivityEvents({
191
- sources: [requestMetrics, streamPerformanceMetrics, options.providerRuntime?.claudePerformance],
194
+ sources: [requestMetrics, streamPerformanceMetrics, options.providerRuntime?.claudePerformance, privacy],
192
195
  snapshot: () => {
193
196
  const requests = requestMetrics.snapshot(), image = optionalRoutes.imageStats();
194
197
  const active = ["responses", "responses_compact", "messages"].reduce((sum, route) => sum + requests.by_route[route].active, image?.active || 0);
195
198
  const claude = options.providerRuntime?.claudePerformance?.activitySnapshot?.();
196
- return { ...adapterHealthPayload(), scope: "activity", uptime_ms: Math.round(process.uptime() * 1000),
199
+ return { ...adapterHealthPayload(), scope: "activity", uptime_ms: Math.round(process.uptime() * 1000), local_privacy: privacy.snapshot(),
197
200
  model_activity: { active }, requests, runtime_usage: runtimeUsageSnapshot(),
198
201
  stream_performance: streamPerformanceMetrics.activitySnapshot(),
199
202
  ...(claude ? { providers: { claude: { requests: { performance: claude } } } } : {}),
@@ -225,6 +228,7 @@ export function createAdapterHandler(options = {}) {
225
228
  },
226
229
  });
227
230
  const responsesHandler = createResponsesHandler({
231
+ privacy,
228
232
  validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
229
233
  resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
230
234
  providerPreference: id => options.providerRuntime?.providerPreference?.(id),
@@ -247,6 +251,7 @@ export function createAdapterHandler(options = {}) {
247
251
  upstreamTimeoutMs,
248
252
  });
249
253
  const responsesCompactHandler = createResponsesCompactHandler({
254
+ privacy,
250
255
  validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
251
256
  resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
252
257
  providerPreference: id => options.providerRuntime?.providerPreference?.(id),
@@ -268,7 +273,7 @@ export function createAdapterHandler(options = {}) {
268
273
  function handlersFor(provider) {
269
274
  if (!provider || provider.id === "github") return githubHandlers;
270
275
  if (!providerHandlers.has(provider)) {
271
- const common = { provider, acquireRequest, imagePressure, keepaliveIntervalMs: options.keepaliveIntervalMs,
276
+ const common = { provider, privacy, acquireRequest, imagePressure, keepaliveIntervalMs: options.keepaliveIntervalMs,
272
277
  validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
273
278
  resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
274
279
  providerPreference: id => options.providerRuntime?.providerPreference?.(id),
@@ -519,7 +524,7 @@ export function createAdapterHandler(options = {}) {
519
524
  if (state?.version !== 1) throw new Error("Unsupported service-state version");
520
525
  importResponseHistory(state.history);await optionalRoutes.importState(state.optional);
521
526
  };
522
- handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose(); };
527
+ handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();if (!options.providerRuntime?.privacy) privacy.close(); };
523
528
  return handler;
524
529
  }
525
530
 
@@ -72,12 +72,11 @@ export function syncClaudeCapabilities(plan, options = {}) {
72
72
  for (const [id, value] of Object.entries(plan.budgets)) add(["modelSettings", id, "autoCompactWindow"], value);
73
73
  }
74
74
  const active = new Set(operations.map(op => op.keys.join(".")));
75
- const restored = reconcileClaudeConfiguration([], { ...options, restore: true,
76
- selectOperation: op => op.file === paths.code && (ownedFields.includes(op.keys.join(".")) || op.keys[0] === "modelSettings" && op.keys[2] === "autoCompactWindow") && !active.has(op.keys.join(".")) });
77
- const result = reconcileClaudeConfiguration(operations, options);
78
- return { state: conflict || result.preserved || restored.preserved ? "partially_preserved" : operations.length ? "configured" : "limited",
79
- changed: result.changed || restored.changed, preserved: result.preserved + restored.preserved,
80
- restart_required: result.changed || restored.changed };
75
+ const result = reconcileClaudeConfiguration(operations, { ...options,
76
+ restoreSelect: op => op.file === paths.code && (ownedFields.includes(op.keys.join(".")) || op.keys[0] === "modelSettings" && op.keys[2] === "autoCompactWindow") && !active.has(op.keys.join(".")) });
77
+ return { state: conflict || result.preserved ? "partially_preserved" : operations.length ? "configured" : "limited",
78
+ changed: result.changed, preserved: result.preserved,
79
+ restart_required: result.changed };
81
80
  }
82
81
 
83
82
  export function inspectClaudeCapabilityConfiguration(models, options = {}) {
@@ -114,7 +114,7 @@ function appModelsOwned(current, previous, desired, alreadyDesired) {
114
114
  withoutAppPreference(recorded.filter(model => wanted.has(model.name))));
115
115
  }
116
116
 
117
- export function reconcileClaudeConfiguration(operations, { restore = false, restoreFields = [], ...options } = {}) {
117
+ export function reconcileClaudeConfiguration(operations, { restore = false, restoreFields = [], restoreSelect, ...options } = {}) {
118
118
  const paths = claudeClientPaths(options), allowed = new Set(Object.values(paths)), journalPath = m365Paths(options).ownership;
119
119
  fs.mkdirSync(path.dirname(journalPath), { recursive: true, mode: 0o700 });
120
120
  return withFileLockSync(`${journalPath}.lock`, () => {
@@ -138,7 +138,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
138
138
  const forClient = op => (!options.selectOperation || options.selectOperation(op)) && (!options.client || (options.client === "claude_code" ? op.file === paths.code && !sharedOperation(op) : op.file !== paths.code))
139
139
  && (!options.fields || options.fields.includes(op.keys.join(".")));
140
140
  const list = restore ? journal.operations.filter(forClient) : [
141
- ...journal.operations.filter(op => forClient(op) && restoreFields.includes(op.keys.join("."))).map(op => ({ ...op, restore: true })), ...operations];
141
+ ...journal.operations.filter(op => forClient(op) && (restoreFields.includes(op.keys.join(".")) || restoreSelect?.(op))).map(op => ({ ...op, restore: true })), ...operations];
142
142
  for (const operation of list) {
143
143
  if (!allowed.has(operation.file) || !safeKeys(operation)) throw new Error("Unexpected Claude configuration path");
144
144
  if (!states.has(operation.file)) states.set(operation.file, read(operation.file));
@@ -61,12 +61,12 @@ function authenticated(headers, key) {
61
61
  // Observe bounded SSE frames. Alias clients rewrite only message_start.model;
62
62
  // other frames retain their wire text. Client backpressure controls upstream reads.
63
63
  export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clientModel = null) {
64
- const decoder = new TextDecoder("utf-8", { fatal: Boolean(clientModel) });let fragments = [], lineBytes = 0, data = [], frameBytes = 0, wire = [], wireBytes = 0, output = [];
64
+ const decoder = new TextDecoder("utf-8", { fatal: true });let fragments = [], lineBytes = 0, data = [], frameBytes = 0, wire = [], wireBytes = 0, output = [];
65
65
  const frame = () => {
66
66
  let value;
67
67
  if (data.length) { try { value = JSON.parse(data.join("\n")); } catch { throw new Error("Invalid Claude stream event"); }onEvent(value); }
68
- if (clientModel && wire.length) {
69
- if (value?.type === "message_start" && value.message && typeof value.message === "object" && !Array.isArray(value.message)) {
68
+ if (wire.length) {
69
+ if (clientModel && value?.type === "message_start" && value.message && typeof value.message === "object" && !Array.isArray(value.message)) {
70
70
  const replacement = JSON.stringify({ ...value, message: { ...value.message, model: clientModel } });let replaced = false;
71
71
  wire = wire.map(line => {
72
72
  if (!line.startsWith("data:")) return line;
@@ -79,7 +79,7 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
79
79
  data = [];frameBytes = 0;
80
80
  };
81
81
  const line = (value, newline = true) => {
82
- if (clientModel) {
82
+ {
83
83
  wireBytes += Buffer.byteLength(value) + (newline ? 1 : 0);
84
84
  if (wireBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");
85
85
  wire.push(value + (newline ? "\n" : ""));
@@ -96,18 +96,18 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
96
96
  while (start < text.length) {
97
97
  const newline = text.indexOf("\n", start), end = newline < 0 ? text.length : newline, part = text.slice(start, end);
98
98
  lineBytes += Buffer.byteLength(part);
99
- if (lineBytes > maxBytes || clientModel && wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
99
+ if (lineBytes > maxBytes || wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
100
100
  fragments.push(part);
101
101
  if (newline < 0) break;
102
102
  line(fragments.join(""));fragments = [];lineBytes = 0;start = newline + 1;
103
103
  }
104
104
  }
105
105
  return { write(chunk) { output = [];consume(decoder.decode(chunk, { stream: true }));return output; },
106
- finish() { output = [];consume(decoder.decode());if (fragments.length) line(fragments.join(""), false);frame();return output; } };
106
+ 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
107
  }
108
108
 
109
109
  export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
110
- resolveRequest, record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
110
+ resolveRequest, privacy, privacyClient = "claude", record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
111
111
  if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
112
112
  const config = loadRuntimeConfig(env), performance = sharedPerformance || createStreamPerformanceMetrics({ routeNames: ["messages"] });
113
113
  const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
@@ -179,7 +179,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
179
179
  conversation = validateConversation?.(body, req.headers, selectedProvider);
180
180
  if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
181
181
  terminalOrigin = "transport";
182
- const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
182
+ const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
183
+ const upstream = await call(body, { headers: req.headers, countTokens, signal: abort.signal,
183
184
  onCountObservation(value) {
184
185
  context.countObservation = { ...context.countObservation, ...value };
185
186
  if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
@@ -242,7 +243,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
242
243
  tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
243
244
  const frames = observer.write(value);
244
245
  let writable = true;
245
- for (const chunk of clientModel ? frames : [value]) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) { writable = false;break; }
246
+ for (const chunk of frames) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) { writable = false;break; }
246
247
  if (!writable) break;
247
248
  if (sawStop || failedEvent) break;
248
249
  }
@@ -18,6 +18,7 @@ import { createApiModelDisplayStore } from "./api-model-display.mjs";
18
18
  import { createCodexMemoryModel } from "./codex-memory-model.mjs";
19
19
  import { readClientGatewayKeys, gatewayClient } from "./client-gateway-keys.mjs";
20
20
  import { createClaudeGatewayHandler } from "./claude-gateway.mjs";
21
+ import { createLocalPrivacy } from "./local-privacy.mjs";
21
22
  import {
22
23
  configureClaudeClients,
23
24
  restoreClaudeClients,
@@ -72,6 +73,7 @@ export function createConnectionRuntime({
72
73
  onTransfer: () => log("info", "Conversation continued on the selected source; original history kept"),
73
74
  });
74
75
  const memoryModel = createCodexMemoryModel({ ...options, corePort });
76
+ const privacy = createLocalPrivacy(options);
75
77
  let settings = readAccessSettings(options),
76
78
  managed = fs.existsSync(accessSettingsPath(options)),
77
79
  serial = Promise.resolve(),
@@ -1233,7 +1235,8 @@ export function createConnectionRuntime({
1233
1235
  state?.credentials || [],
1234
1236
  settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)
1235
1237
  ),
1236
- busy: () =>
1238
+ privacy,
1239
+ busy: () => privacy.busy() ||
1237
1240
  operations > 0 ||
1238
1241
  active.size > 0 ||
1239
1242
  Boolean(syncFlight) ||
@@ -1468,6 +1471,8 @@ export function createConnectionRuntime({
1468
1471
  provider: catalog,
1469
1472
  acquireRequest: acquireClaudeRequest,
1470
1473
  apiKey: identities()[id],
1474
+ privacy,
1475
+ privacyClient: id,
1471
1476
  env,
1472
1477
  log,
1473
1478
  performance: legacy.claudePerformance,
@@ -1655,6 +1660,7 @@ export function createConnectionRuntime({
1655
1660
  },
1656
1661
  async close() {
1657
1662
  closed = true;
1663
+ privacy.close();
1658
1664
  await memoryModel.close();
1659
1665
  await catalogRefresh.close();
1660
1666
  await serial;
@@ -113,6 +113,7 @@
113
113
  }
114
114
  window.addEventListener("ccdx:providers", () => { syncSources();if (current === "codex") void loadSourceModels(); });
115
115
  function applySettings(data, meta) {
116
+ globalThis.ccdxPrivacy?.sync(data.local_privacy);
116
117
  settings = data;
117
118
  const nightly = data.nightly_update;
118
119
  el("nightly-update").checked = nightly?.enabled === true;el("nightly-update").disabled = false;
@@ -320,6 +321,7 @@
320
321
  });
321
322
  el("auto-refresh").addEventListener("click", schedule);
322
323
  el("refresh").addEventListener("click", () => { if (settingsViews.includes(current)) void loadSettings(); });
324
+ document.addEventListener("ccdx:privacy-preferences", event => { if (event.detail?.preferences) preferences?.sync(event.detail);else if (settingsViews.includes(current)) void loadSettings(); });
323
325
  window.addEventListener("pagehide", () => { stopped = true;clearTimeout(timer); });
324
326
  window.addEventListener("pageshow", () => { stopped = false;schedule(); });
325
327
  navigate();schedule();
@@ -26,6 +26,7 @@
26
26
  <script src="/console.js" defer></script>
27
27
  <script src="/tools.js" defer></script>
28
28
  <script src="/connections.js" defer></script>
29
+ <script src="/privacy.js" defer></script>
29
30
  <title data-i18n="ccdx_local_dashboard">CCDX · Dashboard</title>
30
31
  </head>
31
32
  <body>
@@ -436,6 +437,18 @@
436
437
  <p id="install-windows-policy" class="hint" hidden data-i18n="update_windows_policy">If scripts are blocked, use your company’s approved installation method.</p>
437
438
  </details><p id="update-copy-note" class="hint" role="status"></p>
438
439
  </section>
440
+ <section class="panel dashboard-section" id="privacy-settings" aria-labelledby="privacy-heading">
441
+ <h2 id="privacy-heading" data-i18n="privacy_heading">ADVANCED</h2>
442
+ <div class="setting-row"><label for="privacy-enabled" data-i18n="privacy_enable">Local masking</label><input id="privacy-enabled" type="checkbox" role="switch" disabled><span id="privacy-status" class="hint" role="status" aria-live="polite"></span></div>
443
+ <p class="hint" data-i18n="privacy_scope">Conversation and tool text. Images and predictions keep their current behavior.</p>
444
+ <div id="privacy-options" hidden>
445
+ <div class="setting-row"><label for="privacy-personal" data-i18n="privacy_personal">Include personal information</label><input id="privacy-personal" type="checkbox" role="switch"><span id="privacy-device" class="hint"></span></div>
446
+ <p class="hint" data-i18n="privacy_personal_hint">Names and addresses may be mistaken for code.</p>
447
+ <details class="privacy-preview"><summary data-i18n="privacy_try">Try locally</summary><label for="privacy-text" data-i18n="privacy_sample">Sample text</label><textarea id="privacy-text" rows="3" maxlength="8192" spellcheck="false"></textarea><div class="section-actions"><button id="privacy-preview" type="button" data-i18n="privacy_check">Check text</button><span id="privacy-preview-count" class="hint" role="status"></span></div><pre id="privacy-result" hidden></pre></details>
448
+ </div>
449
+ <div class="section-actions"><button id="privacy-cancel" type="button" hidden data-i18n="cancel">Cancel</button><button id="privacy-retry" type="button" hidden data-i18n="view_retry">Retry</button><button id="privacy-remove" type="button" hidden data-i18n="privacy_remove">Delete model</button><p id="privacy-error" class="hint" role="alert"></p></div>
450
+ </section>
451
+ <dialog id="privacy-dialog" class="preferences-dialog" aria-labelledby="privacy-dialog-title"><h2 id="privacy-dialog-title" data-i18n="privacy_enable">Local masking</h2><p data-i18n="privacy_download">Downloads about 39 MB plus the local component. Checks may add delay or mistake ordinary text.</p><p data-i18n="privacy_fail_closed">If a check cannot finish, the request is not sent.</p><div class="section-actions"><button id="privacy-dialog-cancel" type="button" data-i18n="cancel">Cancel</button><button id="privacy-dialog-confirm" type="button" data-i18n="privacy_confirm">Download &amp; enable</button></div></dialog>
439
452
  <section class="panel dashboard-section" id="settings-preferences" aria-labelledby="preferences-heading">
440
453
  <h2 id="preferences-heading" data-i18n="preferences_heading">SAVE &amp; RESTORE</h2>
441
454
  <div class="preferences-row"><div><label for="preferences-auto" data-i18n="preferences_auto">Save changes automatically</label><p class="hint" data-i18n="preferences_auto_hint">Valid changes on this page save automatically.</p></div><input id="preferences-auto" type="checkbox" role="switch" disabled checked></div>
@@ -1,5 +1,10 @@
1
1
  (() => {
2
2
  const translations = {
3
+ privacy_heading: ["ADVANCED", "高级"], privacy_enable: ["Local masking", "本地脱敏"], privacy_scope: ["Conversation and tool text. Images and predictions keep their current behavior.", "检查对话和工具文本。图片与预测保持原有行为。"], privacy_state_checking: ["On · checking locally", "已开启 · 本地检查中"],
4
+ privacy_personal: ["Include personal information", "同时保护个人信息"], privacy_personal_hint: ["Names and addresses may be mistaken for code.", "姓名和地址可能与代码混淆。"], privacy_try: ["Try locally", "本地试用"], privacy_sample: ["Sample text", "试用文本"], privacy_check: ["Check text", "检查文本"], privacy_remove: ["Delete model", "删除模型"],
5
+ privacy_download: ["Downloads about 39 MB plus the local component. Checks may add delay or mistake ordinary text.", "下载约 39 MB 模型及本地组件。检查可能增加等待或误识别。"], privacy_fail_closed: ["If a check cannot finish, the request is not sent.", "检查未完成时,请求不会发出。"], privacy_confirm: ["Download & enable", "下载并开启"],
6
+ privacy_state_off: ["Off", "已关闭"], privacy_state_downloading: ["Downloading · {percent}%", "下载中 · {percent}%"], privacy_state_loading: ["Loading locally", "本地加载中"], privacy_state_ready: ["On · keys and passwords", "已开启 · 密钥与密码"], privacy_state_error: ["Not ready", "尚未就绪"], privacy_state_installed: ["Downloaded · off", "已下载 · 已关闭"], privacy_result: ["{count} values masked · {ms} ms", "脱敏 {count} 项 · {ms} ms"],
7
+ privacy_error: ["Check could not finish. Nothing was sent; retry or review these settings.", "检查未完成,未发送请求。请重试或检查设置。"], privacy_download_error: ["Download failed. Check approved download access, proxy and certificates.", "下载失败。请检查下载权限、代理和证书。"], privacy_changed: ["Settings changed elsewhere. Reload this section before trying again.", "设置已在其他窗口修改。请刷新后重试。"], privacy_preview_error: ["Local check failed. No text was sent to a provider.", "本地检查失败。未向模型来源发送文本。"],
3
8
  "client_key_encrypted_kept": ["Key kept encrypted; access not checked.", "密钥保持加密,访问未验证。"],
4
9
  "context_tabs": ["Usage view", "统计视图"],
5
10
  "context_unknown_window": ["Unknown", "未知"],
@@ -54,10 +54,10 @@
54
54
  }
55
55
  function sync(data, { readVersion } = {}) {
56
56
  if (!data.preferences) return;
57
- terminalMode = data.terminal?.mode;
57
+ if (data.terminal) terminalMode = data.terminal.mode;
58
58
  if (readVersion !== undefined && readVersion !== version || pending) { render();return; }
59
59
  const next = data.preferences;
60
- locks.terminal_animation_enabled = data.effective?.terminal_animation_enabled?.locked;
60
+ if (data.effective) locks.terminal_animation_enabled = data.effective.terminal_animation_enabled?.locked;
61
61
  if (base) for (const key of Object.keys(draft)) {
62
62
  if (next.values[key] === draft[key]) delete draft[key];
63
63
  else if (next.values[key] !== base.values[key]) { conflict = true;error = "preferences_changed"; }
@@ -0,0 +1,67 @@
1
+ (() => {
2
+ const el = id => document.getElementById(id), root = el("privacy-settings");if (!root) return;
3
+ const words = (id, key, values) => globalThis.ccdxLanguage.set(el(id), key, values);
4
+ let state = null, pending = false, timer, pushed = 0;
5
+ const visible = () => !root.closest("[hidden]") && document.visibilityState === "visible";
6
+ function apply(value) {
7
+ const previous = state?.revision;state = value;render();
8
+ if (value.preferences || previous && previous !== state.revision) document.dispatchEvent(new CustomEvent("ccdx:privacy-preferences", { detail: value.preferences ? { preferences: value.preferences } : null }));
9
+ }
10
+ async function request(input) {
11
+ const response = await fetch("/_ccdx/ui/privacy", { method: input ? "POST" : "GET", headers: { "X-CCDX-Dashboard": "1", ...(input ? { "Content-Type": "application/json" } : {}) }, body: input ? JSON.stringify(input) : undefined, signal: AbortSignal.timeout(20000) });
12
+ const data = await response.json();if (!response.ok) throw Object.assign(Error(), { code: data.code });return data;
13
+ }
14
+ function render() {
15
+ if (!state) return;
16
+ const busy = pending || state.action_pending || ["downloading", "loading"].includes(state.state);
17
+ el("privacy-enabled").checked = state.enabled;el("privacy-enabled").disabled = pending || busy && !state.enabled;
18
+ el("privacy-personal").checked = state.personal;el("privacy-personal").disabled = busy;
19
+ el("privacy-options").hidden = !state.enabled || state.state !== "ready";
20
+ el("privacy-cancel").hidden = !busy;el("privacy-cancel").disabled = pending;
21
+ el("privacy-retry").hidden = state.state !== "error" && !state.error;el("privacy-retry").disabled = pending;
22
+ el("privacy-remove").hidden = busy || state.state === "not_downloaded";el("privacy-remove").disabled = pending;
23
+ const status = ["downloading", "loading", "error"].includes(state.state) ? state.state : state.enabled ? state.state === "ready" ? state.pending_checks ? "checking" : "ready" : "error" : state.state === "installed" || state.state === "ready" ? "installed" : "off";
24
+ words("privacy-status", `privacy_state_${status}`, { percent: Math.min(100, Math.round((state.downloaded_bytes || 0) * 100 / Math.max(1, state.download_bytes))) });
25
+ el("privacy-device").textContent = state.backend || "";
26
+ if (state.error) words("privacy-error", state.error.includes("download") ? "privacy_download_error" : "privacy_error");
27
+ else { el("privacy-error").textContent = "";el("privacy-error").removeAttribute("data-i18n"); }
28
+ clearTimeout(timer);
29
+ if (busy && visible()) timer = setTimeout(() => { if (Date.now() - pushed > 2500) void load();else render(); }, 3000);
30
+ }
31
+ async function load() {
32
+ if (!visible() || pending) return;
33
+ try { apply(await request()); } catch { words("privacy-error", "privacy_error"); }
34
+ }
35
+ async function act(action, extra = {}) {
36
+ if (!state || pending) return;
37
+ pending = true;render();
38
+ try { apply(await request({ action, revision: state.revision, ...extra })); }
39
+ catch (error) { words("privacy-error", error.code === "ccdx_privacy_settings_changed" ? "privacy_changed" : "privacy_error");await load(); }
40
+ finally { pending = false;render(); }
41
+ }
42
+ function enable() { el("privacy-dialog").showModal(); }
43
+ el("privacy-enabled").addEventListener("change", () => {
44
+ if (el("privacy-enabled").checked) { el("privacy-enabled").checked = false;enable(); }
45
+ else void act("disable");
46
+ });
47
+ el("privacy-personal").addEventListener("change", () => void act("personal", { personal: el("privacy-personal").checked }));
48
+ el("privacy-dialog-cancel").addEventListener("click", () => el("privacy-dialog").close());
49
+ el("privacy-dialog-confirm").addEventListener("click", () => { el("privacy-dialog").close();void act("enable"); });
50
+ el("privacy-cancel").addEventListener("click", () => void act("disable"));
51
+ el("privacy-retry").addEventListener("click", () => void act("enable"));
52
+ el("privacy-remove").addEventListener("click", () => void act("remove"));
53
+ el("privacy-preview").addEventListener("click", async () => {
54
+ const trigger = el("privacy-preview");trigger.disabled = true;el("privacy-result").hidden = true;
55
+ try {
56
+ const result = await request({ action: "try", text: el("privacy-text").value });
57
+ el("privacy-result").textContent = result.text;el("privacy-result").hidden = false;
58
+ words("privacy-preview-count", "privacy_result", { count: result.count, ms: result.elapsed_ms });
59
+ } catch { words("privacy-preview-count", "privacy_preview_error"); }
60
+ finally { trigger.disabled = false; }
61
+ });
62
+ document.addEventListener("visibilitychange", () => { clearTimeout(timer);if (visible()) void load(); });
63
+ window.addEventListener("hashchange", () => { clearTimeout(timer);if (visible()) void load(); });
64
+ el("refresh").addEventListener("click", () => void load());
65
+ globalThis.ccdxPrivacy = { sync(value) { if (!value || !visible()) return;pushed = Date.now();apply(value); } };
66
+ void load();
67
+ })();
@@ -383,7 +383,8 @@
383
383
  const key = String(request.request_id || `${request.at || ""}/${request.provider || ""}/${request.model || ""}`).slice(0, 256);
384
384
  details.setAttribute?.("data-request-key", key);details.open = expanded.has(key);
385
385
  details.className = "request-details";fields.className = "failure-detail";
386
- localize(summary, "request_metadata");details.append(summary, fields);
386
+ if (Number.isSafeInteger(context.privacy_count)) globalThis.ccdxLanguage.set(summary, "privacy_result", { count: context.privacy_count, ms: context.privacy_ms || 0 });
387
+ else localize(summary, "request_metadata");details.append(summary, fields);
387
388
  for (const [key, value] of [["request_id", request.request_id || "—"], ["http_status", number(request.http_status)], ["attempts", number(request.upstream_attempts)], ["model_outcome", globalThis.ccdxLanguage?.format(outcome.toLowerCase()) || outcome],
388
389
  ["time", Number.isFinite(at) ? time(at, { date: true }) : "—"],
389
390
  ["wire_mib", finite(context.payload_bytes) ? `${(Number(context.payload_bytes) / 1048576).toFixed(2)} MiB` : "—"],
@@ -634,6 +634,10 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
634
634
  #preferences-save, #preferences-dialog-confirm { background:var(--accent); color:var(--page); border-color:var(--accent); }
635
635
  .preferences-dialog { width:480px; max-width:calc(100% - 32px); padding:25px; border:1px solid var(--border); border-radius:2px; background:var(--surface); color:var(--text); font:inherit; }
636
636
  .preferences-dialog::backdrop { background:#0007; }
637
+ .privacy-preview { margin-top:12px; }
638
+ .privacy-preview label { display:block; margin:12px 0 6px; }
639
+ .privacy-preview textarea { width:100%; box-sizing:border-box; resize:vertical; padding:8px; color:var(--text); background:var(--surface); border:1px solid var(--border); border-radius:2px; font:inherit; }
640
+ .privacy-preview pre { white-space:pre-wrap; overflow-wrap:anywhere; margin:12px 0 0; font-size:12px; }
637
641
  .preferences-dialog h2 { font-size:19px; margin:0 0 18px; color:var(--strong); }
638
642
  .preferences-dialog p, .preferences-dialog dl { font-size:12px; line-height:1.8; }
639
643
  .preferences-dialog dl > div { display:grid; grid-template-columns:80px minmax(0,1fr); gap:12px; margin-top:12px; }
@@ -426,6 +426,7 @@ let liveCompleted = null;
426
426
  const liveActivity = globalThis.ccdxLive.create({
427
427
  visible: () => document.visibilityState === "visible",
428
428
  apply: data => {
429
+ globalThis.ccdxPrivacy?.sync(data.local_privacy);
429
430
  renderActivity(data);
430
431
  const completed = JSON.stringify([data.instance_id, data.requests?.completed]);
431
432
  if (completed !== liveCompleted && globalThis.ccdxContextView?.visible()) void dashboardRefresh.refresh("context", { force: true });
@@ -18,6 +18,7 @@ import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroup
18
18
  import { createUsageAnalytics } from "./usage-analytics.mjs";
19
19
  import { analyzeUsageLogs } from "./usage-analysis.mjs";
20
20
  import { readUserSettings, terminalAnimationPreference, writeTerminalAnimationTheme } from "./user-settings.mjs";
21
+ import { settingsPreferencesSnapshot } from "./settings-preferences.mjs";
21
22
 
22
23
  const ANIMATION_PATH = "/_ccdx/ui/animation";
23
24
  const MODELS_PATH = "/_ccdx/ui/models/live";
@@ -152,6 +153,7 @@ export async function handleDashboardApi(req, res, pathname, {
152
153
  updateStatusFn,
153
154
  serviceControl,
154
155
  applyAnimation,
156
+ privacy,
155
157
  tools,
156
158
  } = {}) {
157
159
  if (!isLoopbackAddress(req.socket?.remoteAddress)
@@ -165,6 +167,19 @@ export async function handleDashboardApi(req, res, pathname, {
165
167
  return;
166
168
  }
167
169
 
170
+ if (pathname === "/_ccdx/ui/privacy") {
171
+ if (!privacy) { sendJson(res, 503, { code: "ccdx_privacy_unavailable" });return; }
172
+ if (req.headers.origin && !sameOrigin(req)) { sendJson(res, 403, { code: "ccdx_privacy_origin_required" });return; }
173
+ if (req.method === "GET") { sendJson(res, 200, { ...privacy.snapshot(), preferences: settingsPreferencesSnapshot({ home, env }) });return; }
174
+ if (req.method !== "POST") { sendJson(res, 405, { error: "Use GET or POST" });return; }
175
+ if (!sameOrigin(req) || !/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { sendJson(res, 403, { code: "ccdx_privacy_origin_required" });return; }
176
+ const abort = createRequestAbort(req, res);abort.setTimeout(5000, "request_body_timeout");
177
+ try {
178
+ const input = await readJsonBody(req, { maxBodyBytes: 16384, maxDecodedBodyBytes: 16384, signal: abort.signal });abort.clearTimeout();
179
+ sendJson(res, 200, { ...await privacy.action(input), preferences: settingsPreferencesSnapshot({ home, env }) });
180
+ } catch (error) { sendJson(res, error.statusCode || 503, { code: /^ccdx_privacy_[a-z_]+$/.test(error.code || "") ? error.code : "ccdx_privacy_unavailable" }); }
181
+ finally { abort.cleanup(); }return;
182
+ }
168
183
  if (pathname === "/_ccdx/ui/context") {
169
184
  if (req.method !== "GET") { sendJson(res, 405, { error: "Use GET" });return; }
170
185
  if (req.headers.origin && !sameOrigin(req)) { sendJson(res, 403, { error: "Context requires the same-origin dashboard" });return; }
package/src/dashboard.mjs CHANGED
@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";
4
4
  import { ADAPTER_VERSION } from "./running-adapter.mjs";
5
5
 
6
6
  const ASSETS = new Map([
7
+ ["/privacy.js", ["./dashboard/privacy.js", "text/javascript; charset=utf-8"]],
7
8
  ["/", ["./dashboard/index.html", "text/html; charset=utf-8"]],
8
9
  ["/ui.css", ["./dashboard/ui.css", "text/css; charset=utf-8"]],
9
10
  ["/theme.js", ["./dashboard/theme.js", "text/javascript; charset=utf-8"]],