codex-copilot-dx 1.3.4 → 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 +4 -2
- package/docs/ARCHITECTURE.md +42 -5
- package/docs/README.md +2 -0
- package/docs/REFERENCE.md +31 -2
- package/package.json +1 -1
- package/src/adapter.mjs +13 -8
- package/src/claude-capability-config.mjs +5 -6
- package/src/claude-client-config.mjs +8 -5
- package/src/claude-gateway.mjs +10 -9
- package/src/cli-management.mjs +3 -2
- package/src/client-integration.mjs +1 -1
- package/src/client-model-plan.mjs +10 -0
- package/src/connection-runtime.mjs +31 -9
- package/src/dashboard/connections.js +2 -2
- package/src/dashboard/console.js +2 -0
- package/src/dashboard/index.html +15 -2
- package/src/dashboard/language.js +15 -0
- package/src/dashboard/preferences.js +2 -2
- package/src/dashboard/privacy.js +67 -0
- package/src/dashboard/status.js +3 -1
- package/src/dashboard/ui.css +11 -0
- package/src/dashboard/ui.js +6 -0
- package/src/dashboard-api.mjs +19 -0
- package/src/dashboard.mjs +1 -0
- package/src/local-privacy.mjs +135 -0
- package/src/native-prediction-app.mjs +67 -0
- package/src/native-prediction-fix.mjs +1 -1
- package/src/native-prediction-profile.mjs +2 -36
- package/src/native-prediction-state.mjs +4 -1
- package/src/native-prediction-transport.mjs +21 -7
- package/src/native-prediction-windows.mjs +28 -11
- package/src/native-prediction.mjs +5 -3
- package/src/optional-routes.mjs +2 -2
- package/src/privacy-model.mjs +161 -0
- package/src/privacy-notices.txt +104 -0
- package/src/privacy-transform.mjs +192 -0
- package/src/provider-runtime.mjs +4 -3
- package/src/response-failures.mjs +12 -1
- package/src/responses-handler.mjs +11 -2
- package/src/responses-proxy.mjs +3 -3
- package/src/service-control.mjs +2 -1
- package/src/settings-preferences.mjs +3 -2
- package/src/startup-ui.mjs +1 -1
- package/src/stream-performance.mjs +1 -1
- package/src/terminal-colors.mjs +9 -5
- package/src/usage-analysis.mjs +79 -36
- package/src/usage-analytics.mjs +1 -0
- package/src/usage-store.mjs +21 -11
- package/src/usage.mjs +2 -0
- package/src/user-settings.mjs +3 -3
- package/src/native-prediction-protocol.mjs +0 -45
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.
|
|
19
|
-
- Windows: [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.3.
|
|
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
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -345,6 +345,9 @@ startup cleanup closes any optional listener that was already started.
|
|
|
345
345
|
Only its two selected hosts use the App-specific route. Non-configuration requests
|
|
346
346
|
on those hosts are forwarded unchanged. The bridge does not replace Copilot or
|
|
347
347
|
image-provider networking, modify client program files, or install system trust.
|
|
348
|
+
App identity checks use system metadata and asynchronous platform verification,
|
|
349
|
+
without reading an App archive or renderer implementation. Only recognized live
|
|
350
|
+
configuration responses receive the existing prediction overlay.
|
|
348
351
|
Static upstream proxy routes and bypass rules are preserved. IPv4/IPv6 CIDRs
|
|
349
352
|
match URL IP literals, without DNS. macOS dynamic PAC/WPAD remains unsupported
|
|
350
353
|
and is reported rather than discarded.
|
|
@@ -390,10 +393,16 @@ only, preserves company/user routing, and never treats a saved preference as
|
|
|
390
393
|
proof of a running route or visible candidate. App compatibility is rechecked only
|
|
391
394
|
when its recorded identity changes, before existing trust/port checks are reused.
|
|
392
395
|
|
|
393
|
-
`native-prediction-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
396
|
+
`native-prediction-app.mjs` owns asynchronous installation identity checks. macOS
|
|
397
|
+
uses signed bundle metadata and executable stamps; Windows uses the official Store
|
|
398
|
+
registration and executable stamp. Renderer files and archive layout are not
|
|
399
|
+
compatibility gates. Concurrent checks share a bounded signature result cache.
|
|
400
|
+
Legacy identity records are reverified on first use while keeping their certificate,
|
|
401
|
+
port and profile. A Store update may change its install path only when the official
|
|
402
|
+
package family and selected profile remain the same. Known configuration schemas
|
|
403
|
+
remain the overlay boundary; unknown payloads retain the existing pass-through rules.
|
|
404
|
+
The optional TLS transport has a 64 KiB header budget for requests, replies and
|
|
405
|
+
upgrades, with bounded stage/target diagnostics rather than header contents.
|
|
397
406
|
|
|
398
407
|
`prediction-pac.mjs` is the pure shared format boundary for direct, static and
|
|
399
408
|
Windows company-PAC composition. Its stable revision URL makes a one-time old-PAC
|
|
@@ -650,7 +659,7 @@ management. CLI and UI share advertised effort filtering and preference writes.
|
|
|
650
659
|
|
|
651
660
|
## Independent appearance settings (1.2.2)
|
|
652
661
|
|
|
653
|
-
Web color (`green` / `klein` / `pink`) and dark/light mode are browser-local presentation state applied before CSS in `dashboard/theme.js`. CSS semantic roles keep errors/warnings separate from theme accents. Terminal color uses a distinct `terminal_color_theme` config field; animation continues to use `terminal_animation`. `terminal-colors.mjs` owns terminal color capability checks and escaping, while the existing layout runs on plain text first. The one-per-second coherent settings snapshot carries terminal color; animation frames introduce no additional settings reads. No inference, provider-routing or installer dependency is added.
|
|
662
|
+
Web color (`green` / `klein` / `pink` / `mono`) and dark/light mode are browser-local presentation state applied before CSS in `dashboard/theme.js`. CSS semantic roles keep errors/warnings separate from theme accents. Terminal color (`green`, `klein`, `pink`, `mono`, `orange`) uses a distinct `terminal_color_theme` config field; animation continues to use `terminal_animation`. `terminal-colors.mjs` owns terminal color capability checks and escaping, while the existing layout runs on plain text first. The one-per-second coherent settings snapshot carries terminal color; animation frames introduce no additional settings reads. No inference, provider-routing or installer dependency is added.
|
|
654
663
|
|
|
655
664
|
The existing same-origin bounded settings action saves terminal color through the strict locked atomic writer, then applies it to the live console. Read or save failures retain existing files and controls revert to the last confirmed choice. Model-list check errors project only bounded public diagnostic fields; UI associates them with the selected source and its last successful snapshot. Existing generation checks, cancellation and deduplication prevent late results from replacing another source's data.
|
|
656
665
|
|
|
@@ -1030,3 +1039,31 @@ Messages window observation belongs to `claude-gateway.mjs`, independently of th
|
|
|
1030
1039
|
`dashboard/ui.css` retains the existing color/type system and grid/navigation boundaries. Shared `--control-height` and `--inline-control-height` values align controls at 32/30 px, with 44 px coarse-pointer targets; multiline choice cards keep intrinsic height. Existing narrow-header rules still own reflow. Panel/header/table/form spacing is adjusted in its existing rules rather than adding a second layout mode. Request-flow geometry continues to measure actual anchors after resize and disclosure changes. Browser replays assert actual sizes and unchanged header anchors alongside bilingual themes, model details, drafts and reduced motion.
|
|
1031
1040
|
|
|
1032
1041
|
The Auto refresh button overlays its visible and width-measuring labels in one centered grid cell. Browser acceptance measures the visible text range against the button on both axes, including ON/OFF in both languages; the outer control height alone is not alignment evidence.
|
|
1042
|
+
|
|
1043
|
+
In 1.3.5, expected local GET/HEAD MCP discovery replies retain their HTTP counts
|
|
1044
|
+
and a separate bounded probe history; they do not animate model activity. Unknown
|
|
1045
|
+
paths and security failures remain inspectable. Source catalog details explain
|
|
1046
|
+
client exclusions from current grants, interfaces, policy and selections. They
|
|
1047
|
+
perform no inference or automatic model selection. Removing an owned Claude
|
|
1048
|
+
source-only flag shares the existing configuration/journal rollback transaction.
|
|
1049
|
+
|
|
1050
|
+
Dashboard usage analytics keeps two aggregate checkpoints within 2 MiB. A passive
|
|
1051
|
+
listener exists only while checkpoints are retained. The existing asynchronous
|
|
1052
|
+
writer reports before/after file versions inside its rotation lock; only witnessed
|
|
1053
|
+
non-rotating appends queue delta lines (at most 256 KiB per checkpoint). Queries
|
|
1054
|
+
apply those records without rescanning history. Other-process writes, unknown
|
|
1055
|
+
changes, rotation, incomplete tails, warnings and oversized results rebuild through
|
|
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,8 @@
|
|
|
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.
|
|
8
|
+
- [1.3.5](RELEASE_1.3.5.md): protocol-first App checks, bounded prediction transport and incremental usage analytics.
|
|
7
9
|
- [1.3.4](RELEASE_1.3.4.md): centered Auto refresh labels at compact control heights.
|
|
8
10
|
- [1.3.3](RELEASE_1.3.3.md): live activity updates and compact WebUI spacing.
|
|
9
11
|
- [1.3.2](RELEASE_1.3.2.md): protected App keys, bounded diagnostics and coalesced usage reads.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -86,6 +86,8 @@ Claude App and Claude Code use separate keys on `http://127.0.0.1:2026/anthropic
|
|
|
86
86
|
|
|
87
87
|
Claude App can continue an existing conversation on another selected, authorized source when complete Messages history is available. Unfinished tool turns, unavailable attachments and company-account isolation are checked before transfer. Opaque signed or compacted history is not transferable between services. Codex and Claude Code keep their existing continuation rules. A 409 is a history/isolation conflict; it does not by itself mean the selected model is unavailable.
|
|
88
88
|
|
|
89
|
+
Model details show exclusion reasons only when applicable: app/source disabled, source access not granted, missing interface, source restriction, missing catalog entry or no selection. These are configuration/catalog facts, not an online capability test. Expected local GET/HEAD discovery replies are listed separately under Requests → Service probes. Raw HTTP counters remain unchanged; unknown paths, security denials and actual call failures remain inspectable.
|
|
90
|
+
|
|
89
91
|
## Microsoft 365
|
|
90
92
|
|
|
91
93
|
Supported company environments discover local accounts at startup. Access depends on the account, tenant, device policy and service entitlement. Optional failure does not block another source.
|
|
@@ -133,6 +135,8 @@ Finish active work before updating the active installation, then restart CCDX no
|
|
|
133
135
|
Overnight updates are opt-in. The supervised service checks within its local midnight window, stages only eligible patches in the same minor version, and waits for idle work before handoff. Candidates must be published for at least 24 hours. Failed preparation/handoff retains or restores the previous service. Enabling this feature requires its documented normal restart; it does not attach a supervisor to an existing ordinary process. Minor upgrades such as 1.2 → 1.3 remain manual.
|
|
134
136
|
|
|
135
137
|
|
|
138
|
+
Terminal palettes are green (default), Klein blue, soft pink, black & white (`mono`) and orange. Choose one in Settings → Terminal appearance or with `ccdx config terminal`. Black & white follows the terminal's default foreground without changing its background. Orange adapts to truecolor, 256-color and ANSI; an explicit light `COLORFGBG` uses a darker orange. Non-TTY, `NO_COLOR` and dumb-terminal output keep their plain behavior. Web color remains independent.
|
|
139
|
+
|
|
136
140
|
## Model capabilities and Claude synchronization
|
|
137
141
|
|
|
138
142
|
An explicitly selected default keeps its identity when its catalog entry becomes
|
|
@@ -246,6 +250,15 @@ feature uses the App's existing composer UI and the conversation's
|
|
|
246
250
|
selected model through CCDX. Suggestions are not sent automatically. Native
|
|
247
251
|
eligibility rules still apply; availability is not promised for every thread type.
|
|
248
252
|
|
|
253
|
+
App identity is verified through system installation metadata and platform trust,
|
|
254
|
+
without scanning internal App archives. Checks are asynchronous and leave account,
|
|
255
|
+
model and image settings alone. Existing prediction trust, profile and port are
|
|
256
|
+
reused after an App update. Known live configuration schemas determine adaptation;
|
|
257
|
+
unknown payloads keep their existing forwarding behavior. No configuration traffic
|
|
258
|
+
means unverified availability, not a confirmed incompatibility. Visible suggestions
|
|
259
|
+
still require an App-side check. The bridge accepts headers up to 64 KiB; larger
|
|
260
|
+
headers fail with bounded stage diagnostics and are not retried.
|
|
261
|
+
|
|
249
262
|
The `0.9.40` routing revision uses the stable local PAC URL
|
|
250
263
|
`/proxy.pac?v=2`, independent of the package version. The primary proxy remains
|
|
251
264
|
`127.0.0.1` on the saved port. A secondary, time-bucketed `.localhost` name points
|
|
@@ -646,7 +659,7 @@ The summary covers the current log and its single rotated backup, not an unbound
|
|
|
646
659
|
|
|
647
660
|
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.
|
|
648
661
|
|
|
649
|
-
Repeated plain usage summaries
|
|
662
|
+
Repeated plain usage summaries reuse one bounded entry when retained files are unchanged, with the existing two-second recent-write guard and 256 KiB/128-group limit. Dashboard analytics keeps up to two independent aggregate checkpoints within 2 MiB. Its first read scans both retained logs. Later reads apply only append batches witnessed by this process under the existing write lock, with a 256 KiB pending-delta limit per checkpoint. Another process's writes, rotation, truncation, replacement, incomplete tails, warnings, future/undated records and oversized results fall back to a complete read. Queries remain scoped by source, time zone and local date; returned results are cloned and identical concurrent reads share work. The asynchronous writer supplies file-version evidence only while analytics checkpoints exist. There is no persistent index, background poll or added model request.
|
|
650
663
|
|
|
651
664
|
Diagnostic redaction removes Basic authorization payloads and URL userinfo, and consumes escaped quotes inside sensitive JSON fields. Ordinary Basic-related prose, safe host/path information and error codes are retained. These protections apply to existing failure/status/debug diagnostics, not forwarded requests or upstream response bodies. They do not make arbitrary upstream prose guaranteed safe to share.
|
|
652
665
|
|
|
@@ -723,4 +736,20 @@ Internal supervisor and installer environment fields are not user settings.
|
|
|
723
736
|
|
|
724
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.
|
|
725
738
|
|
|
726
|
-
Usage queries
|
|
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
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";
|
|
@@ -21,7 +22,7 @@ import { createManagementHandler, isManagementRoute } from "./management-routes.
|
|
|
21
22
|
import { createOptionalRoutes, isOptionalRoute, DASHBOARD_PATHS, DASHBOARD_API_PATHS } from "./optional-routes.mjs";
|
|
22
23
|
import { createResponsesCompactHandler, createResponsesHandler } from "./responses-handler.mjs";
|
|
23
24
|
import { createResponsesImagePressureController } from "./responses-image-pressure.mjs";
|
|
24
|
-
import { createResponseFailureDiagnostics, createHttpFailureDiagnostics, buildHttpFailureDetails } from "./response-failures.mjs";
|
|
25
|
+
import { createResponseFailureDiagnostics, createHttpFailureDiagnostics, buildHttpFailureDetails, isDiscoveryRequest } from "./response-failures.mjs";
|
|
25
26
|
import { ADAPTER_CACHE_PATH } from "./cache-control.mjs";
|
|
26
27
|
import { loadRuntimeConfig, parsePositiveInteger } from "./runtime-config.mjs";
|
|
27
28
|
import {
|
|
@@ -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),
|
|
@@ -428,9 +433,9 @@ export function createAdapterHandler(options = {}) {
|
|
|
428
433
|
&& !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
|
|
429
434
|
const routeName = classifyAdapterRoute(req.method, pathname);
|
|
430
435
|
const complete = trackRequest ? requestMetrics.begin(routeName) : () => {};
|
|
431
|
-
const streamPerformance = trackRequest ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers) }) : null;
|
|
436
|
+
const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers) }) : null;
|
|
432
437
|
let finishTerminalActivity = () => {};
|
|
433
|
-
if (trackRequest && ["responses", "responses_compact", "messages", "image_mcp"].includes(routeName)) {
|
|
438
|
+
if (trackRequest && !isDiscoveryRequest(req.method, pathname) && ["responses", "responses_compact", "messages", "image_mcp"].includes(routeName)) {
|
|
434
439
|
try {
|
|
435
440
|
const finish = options.terminalActivity?.beginRequest?.();
|
|
436
441
|
if (typeof finish === "function") finishTerminalActivity = finish;
|
|
@@ -445,7 +450,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
445
450
|
try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model || context?.requestedModel,
|
|
446
451
|
method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
|
|
447
452
|
target: ["/v1/responses", "/v1/responses/compact", "/anthropic/v1/messages", "/anthropic/v1/messages/count_tokens", "/anthropic/v1/models", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
|
|
448
|
-
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts,
|
|
453
|
+
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts ?? 0,
|
|
449
454
|
attempt_timings: streamPerformance?.attemptTimings?.(),
|
|
450
455
|
requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
|
|
451
456
|
capability_cached: context?.countObservation?.cached, shared_upstream: context?.countObservation?.shared,
|
|
@@ -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
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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, ...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`, () => {
|
|
@@ -137,14 +137,16 @@ export function reconcileClaudeConfiguration(operations, { restore = false, ...o
|
|
|
137
137
|
const sharedOperation = op => op.file === paths.code && (op.keys[0] === "modelSettings" || ["CLAUDE_CODE_MAX_CONTEXT_TOKENS", "CLAUDE_CODE_MAX_OUTPUT_TOKENS", "CLAUDE_CODE_MODEL_CAPABILITIES"].includes(op.keys[1]));
|
|
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
|
-
const list = restore ? journal.operations.filter(forClient) :
|
|
140
|
+
const list = restore ? journal.operations.filter(forClient) : [
|
|
141
|
+
...journal.operations.filter(op => forClient(op) && (restoreFields.includes(op.keys.join(".")) || restoreSelect?.(op))).map(op => ({ ...op, restore: true })), ...operations];
|
|
141
142
|
for (const operation of list) {
|
|
142
143
|
if (!allowed.has(operation.file) || !safeKeys(operation)) throw new Error("Unexpected Claude configuration path");
|
|
143
144
|
if (!states.has(operation.file)) states.set(operation.file, read(operation.file));
|
|
144
145
|
const state = states.get(operation.file);state.next ||= structuredClone(state.value);
|
|
145
146
|
const previous = journal.operations.find(op => op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId);
|
|
146
|
-
const
|
|
147
|
-
|
|
147
|
+
const restoring = restore || operation.restore === true;
|
|
148
|
+
const current = operationValue(state.next, operation), desired = restoring ? operation.before : { exists: true, value: operation.value };
|
|
149
|
+
if (restoring) {
|
|
148
150
|
if (!isDeepStrictEqual(current, { exists: true, value: operation.after })) { skipped.push(operation.file);continue; }
|
|
149
151
|
setOperation(state.next, operation, desired);
|
|
150
152
|
nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
|
|
@@ -282,7 +284,8 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
282
284
|
result.app = "configured";
|
|
283
285
|
}
|
|
284
286
|
}
|
|
285
|
-
const applied = reconcileClaudeConfiguration(operations, options
|
|
287
|
+
const applied = reconcileClaudeConfiguration(operations, { ...options,
|
|
288
|
+
...(!disableExperimentalBetas && result.code === "configured" ? { restoreFields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] } : {}) });
|
|
286
289
|
if (applied.preserved) {
|
|
287
290
|
if (result.code === "configured") result.code = "partially_preserved";
|
|
288
291
|
if (result.app === "configured") result.app = "partially_preserved";
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -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:
|
|
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 (
|
|
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
|
-
|
|
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 ||
|
|
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
|
|
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
|
|
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
|
}
|
package/src/cli-management.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import { checkedApi } from "./access-settings.mjs";
|
|
|
11
11
|
import { hiddenQuestion } from "./cli-image.mjs";
|
|
12
12
|
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
13
13
|
import { deploymentModelId } from "./model-capabilities.mjs";
|
|
14
|
+
import { TERMINAL_COLOR_THEMES } from "./terminal-colors.mjs";
|
|
14
15
|
|
|
15
16
|
async function readSecretInput(input) {
|
|
16
17
|
const chunks = [];let bytes = 0;
|
|
@@ -146,8 +147,8 @@ export async function runManagementCommand(command, options = {}) {
|
|
|
146
147
|
if (typeof local.defaults[ids.key] === "boolean") { if (!["true", "false"].includes(value)) throw new Error("Use true or false for this setting.");value = value === "true"; }
|
|
147
148
|
values = { [ids.key]: value };
|
|
148
149
|
} else if (action === "terminal") {
|
|
149
|
-
const themes =
|
|
150
|
-
if (!themes.includes(pick)) throw new Error("Choose
|
|
150
|
+
const themes = TERMINAL_COLOR_THEMES, pick = (await ask(`Terminal color [${local.values.terminal_color_theme}] (${themes.join("/")}): `)).trim() || local.values.terminal_color_theme;
|
|
151
|
+
if (!themes.includes(pick)) throw new Error("Choose " + themes.join(", ") + ".");values = { terminal_color_theme: pick };
|
|
151
152
|
} else if (["reset", "restore"].includes(action)) {
|
|
152
153
|
operation = action === "reset" ? "reset_preferences" : "restore_preferences";
|
|
153
154
|
backup_id = action === "reset" ? randomUUID() : local.backup?.id;
|
|
@@ -115,7 +115,7 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
|
|
|
115
115
|
}
|
|
116
116
|
const snapshot = prediction.snapshot();
|
|
117
117
|
const status = !snapshot.configured && snapshot.bridge !== "unavailable" ? "disabled" : snapshot.bridge !== "running" ? "failed"
|
|
118
|
-
: pendingRoutePid !== null ? "needs_app_relaunch" : route === "verified" || route === "closed" ? "ready" : route === "missing" ? "needs_app_relaunch" : "route_unverified";
|
|
118
|
+
: pendingRoutePid !== null ? "needs_app_relaunch" : snapshot.client_route === "observed" || route === "verified" || route === "closed" ? "ready" : route === "missing" ? "needs_app_relaunch" : "route_unverified";
|
|
119
119
|
return { status, bridge_restarted: restarted, app_route: route, ...(routeError ? { route_error: true } : {}), prediction: snapshot };
|
|
120
120
|
}); },
|
|
121
121
|
pacUrl() { return native?.pacUrl || null; },
|
|
@@ -4,6 +4,16 @@ import { claudeDeploymentId, claudeRouteAliases } from "./clients/claude-models.
|
|
|
4
4
|
import { modelDisplayName } from "./model-display.mjs";
|
|
5
5
|
|
|
6
6
|
const endpoints = { codex: ["/responses", "/v1/responses"], claude_app: ["/v1/messages"], claude_code: ["/v1/messages"] };
|
|
7
|
+
export function clientModelExclusion({ client, binding, sourceId, sourceEnabled, model, selected }) {
|
|
8
|
+
if (!binding.enabled) return "app_disabled";
|
|
9
|
+
if (!sourceEnabled) return "source_disabled";
|
|
10
|
+
if (!binding.allowed.includes(sourceId)) return "source_not_allowed";
|
|
11
|
+
if (!model) return "model_missing";
|
|
12
|
+
if (["restricted", "hidden"].includes(model.state)) return "source_restricted";
|
|
13
|
+
const protocol = client === "codex" ? "responses" : "messages";
|
|
14
|
+
if (!model.endpoints.includes(protocol) && !(client === "codex" && sourceId === "github" && model.endpoints.includes("chat"))) return "protocol_unsupported";
|
|
15
|
+
return selected ? null : "model_not_selected";
|
|
16
|
+
}
|
|
7
17
|
export function sourceModels(source, client) {
|
|
8
18
|
if (!source) return [];
|
|
9
19
|
const models = source.models?.(client === "codex" ? "gpt" : "claude") || source.registry?.models?.data || [];
|
|
@@ -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,
|
|
@@ -28,7 +29,7 @@ import { autoReviewReasoningEfforts } from "./models.mjs";
|
|
|
28
29
|
import { createRequestAdmission } from "./request-admission.mjs";
|
|
29
30
|
import { createConversationSourceGuard } from "./conversation-source-guard.mjs";
|
|
30
31
|
import { createMessagesHistoryTransfer } from "./messages-history-transfer.mjs";
|
|
31
|
-
import { compileClientModels, sourceModels } from "./client-model-plan.mjs";
|
|
32
|
+
import { compileClientModels, sourceModels, clientModelExclusion } from "./client-model-plan.mjs";
|
|
32
33
|
import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.mjs";
|
|
33
34
|
import { currentRequestContext } from "./request-context.mjs";
|
|
34
35
|
import {
|
|
@@ -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(),
|
|
@@ -346,6 +348,7 @@ export function createConnectionRuntime({
|
|
|
346
348
|
source: item.source,
|
|
347
349
|
id: item.model,
|
|
348
350
|
route_id: deploymentModelId(item.source, item.model),
|
|
351
|
+
reason: modelExclusion(id, item.source, item.model),
|
|
349
352
|
})),
|
|
350
353
|
available: config.clients[id].allowed
|
|
351
354
|
.filter(enabled)
|
|
@@ -363,6 +366,20 @@ export function createConnectionRuntime({
|
|
|
363
366
|
},
|
|
364
367
|
};
|
|
365
368
|
}
|
|
369
|
+
function modelExclusion(id, sourceId, modelId, model, selected = false) {
|
|
370
|
+
if (!model) {
|
|
371
|
+
const source = getSource(sourceId), raw = source?.catalog?.() || source?.registry?.models?.data || [];
|
|
372
|
+
model = publicModelCatalog(raw.filter(value => value.id === modelId))[0];
|
|
373
|
+
}
|
|
374
|
+
return clientModelExclusion({ client: id, binding: binding(id), sourceId, sourceEnabled: enabled(sourceId), model, selected });
|
|
375
|
+
}
|
|
376
|
+
function catalogVisibility(catalog, sourceId) {
|
|
377
|
+
if (!catalog || !Array.isArray(catalog.models)) return catalog;
|
|
378
|
+
const selected = new Map(CLIENT_IDS.map(id => [id, new Set(plan(id).models.filter(model => model.source_id === sourceId).map(model => model.id))]));
|
|
379
|
+
return { ...catalog, models: catalog.models.map(model => ({ ...model,
|
|
380
|
+
client_visibility: CLIENT_IDS.map(id => ({ client: id,
|
|
381
|
+
reason: modelExclusion(id, sourceId, model.id, model, selected.get(id).has(model.id)) })) })) };
|
|
382
|
+
}
|
|
366
383
|
function snapshot(compact = false) {
|
|
367
384
|
const state = legacy.snapshot(),
|
|
368
385
|
config = managed ? settings : editable();
|
|
@@ -548,8 +565,6 @@ export function createConnectionRuntime({
|
|
|
548
565
|
}
|
|
549
566
|
function writeClaudeSync(id, { selected, compiled, source }, desktopManaged) {
|
|
550
567
|
const m365Only = compiled.models.every(model => model.source_id === "m365");
|
|
551
|
-
if (id === "claude_code" && !m365Only)
|
|
552
|
-
restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
|
|
553
568
|
const result = configureClaude({
|
|
554
569
|
...options,
|
|
555
570
|
client: id,
|
|
@@ -1220,7 +1235,8 @@ export function createConnectionRuntime({
|
|
|
1220
1235
|
state?.credentials || [],
|
|
1221
1236
|
settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)
|
|
1222
1237
|
),
|
|
1223
|
-
|
|
1238
|
+
privacy,
|
|
1239
|
+
busy: () => privacy.busy() ||
|
|
1224
1240
|
operations > 0 ||
|
|
1225
1241
|
active.size > 0 ||
|
|
1226
1242
|
Boolean(syncFlight) ||
|
|
@@ -1238,13 +1254,13 @@ export function createConnectionRuntime({
|
|
|
1238
1254
|
throw accessError("ccdx_connections_action_invalid");
|
|
1239
1255
|
const source = getSource(input.id),
|
|
1240
1256
|
raw = source?.catalog?.() || source?.registry?.models?.data;
|
|
1241
|
-
return {
|
|
1257
|
+
return catalogVisibility({
|
|
1242
1258
|
source: input.id,
|
|
1243
1259
|
loaded: Array.isArray(raw),
|
|
1244
1260
|
evidence: input.id.startsWith("api_") ? "configured" : "cached",
|
|
1245
1261
|
access_checked: false,
|
|
1246
1262
|
models: publicModelCatalog(raw || []).map(({ selectable, clients, ...model }) => model),
|
|
1247
|
-
};
|
|
1263
|
+
}, input.id);
|
|
1248
1264
|
}
|
|
1249
1265
|
if (validObject(input, ["operation", "id"]) && input.operation === "discover") {
|
|
1250
1266
|
const models = await catalogRefresh.refresh(input.id, true);
|
|
@@ -1455,6 +1471,8 @@ export function createConnectionRuntime({
|
|
|
1455
1471
|
provider: catalog,
|
|
1456
1472
|
acquireRequest: acquireClaudeRequest,
|
|
1457
1473
|
apiKey: identities()[id],
|
|
1474
|
+
privacy,
|
|
1475
|
+
privacyClient: id,
|
|
1458
1476
|
env,
|
|
1459
1477
|
log,
|
|
1460
1478
|
performance: legacy.claudePerformance,
|
|
@@ -1539,11 +1557,14 @@ export function createConnectionRuntime({
|
|
|
1539
1557
|
});
|
|
1540
1558
|
},
|
|
1541
1559
|
dashboardCatalog(input = {}) {
|
|
1542
|
-
if (!input.provider?.startsWith("api_"))
|
|
1560
|
+
if (!input.provider?.startsWith("api_")) {
|
|
1561
|
+
const value = legacy.dashboardCatalog(input), source = input.provider || this.selection().codex;
|
|
1562
|
+
return value?.then ? value.then(catalog => catalogVisibility(catalog, source)) : catalogVisibility(value, source);
|
|
1563
|
+
}
|
|
1543
1564
|
if (!enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
|
|
1544
|
-
return getSource(input.provider).publicCatalog(
|
|
1565
|
+
return catalogVisibility(getSource(input.provider).publicCatalog(
|
|
1545
1566
|
CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider))
|
|
1546
|
-
);
|
|
1567
|
+
), input.provider);
|
|
1547
1568
|
},
|
|
1548
1569
|
async action(input) {
|
|
1549
1570
|
if (managed && input.action === "auto-review" && Array.isArray(binding("codex").deployments)) {
|
|
@@ -1639,6 +1660,7 @@ export function createConnectionRuntime({
|
|
|
1639
1660
|
},
|
|
1640
1661
|
async close() {
|
|
1641
1662
|
closed = true;
|
|
1663
|
+
privacy.close();
|
|
1642
1664
|
await memoryModel.close();
|
|
1643
1665
|
await catalogRefresh.close();
|
|
1644
1666
|
await serial;
|