codex-copilot-dx 1.3.4 → 1.3.5
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 +2 -2
- package/docs/ARCHITECTURE.md +29 -5
- package/docs/README.md +1 -0
- package/docs/REFERENCE.md +14 -1
- package/package.json +1 -1
- package/src/adapter.mjs +4 -4
- package/src/claude-client-config.mjs +8 -5
- 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 +24 -8
- package/src/dashboard/connections.js +2 -2
- package/src/dashboard/index.html +2 -2
- package/src/dashboard/language.js +10 -0
- package/src/dashboard/status.js +1 -0
- package/src/dashboard/ui.css +7 -0
- package/src/dashboard/ui.js +5 -0
- package/src/dashboard-api.mjs +4 -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/response-failures.mjs +12 -1
- package/src/startup-ui.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 +2 -2
- package/src/native-prediction-protocol.mjs +0 -45
package/README.md
CHANGED
|
@@ -15,8 +15,8 @@ ccdx
|
|
|
15
15
|
|
|
16
16
|
Without Node.js, download and run the installer for your system:
|
|
17
17
|
|
|
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.
|
|
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
20
|
|
|
21
21
|
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
22
|
|
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,18 @@ 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.
|
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.5](RELEASE_1.3.5.md): protocol-first App checks, bounded prediction transport and incremental usage analytics.
|
|
7
8
|
- [1.3.4](RELEASE_1.3.4.md): centered Auto refresh labels at compact control heights.
|
|
8
9
|
- [1.3.3](RELEASE_1.3.3.md): live activity updates and compact WebUI spacing.
|
|
9
10
|
- [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
|
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -21,7 +21,7 @@ import { createManagementHandler, isManagementRoute } from "./management-routes.
|
|
|
21
21
|
import { createOptionalRoutes, isOptionalRoute, DASHBOARD_PATHS, DASHBOARD_API_PATHS } from "./optional-routes.mjs";
|
|
22
22
|
import { createResponsesCompactHandler, createResponsesHandler } from "./responses-handler.mjs";
|
|
23
23
|
import { createResponsesImagePressureController } from "./responses-image-pressure.mjs";
|
|
24
|
-
import { createResponseFailureDiagnostics, createHttpFailureDiagnostics, buildHttpFailureDetails } from "./response-failures.mjs";
|
|
24
|
+
import { createResponseFailureDiagnostics, createHttpFailureDiagnostics, buildHttpFailureDetails, isDiscoveryRequest } from "./response-failures.mjs";
|
|
25
25
|
import { ADAPTER_CACHE_PATH } from "./cache-control.mjs";
|
|
26
26
|
import { loadRuntimeConfig, parsePositiveInteger } from "./runtime-config.mjs";
|
|
27
27
|
import {
|
|
@@ -428,9 +428,9 @@ export function createAdapterHandler(options = {}) {
|
|
|
428
428
|
&& !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
|
|
429
429
|
const routeName = classifyAdapterRoute(req.method, pathname);
|
|
430
430
|
const complete = trackRequest ? requestMetrics.begin(routeName) : () => {};
|
|
431
|
-
const streamPerformance = trackRequest ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers) }) : null;
|
|
431
|
+
const streamPerformance = trackRequest && !isDiscoveryRequest(req.method, pathname) ? streamPerformanceMetrics.begin(routeName, { requestId, application: requestApplication(req.headers) }) : null;
|
|
432
432
|
let finishTerminalActivity = () => {};
|
|
433
|
-
if (trackRequest && ["responses", "responses_compact", "messages", "image_mcp"].includes(routeName)) {
|
|
433
|
+
if (trackRequest && !isDiscoveryRequest(req.method, pathname) && ["responses", "responses_compact", "messages", "image_mcp"].includes(routeName)) {
|
|
434
434
|
try {
|
|
435
435
|
const finish = options.terminalActivity?.beginRequest?.();
|
|
436
436
|
if (typeof finish === "function") finishTerminalActivity = finish;
|
|
@@ -445,7 +445,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
445
445
|
try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model || context?.requestedModel,
|
|
446
446
|
method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
|
|
447
447
|
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,
|
|
448
|
+
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts ?? 0,
|
|
449
449
|
attempt_timings: streamPerformance?.attemptTimings?.(),
|
|
450
450
|
requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
|
|
451
451
|
capability_cached: context?.countObservation?.cached, shared_upstream: context?.countObservation?.shared,
|
|
@@ -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 = [], ...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("."))).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/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 || [];
|
|
@@ -28,7 +28,7 @@ import { autoReviewReasoningEfforts } from "./models.mjs";
|
|
|
28
28
|
import { createRequestAdmission } from "./request-admission.mjs";
|
|
29
29
|
import { createConversationSourceGuard } from "./conversation-source-guard.mjs";
|
|
30
30
|
import { createMessagesHistoryTransfer } from "./messages-history-transfer.mjs";
|
|
31
|
-
import { compileClientModels, sourceModels } from "./client-model-plan.mjs";
|
|
31
|
+
import { compileClientModels, sourceModels, clientModelExclusion } from "./client-model-plan.mjs";
|
|
32
32
|
import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.mjs";
|
|
33
33
|
import { currentRequestContext } from "./request-context.mjs";
|
|
34
34
|
import {
|
|
@@ -346,6 +346,7 @@ export function createConnectionRuntime({
|
|
|
346
346
|
source: item.source,
|
|
347
347
|
id: item.model,
|
|
348
348
|
route_id: deploymentModelId(item.source, item.model),
|
|
349
|
+
reason: modelExclusion(id, item.source, item.model),
|
|
349
350
|
})),
|
|
350
351
|
available: config.clients[id].allowed
|
|
351
352
|
.filter(enabled)
|
|
@@ -363,6 +364,20 @@ export function createConnectionRuntime({
|
|
|
363
364
|
},
|
|
364
365
|
};
|
|
365
366
|
}
|
|
367
|
+
function modelExclusion(id, sourceId, modelId, model, selected = false) {
|
|
368
|
+
if (!model) {
|
|
369
|
+
const source = getSource(sourceId), raw = source?.catalog?.() || source?.registry?.models?.data || [];
|
|
370
|
+
model = publicModelCatalog(raw.filter(value => value.id === modelId))[0];
|
|
371
|
+
}
|
|
372
|
+
return clientModelExclusion({ client: id, binding: binding(id), sourceId, sourceEnabled: enabled(sourceId), model, selected });
|
|
373
|
+
}
|
|
374
|
+
function catalogVisibility(catalog, sourceId) {
|
|
375
|
+
if (!catalog || !Array.isArray(catalog.models)) return catalog;
|
|
376
|
+
const selected = new Map(CLIENT_IDS.map(id => [id, new Set(plan(id).models.filter(model => model.source_id === sourceId).map(model => model.id))]));
|
|
377
|
+
return { ...catalog, models: catalog.models.map(model => ({ ...model,
|
|
378
|
+
client_visibility: CLIENT_IDS.map(id => ({ client: id,
|
|
379
|
+
reason: modelExclusion(id, sourceId, model.id, model, selected.get(id).has(model.id)) })) })) };
|
|
380
|
+
}
|
|
366
381
|
function snapshot(compact = false) {
|
|
367
382
|
const state = legacy.snapshot(),
|
|
368
383
|
config = managed ? settings : editable();
|
|
@@ -548,8 +563,6 @@ export function createConnectionRuntime({
|
|
|
548
563
|
}
|
|
549
564
|
function writeClaudeSync(id, { selected, compiled, source }, desktopManaged) {
|
|
550
565
|
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
566
|
const result = configureClaude({
|
|
554
567
|
...options,
|
|
555
568
|
client: id,
|
|
@@ -1238,13 +1251,13 @@ export function createConnectionRuntime({
|
|
|
1238
1251
|
throw accessError("ccdx_connections_action_invalid");
|
|
1239
1252
|
const source = getSource(input.id),
|
|
1240
1253
|
raw = source?.catalog?.() || source?.registry?.models?.data;
|
|
1241
|
-
return {
|
|
1254
|
+
return catalogVisibility({
|
|
1242
1255
|
source: input.id,
|
|
1243
1256
|
loaded: Array.isArray(raw),
|
|
1244
1257
|
evidence: input.id.startsWith("api_") ? "configured" : "cached",
|
|
1245
1258
|
access_checked: false,
|
|
1246
1259
|
models: publicModelCatalog(raw || []).map(({ selectable, clients, ...model }) => model),
|
|
1247
|
-
};
|
|
1260
|
+
}, input.id);
|
|
1248
1261
|
}
|
|
1249
1262
|
if (validObject(input, ["operation", "id"]) && input.operation === "discover") {
|
|
1250
1263
|
const models = await catalogRefresh.refresh(input.id, true);
|
|
@@ -1539,11 +1552,14 @@ export function createConnectionRuntime({
|
|
|
1539
1552
|
});
|
|
1540
1553
|
},
|
|
1541
1554
|
dashboardCatalog(input = {}) {
|
|
1542
|
-
if (!input.provider?.startsWith("api_"))
|
|
1555
|
+
if (!input.provider?.startsWith("api_")) {
|
|
1556
|
+
const value = legacy.dashboardCatalog(input), source = input.provider || this.selection().codex;
|
|
1557
|
+
return value?.then ? value.then(catalog => catalogVisibility(catalog, source)) : catalogVisibility(value, source);
|
|
1558
|
+
}
|
|
1543
1559
|
if (!enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
|
|
1544
|
-
return getSource(input.provider).publicCatalog(
|
|
1560
|
+
return catalogVisibility(getSource(input.provider).publicCatalog(
|
|
1545
1561
|
CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider))
|
|
1546
|
-
);
|
|
1562
|
+
), input.provider);
|
|
1547
1563
|
},
|
|
1548
1564
|
async action(input) {
|
|
1549
1565
|
if (managed && input.action === "auto-review" && Array.isArray(binding("codex").deployments)) {
|
|
@@ -380,7 +380,7 @@
|
|
|
380
380
|
el("connection-client-cancel").disabled = !bindingDirty;
|
|
381
381
|
const body = el("connection-bindings"), c = client(editingClient);body.replaceChildren();
|
|
382
382
|
const available = c.model_plan?.available || [], availableKeys = new Set(available.map(item => bindingKey(item.source, item.id)));
|
|
383
|
-
const missing = [...bindingSelection].filter(key => !availableKeys.has(key)).map(key => { const [source, id] = key.split("\0")
|
|
383
|
+
const missing = [...bindingSelection].filter(key => !availableKeys.has(key)).map(key => { const [source, id] = key.split("\0"), saved = c.model_plan?.unavailable?.find(item => item.source === source && item.id === id);return { source, id, route_id: saved?.route_id, reason: saved?.reason, unavailable: true }; });
|
|
384
384
|
for (const item of [...available, ...missing]) {
|
|
385
385
|
const key = bindingKey(item.source, item.id), row = node("tr"), name = node("td"), capability = item.capability?.values || {};
|
|
386
386
|
const selection = check("binding-model", key, bindingSelection.has(key), item.display_name || item.id);
|
|
@@ -398,7 +398,7 @@
|
|
|
398
398
|
const action = button(bindingDefault === routeId(item) && bindingSelection.has(key) ? "cap_default" : "cap_set_default", () => { bindingDirty = true;bindingSelection.add(key);bindingDefault = routeId(item);rememberDraft();bindingRows({ kind: "default", key }); });
|
|
399
399
|
action.setAttribute("aria-pressed", String(bindingDefault === routeId(item) && bindingSelection.has(key)));
|
|
400
400
|
action.dataset.binding = key;action.disabled = Boolean(item.unavailable);action.setAttribute("aria-label", item.id + " · " + format(bindingDefault === routeId(item) ? "cap_default" : "cap_set_default"));
|
|
401
|
-
if (item.unavailable) { const warning = node("span", undefined, "hint binding-unavailable");words(warning, "cap_model_unavailable");name.append(warning); }
|
|
401
|
+
if (item.unavailable) { const warning = node("span", undefined, "hint binding-unavailable");words(warning, item.reason ? "visibility_" + item.reason : "cap_model_unavailable");name.append(warning); }
|
|
402
402
|
const cell = node("td");cell.append(action);
|
|
403
403
|
const details = [node("td", source(item.source)?.name || item.source), node("td", count(capability.context_window)), node("td", reasoningText(capability))];
|
|
404
404
|
details.forEach((cell, i) => cell.dataset.label = format(["source", "cap_context", "cap_reasoning"][i]));
|
package/src/dashboard/index.html
CHANGED
|
@@ -355,7 +355,7 @@
|
|
|
355
355
|
<details class="lower" id="recent-failures" open>
|
|
356
356
|
<summary class="panel-heading"><h2 data-i18n="recent_inference_http_failures">RECENT REQUEST ISSUES</h2><span id="failure-count">requests + events</span></summary>
|
|
357
357
|
<label for="failure-kind" class="sr-only" data-i18n="issue_category">Issue category</label>
|
|
358
|
-
<select id="failure-kind"><option value="issues" data-i18n="issue_replies">Reply issues</option><option value="capability" data-i18n="issue_capabilities">Capability notices</option><option value="connection" data-i18n="issue_connections">Connections and paths</option></select>
|
|
358
|
+
<select id="failure-kind"><option value="issues" data-i18n="issue_replies">Reply issues</option><option value="capability" data-i18n="issue_capabilities">Capability notices</option><option value="connection" data-i18n="issue_connections">Connections and paths</option><option value="discovery" data-i18n="issue_discovery">Service probes</option></select>
|
|
359
359
|
<ol id="failures"><li class="empty" data-i18n="reading_874bf">Reading…</li></ol>
|
|
360
360
|
</details>
|
|
361
361
|
</div>
|
|
@@ -372,7 +372,7 @@
|
|
|
372
372
|
<h2 id="terminal-appearance-title" data-i18n="terminal_appearance">终端外观</h2>
|
|
373
373
|
<div class="appearance-row">
|
|
374
374
|
<div class="appearance-label"><label for="terminal-color-theme" data-i18n="appearance_color_theme">颜色主题</label><p id="terminal-color-note" role="status" data-i18n="appearance_terminal_effect">Table updates now; startup logo next launch.</p></div>
|
|
375
|
-
<select id="terminal-color-theme" disabled class="appearance-select"><option value="green" data-i18n="appearance_classic_green">经典绿(默认)</option><option value="klein" data-i18n="appearance_klein_blue">克莱因蓝</option><option value="pink" data-i18n="appearance_soft_pink">淡粉色</option></select>
|
|
375
|
+
<select id="terminal-color-theme" disabled class="appearance-select"><option value="green" data-i18n="appearance_classic_green">经典绿(默认)</option><option value="klein" data-i18n="appearance_klein_blue">克莱因蓝</option><option value="pink" data-i18n="appearance_soft_pink">淡粉色</option><option value="mono" data-i18n="appearance_black_white">黑白</option><option value="orange" data-i18n="appearance_orange">橙色</option></select>
|
|
376
376
|
</div>
|
|
377
377
|
|
|
378
378
|
<div class="setting-row terminal-animation-toggle"><label for="setting-terminal_animation_enabled" data-i18n="terminal_animation">Terminal animation</label><input id="setting-terminal_animation_enabled" type="checkbox" role="switch" disabled><span id="effect-terminal_animation_enabled" class="hint" role="status"></span></div>
|
|
@@ -143,6 +143,16 @@
|
|
|
143
143
|
"issue_replies": ["Reply issues", "回复问题"],
|
|
144
144
|
"issue_capabilities": ["Capabilities and access", "能力与访问"],
|
|
145
145
|
"issue_connections": ["Connections and paths", "连接与路径"],
|
|
146
|
+
"issue_discovery": ["Service probes", "连接探测"],
|
|
147
|
+
"appearance_black_white": ["Black & white", "黑白"],
|
|
148
|
+
"appearance_orange": ["Orange", "橙色"],
|
|
149
|
+
"visibility_app_disabled": ["App access is off", "应用接入已关闭"],
|
|
150
|
+
"visibility_source_disabled": ["Source is off", "模型来源已关闭"],
|
|
151
|
+
"visibility_source_not_allowed": ["Source access not granted", "尚未授权此来源"],
|
|
152
|
+
"visibility_model_missing": ["Missing from source catalog", "来源目录暂未提供"],
|
|
153
|
+
"visibility_source_restricted": ["Hidden or restricted by source", "来源隐藏或限制了此模型"],
|
|
154
|
+
"visibility_protocol_unsupported": ["Required interface unavailable", "缺少应用所需接口"],
|
|
155
|
+
"visibility_model_not_selected": ["Not selected for this app", "此应用尚未选择该模型"],
|
|
146
156
|
"http_categories": ["Generation {inference} · Capabilities/access {capability} · Methods {protocol} · Paths {route} · Other {other}", "生成 {inference} · 能力/访问 {capability} · 方法 {protocol} · 路径 {route} · 其他 {other}"],
|
|
147
157
|
"no_upstream_call": ["No upstream call", "未调用上游"],
|
|
148
158
|
"repeated_issue": ["{detail} · {count} occurrences", "{detail} · 出现 {count} 次"],
|
package/src/dashboard/status.js
CHANGED
|
@@ -306,6 +306,7 @@
|
|
|
306
306
|
issues: [...(data.response_failures?.recent || []), ...(data.http_errors?.actionable_recent || data.http_errors?.recent || [])],
|
|
307
307
|
capability: data.http_errors?.capability_recent || [],
|
|
308
308
|
connection: [...(data.http_errors?.protocol_recent || []), ...(data.http_errors?.route_recent || [])],
|
|
309
|
+
discovery: data.http_errors?.discovery_recent || [],
|
|
309
310
|
};
|
|
310
311
|
for (const rows of Object.values(issueGroups)) rows.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));
|
|
311
312
|
issueRequests = recentRequests;
|
package/src/dashboard/ui.css
CHANGED
|
@@ -422,6 +422,13 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
422
422
|
--bad:#000; --failed:#000; --incomplete:#000;
|
|
423
423
|
}
|
|
424
424
|
.terminal-sample[data-terminal-palette="pink"] { --sample-logo:#f3a8c8; --sample-table:#f3a8c8; --sample-motion:#f3a8c8; }
|
|
425
|
+
.terminal-sample[data-terminal-palette="orange"] { --sample-logo:#ff9a3d; --sample-table:#ff9a3d; --sample-motion:#ff9a3d; }
|
|
426
|
+
.terminal-sample[data-terminal-palette="mono"] { --sample-bg:#000; --sample-text:#fff; --sample-muted:#aaa; --sample-line:#777; --sample-logo:#fff; --sample-table:#fff; --sample-motion:#fff; }
|
|
427
|
+
:root[data-theme="light"] .terminal-sample[data-terminal-palette="mono"] { --sample-bg:#fff; --sample-text:#000; --sample-muted:#555; --sample-logo:#000; --sample-table:#000; --sample-motion:#000; }
|
|
428
|
+
:root:not([data-theme="light"]) #animation-settings[data-terminal-palette="orange"] { --ansi-white:#ff9a3d;--ansi-159:#ff9a3d;--ansi-123:#ff9a3d;--ansi-87:#ff9a3d;--ansi-51:#ff9a3d;--ansi-45:#ff9a3d;--ansi-39:#ff9a3d;--ansi-33:#ff9a3d; }
|
|
429
|
+
:root[data-theme="light"] #animation-settings[data-terminal-palette="orange"] { --ansi-white:#ad4d00;--ansi-159:#ad4d00;--ansi-123:#ad4d00;--ansi-87:#ad4d00;--ansi-51:#ad4d00;--ansi-45:#ad4d00;--ansi-39:#ad4d00;--ansi-33:#ad4d00; }
|
|
430
|
+
:root:not([data-theme="light"]) #animation-settings[data-terminal-palette="mono"] { --ansi-white:#fff;--ansi-159:#fff;--ansi-123:#fff;--ansi-87:#fff;--ansi-51:#fff;--ansi-45:#fff;--ansi-39:#fff;--ansi-33:#fff; }
|
|
431
|
+
:root[data-theme="light"] #animation-settings[data-terminal-palette="mono"] { --ansi-white:#000;--ansi-159:#000;--ansi-123:#000;--ansi-87:#000;--ansi-51:#000;--ansi-45:#000;--ansi-39:#000;--ansi-33:#000; }
|
|
425
432
|
:root:not([data-theme="light"]) #animation-settings[data-terminal-palette="pink"] { --ansi-white:#f3a8c8;--ansi-159:#f3a8c8;--ansi-123:#f3a8c8;--ansi-87:#f3a8c8;--ansi-51:#f3a8c8;--ansi-45:#f3a8c8;--ansi-39:#f3a8c8;--ansi-33:#f3a8c8; }
|
|
426
433
|
:root[data-theme="light"] #animation-settings[data-terminal-palette="pink"] { --ansi-white:#a83e68;--ansi-159:#a83e68;--ansi-123:#a83e68;--ansi-87:#a83e68;--ansi-51:#a83e68;--ansi-45:#a83e68;--ansi-39:#a83e68;--ansi-33:#a83e68; }
|
|
427
434
|
|
package/src/dashboard/ui.js
CHANGED
|
@@ -215,6 +215,11 @@ function applyModels(data, { changed }) {
|
|
|
215
215
|
if (translated) localize(detail, value);else detail.textContent = value;
|
|
216
216
|
fields.append(term, detail);
|
|
217
217
|
}
|
|
218
|
+
for (const item of model.client_visibility || []) if (item.reason) {
|
|
219
|
+
const term = document.createElement("dt"), detail = document.createElement("dd");
|
|
220
|
+
term.textContent = ({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" })[item.client] || item.client;
|
|
221
|
+
localize(detail, "visibility_" + item.reason);fields.append(term, detail);
|
|
222
|
+
}
|
|
218
223
|
row.children[2].append(details);body.append(row);
|
|
219
224
|
}
|
|
220
225
|
if (!data.models.length) emptyTable("live-models-body", 3, "no_models_advertised");
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -324,6 +324,10 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
324
324
|
preview: model.preview === true,
|
|
325
325
|
selectable: model.selectable !== false,
|
|
326
326
|
clients: Array.isArray(model.clients) ? model.clients.filter(value => typeof value === "string").slice(0, 8).map(value => safeText(value, 40)) : [],
|
|
327
|
+
client_visibility: Array.isArray(model.client_visibility) ? model.client_visibility.slice(0, 3)
|
|
328
|
+
.filter(value => ["codex", "claude_app", "claude_code"].includes(value?.client) && (value.reason === null
|
|
329
|
+
|| ["app_disabled", "source_disabled", "source_not_allowed", "model_missing", "source_restricted", "protocol_unsupported", "model_not_selected"].includes(value.reason)))
|
|
330
|
+
.map(({ client, reason }) => ({ client, reason })) : [],
|
|
327
331
|
auto_review_efforts: Array.isArray(model.auto_review_efforts) ? model.auto_review_efforts.slice(0, 16).map(value => safeText(value, 16)) : [],
|
|
328
332
|
reasoning_efforts: Array.isArray(model.reasoning_efforts) ? model.reasoning_efforts.slice(0, 16).map(value => safeText(value, 16)) : null,
|
|
329
333
|
state: ["listed", "restricted", "hidden"].includes(model.state) ? model.state : "listed",
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { installedWindowsPredictionAppAsync, windowsPredictionProfile } from "./native-prediction-windows.mjs";
|
|
6
|
+
|
|
7
|
+
const execute = promisify(execFile);
|
|
8
|
+
const checks = new WeakMap();
|
|
9
|
+
const stat = file => {
|
|
10
|
+
const value = fs.statSync(file);
|
|
11
|
+
if (!value.isFile()) throw new Error("App identity is not a regular file");
|
|
12
|
+
return { size: value.size, mtimeMs: value.mtimeMs };
|
|
13
|
+
};
|
|
14
|
+
const matches = (file, size, mtimeMs) => {
|
|
15
|
+
const value = stat(file);
|
|
16
|
+
return value.size === size && value.mtimeMs === mtimeMs;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// Installation identity is independent of renderer chunks and prediction
|
|
20
|
+
// implementation strings. Live responses decide whether an overlay applies.
|
|
21
|
+
export async function installedPredictionApp({ exec = execute, platform = process.platform, ...options } = {}) {
|
|
22
|
+
if (platform === "win32") {
|
|
23
|
+
const app = await installedWindowsPredictionAppAsync({ ...options, exec });
|
|
24
|
+
const identity = stat(app.app);
|
|
25
|
+
return { ...app, identity_version: 2, executable: app.app, ...identity,
|
|
26
|
+
profile: windowsPredictionProfile({ app, env: options.env, preferredProfile: options.preferredProfile }) };
|
|
27
|
+
}
|
|
28
|
+
if (platform !== "darwin") throw new Error("Prediction App discovery supports macOS and Windows only");
|
|
29
|
+
for (const app of ["/Applications/ChatGPT.app", "/Applications/Codex.app"]) {
|
|
30
|
+
const metadata = path.join(app, "Contents", "Info.plist");
|
|
31
|
+
if (!fs.existsSync(metadata)) continue;
|
|
32
|
+
const info = stat(metadata);
|
|
33
|
+
const result = await exec("/usr/bin/plutil", ["-convert", "json", "-o", "-", metadata],
|
|
34
|
+
{ encoding: "utf8", timeout: 3000, maxBuffer: 64 * 1024 });
|
|
35
|
+
const parsed = JSON.parse(String(result?.stdout ?? result));
|
|
36
|
+
if (parsed?.CFBundleIdentifier !== "com.openai.codex" || !["ChatGPT", "Codex"].includes(parsed.CFBundleExecutable)) {
|
|
37
|
+
throw new Error("Unknown Codex App identity; prediction setup was preserved");
|
|
38
|
+
}
|
|
39
|
+
const executable = path.join(app, "Contents", "MacOS", parsed.CFBundleExecutable), identity = stat(executable);
|
|
40
|
+
const key = JSON.stringify([app, info, identity]);
|
|
41
|
+
let cache = checks.get(exec);
|
|
42
|
+
if (!cache) { cache = new Map();checks.set(exec, cache); }
|
|
43
|
+
if (!cache.has(key)) {
|
|
44
|
+
while (cache.size >= 2) cache.delete(cache.keys().next().value);
|
|
45
|
+
const pending = (async () => {
|
|
46
|
+
await exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", "-R", '=identifier "com.openai.codex" and anchor apple generic and certificate leaf[subject.OU] = "2DC432GLL2"', app],
|
|
47
|
+
{ encoding: "utf8", timeout: 15_000, maxBuffer: 64 * 1024 });
|
|
48
|
+
if (!matches(metadata, info.size, info.mtimeMs) || !matches(executable, identity.size, identity.mtimeMs)) {
|
|
49
|
+
throw new Error("Codex App changed during identity verification");
|
|
50
|
+
}
|
|
51
|
+
return { app, identity_version: 2, executable, ...identity, metadata,
|
|
52
|
+
metadataSize: info.size, metadataMtimeMs: info.mtimeMs };
|
|
53
|
+
})();
|
|
54
|
+
cache.set(key, pending);
|
|
55
|
+
pending.catch(() => { if (cache.get(key) === pending) cache.delete(key); });
|
|
56
|
+
}
|
|
57
|
+
return { ...await cache.get(key) };
|
|
58
|
+
}
|
|
59
|
+
throw new Error("A registered Codex App was not found; prediction setup was preserved");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function predictionAppMatches(app) {
|
|
63
|
+
try {
|
|
64
|
+
return app?.identity_version === 2 && matches(app.executable, app.size, app.mtimeMs)
|
|
65
|
+
&& (!app.metadata || matches(app.metadata, app.metadataSize, app.metadataMtimeMs));
|
|
66
|
+
} catch { return false; }
|
|
67
|
+
}
|
|
@@ -22,6 +22,6 @@ export async function requestPredictionFix({ host = "127.0.0.1", port = 2026, fe
|
|
|
22
22
|
|| !["running", "stopped", "unavailable", "recovering"].includes(value?.prediction?.bridge)
|
|
23
23
|
|| value.prediction.candidate !== "unknown"
|
|
24
24
|
|| (["ready", "needs_app_relaunch", "route_unverified"].includes(value.status) && value.prediction.bridge !== "running")
|
|
25
|
-
|| (value.status === "ready" && !["verified", "closed"].includes(value.app_route))) throw new Error("Adapter returned an invalid prediction repair result");
|
|
25
|
+
|| (value.status === "ready" && !["verified", "closed"].includes(value.app_route) && value.prediction.client_route !== "observed")) throw new Error("Adapter returned an invalid prediction repair result");
|
|
26
26
|
return value;
|
|
27
27
|
}
|
|
@@ -8,10 +8,9 @@ import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
|
8
8
|
import { userSettingsPath } from "./user-settings.mjs";
|
|
9
9
|
import { resolveNetworkRoute } from "./network-route.mjs";
|
|
10
10
|
import { codexPaths } from "./codex-paths.mjs";
|
|
11
|
-
import { assertWindowsCodexClosed,
|
|
12
|
-
windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
|
|
11
|
+
import { assertWindowsCodexClosed, windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
|
|
13
12
|
import { windowsPredictionCertificate } from "./windows-prediction-certificate.mjs";
|
|
14
|
-
|
|
13
|
+
export { installedPredictionApp, predictionAppMatches } from "./native-prediction-app.mjs";
|
|
15
14
|
|
|
16
15
|
export function predictionPaths({ env = process.env, home = os.homedir(), platform = process.platform, app } = {}) {
|
|
17
16
|
const directory = path.join(path.dirname(userSettingsPath({ env, home })), "native-prediction");
|
|
@@ -59,39 +58,6 @@ export function assertCodexClosed({ exec = execFileSync, platform = process.plat
|
|
|
59
58
|
}
|
|
60
59
|
}
|
|
61
60
|
|
|
62
|
-
export function installedPredictionApp({ exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
63
|
-
const candidates = platform === "win32" ? [installedWindowsPredictionApp({ ...options, exec })]
|
|
64
|
-
: ["/Applications/ChatGPT.app", "/Applications/Codex.app"].map(app => ({ app, archive: path.join(app, "Contents", "Resources", "app.asar") }));
|
|
65
|
-
for (const candidate of candidates) {
|
|
66
|
-
const { app, archive } = candidate;
|
|
67
|
-
if (!fs.existsSync(archive)) continue;
|
|
68
|
-
const inspected = inspectPredictionArchive(archive);
|
|
69
|
-
if (!inspected.compatible) continue;
|
|
70
|
-
if (platform !== "win32") exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
|
|
71
|
-
const stat = fs.statSync(archive);
|
|
72
|
-
if (stat.size !== inspected.size || stat.mtimeMs !== inspected.mtimeMs) throw new Error("Codex App changed during compatibility verification");
|
|
73
|
-
if (platform === "win32") {
|
|
74
|
-
const executable = fs.statSync(app);
|
|
75
|
-
return { ...candidate, profile: windowsPredictionProfile({ app: candidate, env: options.env, preferredProfile: options.preferredProfile }),
|
|
76
|
-
size: stat.size, mtimeMs: stat.mtimeMs, executableSize: executable.size, executableMtimeMs: executable.mtimeMs };
|
|
77
|
-
}
|
|
78
|
-
return { app, archive, size: stat.size, mtimeMs: stat.mtimeMs };
|
|
79
|
-
}
|
|
80
|
-
throw new Error("This Codex App does not expose the verified native prediction protocol; setup was skipped");
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function predictionAppMatches(app) {
|
|
84
|
-
try {
|
|
85
|
-
const stat = fs.statSync(app.archive);
|
|
86
|
-
if (app.executableSize !== undefined) {
|
|
87
|
-
const executable = fs.statSync(app.app);
|
|
88
|
-
if (executable.size !== app.executableSize || executable.mtimeMs !== app.executableMtimeMs) return false;
|
|
89
|
-
}
|
|
90
|
-
return stat.size === app.size && stat.mtimeMs === app.mtimeMs;
|
|
91
|
-
}
|
|
92
|
-
catch { return false; }
|
|
93
|
-
}
|
|
94
|
-
|
|
95
61
|
function privateDirectory(directory, { platform = process.platform, ...options } = {}) {
|
|
96
62
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
97
63
|
const stat = fs.lstatSync(directory);
|
|
@@ -34,7 +34,10 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
|
|
|
34
34
|
state.configuration[event.route] = { status: event.status, modified: event.changed === true, official: event.official === true };
|
|
35
35
|
} else if (event.type === "tls_error") state.counters.tls_errors++;
|
|
36
36
|
else if (event.type === "upstream_error") state.counters.upstream_errors++;
|
|
37
|
-
if (event.error) state.last_error = { code: event.error.code, source: event.error.source, message: event.error.message, status: event.error.status
|
|
37
|
+
if (event.error) state.last_error = { code: event.error.code, source: event.error.source, message: event.error.message, status: event.error.status,
|
|
38
|
+
...(["request_headers", "response_headers", "response_body", "upstream_request"].includes(event.phase) ? { phase: event.phase } : {}),
|
|
39
|
+
...(["bootstrap", "prediction", "refresh", "passthrough", "upgrade"].includes(event.target) ? { target: event.target } : {}),
|
|
40
|
+
...(event.header_limit === 65536 ? { header_limit: event.header_limit } : {}) };
|
|
38
41
|
},
|
|
39
42
|
snapshot() { return structuredClone(state); },
|
|
40
43
|
};
|
|
@@ -9,6 +9,7 @@ import { PREDICTION_PAC_PATH, predictionProxyExpression } from "./prediction-pac
|
|
|
9
9
|
export const PREDICTION_HOSTS = Object.freeze(["chatgpt.com", "ab.chatgpt.com"]);
|
|
10
10
|
const CONFIG_LIMIT = 16 * 1024 * 1024;
|
|
11
11
|
const REQUEST_LIMIT = 512 * 1024;
|
|
12
|
+
export const PREDICTION_HEADER_LIMIT = 64 * 1024;
|
|
12
13
|
const decoders = { gzip: promisify(gunzip), deflate: promisify(inflate), br: promisify(brotliDecompress) };
|
|
13
14
|
|
|
14
15
|
export function predictionRoute(host, pathname) {
|
|
@@ -67,7 +68,7 @@ export async function startPredictionTransport({
|
|
|
67
68
|
const upstreams = new Set();
|
|
68
69
|
let closing = false;
|
|
69
70
|
let listenerError = false;
|
|
70
|
-
const gateway = https.createServer({ key, cert, minVersion: "TLSv1.2" }, (req, res) => {
|
|
71
|
+
const gateway = https.createServer({ key, cert, minVersion: "TLSv1.2", maxHeaderSize: PREDICTION_HEADER_LIMIT }, (req, res) => {
|
|
71
72
|
let target;
|
|
72
73
|
try {
|
|
73
74
|
target = new URL(req.url, `https://${req.headers.host}`);
|
|
@@ -82,8 +83,9 @@ export async function startPredictionTransport({
|
|
|
82
83
|
// No decoding/re-encoding on pass-through paths.
|
|
83
84
|
if (route && enabled()) headers["accept-encoding"] = "identity";
|
|
84
85
|
let upstream;
|
|
85
|
-
const fail = (error) => {
|
|
86
|
-
onEvent({ type: "upstream_error", error: operationErrorDetails(error)
|
|
86
|
+
const fail = (error, phase = error?.code === "HPE_HEADER_OVERFLOW" ? "response_headers" : "upstream_request") => {
|
|
87
|
+
onEvent({ type: "upstream_error", error: operationErrorDetails(error), phase,
|
|
88
|
+
target: route || "passthrough", host: target.hostname, header_limit: PREDICTION_HEADER_LIMIT });
|
|
87
89
|
if (!res.headersSent) { res.writeHead(502); res.end(); } else res.destroy();
|
|
88
90
|
};
|
|
89
91
|
const send = (body, streamRemainder = false) => {
|
|
@@ -93,13 +95,14 @@ export async function startPredictionTransport({
|
|
|
93
95
|
servername: target.hostname, method: req.method,
|
|
94
96
|
path: req.url, headers,
|
|
95
97
|
rejectUnauthorized: true,
|
|
98
|
+
maxHeaderSize: PREDICTION_HEADER_LIMIT,
|
|
96
99
|
...(agent ? { agent } : {}),
|
|
97
100
|
}, (reply) => {
|
|
98
101
|
const pass = () => {
|
|
99
102
|
res.writeHead(reply.statusCode, cleanHeaders(reply.headers));
|
|
100
103
|
reply.pipe(res);
|
|
101
104
|
};
|
|
102
|
-
reply.on("error", fail);
|
|
105
|
+
reply.on("error", error => fail(error, "response_body"));
|
|
103
106
|
// Error and non-JSON responses are forwarded as received. The overlay
|
|
104
107
|
// decides whether the narrowly allowed missing-config response applies.
|
|
105
108
|
const mediaType = String(reply.headers["content-type"] || "").split(";", 1)[0].trim();
|
|
@@ -192,11 +195,17 @@ export async function startPredictionTransport({
|
|
|
192
195
|
const upstream = requestImpl({
|
|
193
196
|
protocol: "https:", hostname: host, port: 443, servername: host,
|
|
194
197
|
method: req.method, path: req.url, rejectUnauthorized: true,
|
|
198
|
+
maxHeaderSize: PREDICTION_HEADER_LIMIT,
|
|
195
199
|
...(agent ? { agent } : {}),
|
|
196
200
|
headers: { ...cleanHeaders(req.headers), connection: "Upgrade", upgrade: req.headers.upgrade },
|
|
197
201
|
});
|
|
198
202
|
upstreams.add(upstream);
|
|
199
|
-
upstream.on("error",
|
|
203
|
+
upstream.on("error", error => {
|
|
204
|
+
onEvent({ type: "upstream_error", error: operationErrorDetails(error),
|
|
205
|
+
phase: error.code === "HPE_HEADER_OVERFLOW" ? "response_headers" : "upstream_request",
|
|
206
|
+
target: "upgrade", host, header_limit: PREDICTION_HEADER_LIMIT });
|
|
207
|
+
socket.destroy();
|
|
208
|
+
});
|
|
200
209
|
upstream.on("response", (reply) => {
|
|
201
210
|
const headers = Object.entries(cleanHeaders(reply.headers)).flatMap(([name, values]) =>
|
|
202
211
|
(Array.isArray(values) ? values : [values]).map((value) => `${name}: ${value}`));
|
|
@@ -219,8 +228,13 @@ export async function startPredictionTransport({
|
|
|
219
228
|
upstream.end();
|
|
220
229
|
});
|
|
221
230
|
gateway.on("tlsClientError", (error, socket) => { onEvent({ type: "tls_error", error: operationErrorDetails(error) }); socket.destroy(); });
|
|
222
|
-
gateway.on("clientError", (
|
|
223
|
-
|
|
231
|
+
gateway.on("clientError", (error, socket) => {
|
|
232
|
+
if (socket.destroyed || socket.writableEnded) return;
|
|
233
|
+
onEvent({ type: "client_error", error: operationErrorDetails(error), phase: "request_headers", header_limit: PREDICTION_HEADER_LIMIT });
|
|
234
|
+
if (error.code === "HPE_HEADER_OVERFLOW" && socket.writable) socket.end("HTTP/1.1 431 Request Header Fields Too Large\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
235
|
+
else socket.destroy();
|
|
236
|
+
});
|
|
237
|
+
const proxy = http.createServer({ maxHeaderSize: PREDICTION_HEADER_LIMIT }, (req, res) => {
|
|
224
238
|
if (req.method === "GET" && ["/proxy.pac", PREDICTION_PAC_PATH].includes(req.url) && !req.headers.origin
|
|
225
239
|
&& ["127.0.0.1", "localhost"].includes(String(req.headers.host || "").split(":")[0])) {
|
|
226
240
|
res.writeHead(200, { "Content-Type": "application/x-ns-proxy-autoconfig", "Cache-Control": "no-store" });
|
|
@@ -1,17 +1,23 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
4
5
|
import { windowsPowerShellEnvironment } from "./windows-process.mjs";
|
|
5
6
|
export { windowsPowerShellEnvironment } from "./windows-process.mjs";
|
|
6
7
|
|
|
7
8
|
const WINDOWS_PUBLISHER = "CN=50BDFD77-8903-4850-9FFE-6E8522F64D5B";
|
|
8
9
|
const WINDOWS_PACKAGE_FAMILY = "OpenAI.Codex_2p2nqsd0c76g0";
|
|
10
|
+
const execFileAsync = promisify(execFile);
|
|
11
|
+
|
|
12
|
+
function powershellCommand(script, env) {
|
|
13
|
+
return [path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
|
|
14
|
+
["-NoProfile", "-NonInteractive", "-Command", "$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false);" + script]];
|
|
15
|
+
}
|
|
9
16
|
|
|
10
17
|
function powershell(script, { env = process.env, exec = execFileSync, ...options } = {}) {
|
|
11
|
-
const command =
|
|
18
|
+
const [command, args] = powershellCommand(script, env);
|
|
12
19
|
try {
|
|
13
|
-
return exec(command,
|
|
14
|
-
"$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false);" + script],
|
|
20
|
+
return exec(command, args,
|
|
15
21
|
{ encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024, env: windowsPowerShellEnvironment(env), windowsHide: true, ...options }).trim();
|
|
16
22
|
} catch {
|
|
17
23
|
throw new Error("Windows prediction check failed; verify PowerShell, App registration and current-user permissions");
|
|
@@ -44,13 +50,14 @@ export function windowsPredictionAppProcesses(app, { env = process.env, ...optio
|
|
|
44
50
|
return rows;
|
|
45
51
|
}
|
|
46
52
|
|
|
47
|
-
|
|
48
|
-
const raw = powershell(`$p=@(Get-AppxPackage -Name OpenAI.Codex | Where-Object { [int]$_.Status -eq 0 -and [int]$_.SignatureKind -eq 3 -and $_.Publisher -eq '${WINDOWS_PUBLISHER}' -and $_.PackageFamilyName -eq '${WINDOWS_PACKAGE_FAMILY}' });
|
|
53
|
+
const WINDOWS_APP_SCRIPT = `$p=@(Get-AppxPackage -Name OpenAI.Codex | Where-Object { [int]$_.Status -eq 0 -and [int]$_.SignatureKind -eq 3 -and $_.Publisher -eq '${WINDOWS_PUBLISHER}' -and $_.PackageFamilyName -eq '${WINDOWS_PACKAGE_FAMILY}' });
|
|
49
54
|
if($p.Count -ne 1){throw 'A single official OpenAI.Codex MSIX registration is required'};
|
|
50
55
|
$m=Get-AppxPackageManifest -Package ([string]$p[0].PackageFullName);
|
|
51
56
|
$a=@($m.Package.Applications.Application | Where-Object { [System.IO.Path]::GetFileName($_.Executable) -in @('Codex.exe','ChatGPT.exe') });
|
|
52
57
|
if($a.Count -ne 1){throw 'Unknown Windows App executable'};
|
|
53
|
-
@{root=$p[0].InstallLocation;executable=$a[0].Executable;family=$p[0].PackageFamilyName} | ConvertTo-Json -Compress
|
|
58
|
+
@{root=$p[0].InstallLocation;executable=$a[0].Executable;family=$p[0].PackageFamilyName} | ConvertTo-Json -Compress`;
|
|
59
|
+
|
|
60
|
+
function registeredApp(raw) {
|
|
54
61
|
let metadata;
|
|
55
62
|
try { metadata = JSON.parse(raw); } catch { throw new Error("Could not read the registered Windows Codex App"); }
|
|
56
63
|
const { root, executable, family } = metadata;
|
|
@@ -61,10 +68,20 @@ export function installedWindowsPredictionApp(options = {}) {
|
|
|
61
68
|
throw new Error("Unknown Windows App registration; prediction setup was skipped");
|
|
62
69
|
}
|
|
63
70
|
const app = path.win32.join(root, executable);
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
71
|
+
return { app, family };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function installedWindowsPredictionApp(options = {}) {
|
|
75
|
+
return registeredApp(powershell(WINDOWS_APP_SCRIPT, options));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function installedWindowsPredictionAppAsync({ env = process.env, exec = execFileAsync } = {}) {
|
|
79
|
+
const [command, args] = powershellCommand(WINDOWS_APP_SCRIPT, env);
|
|
80
|
+
let result;
|
|
81
|
+
try { result = await exec(command, args, { encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024,
|
|
82
|
+
env: windowsPowerShellEnvironment(env), windowsHide: true }); }
|
|
83
|
+
catch { throw new Error("Windows prediction check failed; verify PowerShell, App registration and current-user permissions"); }
|
|
84
|
+
return registeredApp(String(result?.stdout ?? result).trim());
|
|
68
85
|
}
|
|
69
86
|
|
|
70
87
|
export function windowsPredictionProfile({ app, env = process.env, preferredProfile } = {}) {
|
|
@@ -48,6 +48,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
48
48
|
else if (result.status === "environment_preserved") output(`Network recheck failed; the existing bridge and routes were preserved. ${result.environment_error?.message || "Check ccdx app codex prediction status."}`);
|
|
49
49
|
else if (prediction.bridge !== "running") output(prediction.reason || "Prediction bridge is unavailable; core service was not changed.");
|
|
50
50
|
else if (prediction.environment?.status === "needs_app_relaunch") output("Network settings changed. The bridge uses the new snapshot, but the App may cache its earlier PAC. Fully quit Codex, then run ccdx; no App was restarted.");
|
|
51
|
+
else if (prediction.client_route === "observed") output("Prediction configuration traffic observed. Visible suggestions still need an App-side check.");
|
|
51
52
|
else if (result.app_route === "verified") output("App launch route verified. A visible suggestion still needs an App-side check.");
|
|
52
53
|
else if (result.app_route === "closed") output("Bridge is ready. Run ccdx to open Codex with its prediction route.");
|
|
53
54
|
else if (result.status === "route_unverified") output("Bridge is ready, but App route inspection was unavailable or ambiguous. Check ccdx app codex prediction status; no App was restarted.");
|
|
@@ -105,7 +106,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
105
106
|
}
|
|
106
107
|
assertCodexClosed(opts);
|
|
107
108
|
inspectPredictionEnvironment(opts);
|
|
108
|
-
const app = resolveApp({ ...opts, ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
|
|
109
|
+
const app = await resolveApp({ ...opts, ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
|
|
109
110
|
paths = predictionPaths({ ...opts, app });
|
|
110
111
|
if (settings.store && settings.store !== paths.store) throw new Error("Codex profile changed; disable the previous profile before enabling another");
|
|
111
112
|
let certificate, previous, generated = false;
|
|
@@ -168,9 +169,10 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
168
169
|
}
|
|
169
170
|
if (options.expectedPort !== undefined && settings.bridgePort !== options.expectedPort) throw new Error("Prediction route changed; automatic recovery was skipped");
|
|
170
171
|
if (!predictionAppMatches(settings.app)) {
|
|
171
|
-
const current = (options.resolveApp || installedPredictionApp)({ ...opts,
|
|
172
|
+
const current = await (options.resolveApp || installedPredictionApp)({ ...opts,
|
|
172
173
|
...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
|
|
173
|
-
|
|
174
|
+
const sameApp = current.app === settings.app?.app || platform === "win32" && current.family && current.family === settings.app?.family;
|
|
175
|
+
if (!sameApp || (platform === "win32" && current.profile !== settings.app?.profile)) {
|
|
174
176
|
throw new Error("Codex App identity/profile changed; run ccdx app codex prediction setup after quitting it to recheck compatibility");
|
|
175
177
|
}
|
|
176
178
|
const settingsFile = predictionPaths(opts).settings;
|
|
@@ -138,9 +138,13 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
138
138
|
const protocol = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
139
139
|
const capability = createResponseFailureDiagnostics({ maxEntries: 20, now });
|
|
140
140
|
const routes = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
141
|
+
const discovery = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
141
142
|
const counts = { inference: 0, capability: 0, protocol: 0, route: 0, other: 0 };
|
|
142
143
|
return {
|
|
143
144
|
record(details) {
|
|
145
|
+
const probe = isDiscoveryRequest(details.method, details.target) && [404, 405].includes(details.http_status)
|
|
146
|
+
&& details.upstream_attempts === 0;
|
|
147
|
+
if (probe) details = { ...details, request_kind: "discovery" };
|
|
144
148
|
all.record(details);
|
|
145
149
|
const accessNotice = details.reason === "ccdx_model_not_selected" || details.reason === "ccdx_client_source_disabled";
|
|
146
150
|
const category = accessNotice || details.route === "messages_count_tokens" ? "capability"
|
|
@@ -148,6 +152,7 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
148
152
|
: details.route === "image_mcp" && details.http_status === 405 ? "protocol"
|
|
149
153
|
: details.route === "not_found" ? "route" : "other";
|
|
150
154
|
counts[category]++;
|
|
155
|
+
if (probe) { discovery.record(details);return; }
|
|
151
156
|
if ((category === "inference" || category === "other") && !accessNotice) actionable.record(details);
|
|
152
157
|
if (category === "capability") {
|
|
153
158
|
capability.record(details);
|
|
@@ -158,10 +163,16 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
158
163
|
},
|
|
159
164
|
snapshot() { return { ...all.snapshot(), by_category: { ...counts },
|
|
160
165
|
actionable_recent: actionable.snapshot().recent, capability_recent: capability.snapshot().recent,
|
|
161
|
-
protocol_recent: protocol.snapshot().recent, route_recent: routes.snapshot().recent
|
|
166
|
+
protocol_recent: protocol.snapshot().recent, route_recent: routes.snapshot().recent,
|
|
167
|
+
discovery_total: discovery.snapshot().total, discovery_recent: discovery.snapshot().recent }; },
|
|
162
168
|
};
|
|
163
169
|
}
|
|
164
170
|
|
|
171
|
+
export function isDiscoveryRequest(method, pathname) {
|
|
172
|
+
return ["GET", "HEAD"].includes(method) && ["/mcp/image", "/.well-known/oauth-authorization-server",
|
|
173
|
+
"/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname);
|
|
174
|
+
}
|
|
175
|
+
|
|
165
176
|
export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers, model_error,
|
|
166
177
|
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
167
178
|
application, reason, capability_cached, shared_upstream, transport }) {
|
package/src/startup-ui.mjs
CHANGED
|
@@ -82,7 +82,7 @@ export function predictionStartupCheck(prediction) {
|
|
|
82
82
|
: prediction.active === false ? "Paused; trust and route retained"
|
|
83
83
|
: "Running; suggestion display not verified";
|
|
84
84
|
if (problem) detail += environment === "needs_service_restart" ? "; restart CCDX" : environment === "needs_app_relaunch" ? "; relaunch Codex" : "; environment unavailable";
|
|
85
|
-
const warning = prediction.bridge !== "running" || problem || prediction.launch_route === "unverified";
|
|
85
|
+
const warning = prediction.bridge !== "running" || problem || prediction.launch_route === "unverified" && prediction.client_route !== "observed";
|
|
86
86
|
const lines = [startupCheck(warning ? "warn" : "info", "Suggestions", detail)];
|
|
87
87
|
if (prediction.bridge !== "running" && prediction.reason) lines.push(startupCheck("warn", "Reason", prediction.reason));
|
|
88
88
|
if (warning) lines.push(startupCheck("info", "Details", "ccdx app codex prediction status"));
|
package/src/terminal-colors.mjs
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
export const
|
|
1
|
+
export const TERMINAL_COLOR_THEMES = Object.freeze(["green", "klein", "pink", "mono", "orange"]);
|
|
2
|
+
export const isColorTheme = value => TERMINAL_COLOR_THEMES.includes(value);
|
|
2
3
|
|
|
3
4
|
export function terminalColorCode(theme, { output = process.stdout, env = process.env } = {}) {
|
|
4
5
|
if (output.isTTY !== true || Object.hasOwn(env, "NO_COLOR") || env.TERM === "dumb") return "";
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
if (theme === "mono") return "\x1b[39m";
|
|
7
|
+
// Preserve the original green exactly. Other colors adapt to terminal depth.
|
|
8
|
+
if (theme !== "klein" && theme !== "pink" && theme !== "orange") return "\x1b[38;2;166;245;168m";
|
|
7
9
|
const depth = output.getColorDepth?.(env) || (/truecolor|24bit/i.test(env.COLORTERM || "") ? 24 : 4);
|
|
10
|
+
const light = /^(7|15)$/.test(String(env.COLORFGBG || "").split(";").at(-1));
|
|
11
|
+
if (theme === "orange") return depth >= 24 ? light ? "\x1b[38;2;173;77;0m" : "\x1b[38;2;255;154;61m"
|
|
12
|
+
: depth >= 8 ? light ? "\x1b[38;5;130m" : "\x1b[38;5;208m" : light ? "\x1b[33m" : "\x1b[93m";
|
|
8
13
|
if (theme === "pink") {
|
|
9
|
-
const light = /^(7|15)$/.test(String(env.COLORFGBG || "").split(";").at(-1));
|
|
10
14
|
return depth >= 24 ? light ? "\x1b[38;2;168;62;104m" : "\x1b[38;2;243;168;200m"
|
|
11
15
|
: depth >= 8 ? light ? "\x1b[38;5;132m" : "\x1b[38;5;218m" : "\x1b[95m";
|
|
12
16
|
}
|
|
@@ -19,7 +23,7 @@ export function colorTerminalText(text, theme, options) {
|
|
|
19
23
|
}
|
|
20
24
|
|
|
21
25
|
export function colorTerminalMotion(frame, theme, options) {
|
|
22
|
-
if (theme
|
|
26
|
+
if (!isColorTheme(theme) || theme === "green") return frame;
|
|
23
27
|
const code = terminalColorCode(theme, options);
|
|
24
28
|
return frame.replace(/\x1b\[(?:38;5;\d+|97)m/g, code);
|
|
25
29
|
}
|
package/src/usage-analysis.mjs
CHANGED
|
@@ -1,51 +1,94 @@
|
|
|
1
|
-
import
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import { summarizeUsage, summarizeUsageLogs, usageLogPath, usageSummaryVersion, subscribeUsageAppends, usageProvider, mergeUsageSummary } from "./usage-store.mjs";
|
|
2
4
|
import { createUsageAnalytics } from "./usage-analytics.mjs";
|
|
3
5
|
import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
|
|
4
6
|
|
|
5
7
|
const MAX_ENTRIES = 2;
|
|
6
8
|
const MAX_BYTES = 2 * 1024 * 1024;
|
|
7
|
-
const
|
|
8
|
-
const activeReads = createAbortAwareSingleflight();
|
|
9
|
+
const MAX_PENDING_BYTES = 256 * 1024;
|
|
10
|
+
const cache = new Map(), activeReads = createAbortAwareSingleflight();
|
|
11
|
+
let unsubscribe;
|
|
12
|
+
|
|
13
|
+
async function completeLines(file) {
|
|
14
|
+
for (const candidate of [file + ".1", file]) {
|
|
15
|
+
let handle;
|
|
16
|
+
try {
|
|
17
|
+
handle = await fs.open(candidate, "r");const stat = await handle.stat();
|
|
18
|
+
if (!stat.size) continue;
|
|
19
|
+
const byte = Buffer.alloc(1);await handle.read(byte, 0, 1, stat.size - 1);
|
|
20
|
+
if (byte[0] !== 10) return false;
|
|
21
|
+
} catch (error) { if (error.code !== "ENOENT") return false; }
|
|
22
|
+
finally { await handle?.close(); }
|
|
23
|
+
}
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Reuse only appends witnessed inside the writer's existing cross-process lock.
|
|
28
|
+
// External edits, another process's writes and rotations force the normal scan.
|
|
29
|
+
function appendOnly(before, after, bytes) {
|
|
30
|
+
if (!before || !after) return false;
|
|
31
|
+
const a = before.split("\0"), b = after.split("\0");
|
|
32
|
+
if (a.length !== 2 || b.length !== 2 || a[0] !== b[0]) return false;
|
|
33
|
+
const oldFiles = a[1].split("|"), nextFiles = b[1].split("|");
|
|
34
|
+
if (oldFiles.length !== 2 || nextFiles.length !== 2 || oldFiles[0] !== nextFiles[0]) return false;
|
|
35
|
+
const old = oldFiles[1].split(":"), next = nextFiles[1].split(":");
|
|
36
|
+
return next.length === 5 && (oldFiles[1] === "missing" ? Number(next[2]) === bytes
|
|
37
|
+
: old.length === 5 && old[0] === next[0] && old[1] === next[1] && Number(next[2]) === Number(old[2]) + bytes);
|
|
38
|
+
}
|
|
39
|
+
function prune() {
|
|
40
|
+
let bytes = [...cache.values()].reduce((sum, e) => sum + e.bytes + e.pendingBytes, 0);
|
|
41
|
+
for (const [key, entry] of cache) {
|
|
42
|
+
if (bytes <= MAX_BYTES && cache.size <= MAX_ENTRIES) break;
|
|
43
|
+
cache.delete(key);bytes -= entry.bytes + entry.pendingBytes;
|
|
44
|
+
}
|
|
45
|
+
if (!cache.size && unsubscribe) { unsubscribe();unsubscribe = null; }
|
|
46
|
+
}
|
|
47
|
+
function observe() {
|
|
48
|
+
unsubscribe ||= subscribeUsageAppends(change => {
|
|
49
|
+
for (const [key, entry] of cache) {
|
|
50
|
+
if (entry.file !== change.filePath) continue;
|
|
51
|
+
if (entry.version !== change.before || !appendOnly(change.before, change.after, change.bytes)
|
|
52
|
+
|| entry.pendingBytes + change.bytes > MAX_PENDING_BYTES) { cache.delete(key);continue; }
|
|
53
|
+
entry.pending.push(...change.lines);entry.pendingBytes += change.bytes;entry.version = change.after;
|
|
54
|
+
}
|
|
55
|
+
prune();
|
|
56
|
+
});
|
|
57
|
+
}
|
|
9
58
|
|
|
10
|
-
// Only bounded, settled-file aggregates survive. No record index or payload cache.
|
|
11
59
|
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", signal } = {}) {
|
|
12
|
-
const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider });
|
|
13
60
|
const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const key = version === null ? null : `${version}\0${query}`;
|
|
17
|
-
const activeVersion = version === null && warn === console.error ? await usageSummaryVersion(filePath, { settled: false }) : null;
|
|
18
|
-
if (key && cache.has(key)) return structuredClone(await cache.get(key).promise);
|
|
19
|
-
if (key) {
|
|
20
|
-
for (const [old, entry] of cache) if (entry.version !== version) cache.delete(old);
|
|
21
|
-
while (cache.size >= MAX_ENTRIES) cache.delete(cache.keys().next().value);
|
|
22
|
-
} else cache.clear();
|
|
23
|
-
const entry = { version, bytes: 0, promise: null };
|
|
61
|
+
const file = path.resolve(filePath), query = `${file}\0${provider}\0${zone.resolvedOptions().timeZone}\0${zone.format(new Date(now))}`;
|
|
62
|
+
const version = warn === console.error ? await usageSummaryVersion(file, { settled: false }) : null;
|
|
24
63
|
const collect = async () => {
|
|
64
|
+
const cached = version && cache.get(query);
|
|
65
|
+
if (cached?.version === version) {
|
|
66
|
+
cache.delete(query);cache.set(query, cached);
|
|
67
|
+
cached.analytics.advanceTime(now);
|
|
68
|
+
for (const line of cached.pending) {
|
|
69
|
+
const record = JSON.parse(line);
|
|
70
|
+
if (provider && provider !== usageProvider(record)) continue;
|
|
71
|
+
const one = summarizeUsage([record]);mergeUsageSummary(cached.summary, one);cached.analytics.record(record, one);
|
|
72
|
+
}
|
|
73
|
+
cached.pending = [];cached.pendingBytes = 0;
|
|
74
|
+
const result = { summary: cached.summary, analytics: cached.analytics.snapshot() };
|
|
75
|
+
cached.bytes = Buffer.byteLength(JSON.stringify(result));
|
|
76
|
+
if (result.analytics.undated_records > 0) cache.delete(query);
|
|
77
|
+
prune();return result;
|
|
78
|
+
}
|
|
79
|
+
cache.delete(query);prune();
|
|
80
|
+
const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider });
|
|
25
81
|
let warned = false;
|
|
26
|
-
const summary = await summarizeUsageLogs(filePath, {
|
|
27
|
-
|
|
28
|
-
onRecord: analytics.record,
|
|
29
|
-
warn(message) { warned = true; warn(message); },
|
|
30
|
-
});
|
|
82
|
+
const summary = await summarizeUsageLogs(filePath, { provider, onRecord: analytics.record,
|
|
83
|
+
warn(message) { warned = true;warn(message); } });
|
|
31
84
|
const result = { summary, analytics: analytics.snapshot() };
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
let bytes = [...cache.values()].reduce((total, item) => total + item.bytes, 0);
|
|
38
|
-
for (const [old, item] of cache) {
|
|
39
|
-
if (bytes <= MAX_BYTES) break;
|
|
40
|
-
cache.delete(old);
|
|
41
|
-
bytes -= item.bytes;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
85
|
+
const complete = version && await completeLines(file);
|
|
86
|
+
const after = version ? await usageSummaryVersion(file, { settled: false }) : null;
|
|
87
|
+
const bytes = Buffer.byteLength(JSON.stringify(result));
|
|
88
|
+
if (version && complete && after === version && !warned && !result.analytics.undated_records && bytes <= MAX_BYTES) {
|
|
89
|
+
cache.set(query, { file, version, summary, analytics, bytes, pending: [], pendingBytes: 0 });observe();prune();
|
|
44
90
|
}
|
|
45
91
|
return result;
|
|
46
92
|
};
|
|
47
|
-
|
|
48
|
-
if (key) cache.set(key, entry);
|
|
49
|
-
try { return structuredClone(await entry.promise); }
|
|
50
|
-
catch (error) { if (cache.get(key) === entry) cache.delete(key); throw error; }
|
|
93
|
+
return structuredClone(await (version ? activeReads.run(`${version}\0${query}`, collect, { signal }) : collect()));
|
|
51
94
|
}
|
package/src/usage-analytics.mjs
CHANGED
|
@@ -40,6 +40,7 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
return {
|
|
43
|
+
advanceTime(value) { now = value; },
|
|
43
44
|
record(record, summary) {
|
|
44
45
|
const timestamp = typeof record.ts === "string" ? Date.parse(record.ts) : NaN;
|
|
45
46
|
if (!Number.isFinite(timestamp) || timestamp > now) { undated += 1; return; }
|
package/src/usage-store.mjs
CHANGED
|
@@ -25,6 +25,10 @@ let pendingRecords = 0;
|
|
|
25
25
|
let pendingBytes = 0;
|
|
26
26
|
let droppedRecords = 0;
|
|
27
27
|
let writeFailures = 0;
|
|
28
|
+
const appendObservers = new Set();
|
|
29
|
+
export function subscribeUsageAppends(listener) {
|
|
30
|
+
appendObservers.add(listener);return () => appendObservers.delete(listener);
|
|
31
|
+
}
|
|
28
32
|
const runtimeUsage = { since: new Date().toISOString(), records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 };
|
|
29
33
|
const runtimeUsageByProvider = new Map();
|
|
30
34
|
|
|
@@ -155,7 +159,14 @@ async function writeUsageBatch(batch) {
|
|
|
155
159
|
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
156
160
|
await withFileLock(`${path.resolve(filePath)}.lock`, async () => {
|
|
157
161
|
batch.push(...takePendingWrites(filePath, maxBytes));
|
|
162
|
+
const before = appendObservers.size ? await usageSummaryVersion(filePath, { settled: false }) : null;
|
|
158
163
|
await appendRotatingLines(filePath, batch.map(({ line }) => line), maxBytes);
|
|
164
|
+
if (before && appendObservers.size) {
|
|
165
|
+
const after = await usageSummaryVersion(filePath, { settled: false });
|
|
166
|
+
const change = { filePath: path.resolve(filePath), before, after,
|
|
167
|
+
lines: batch.map(entry => entry.line), bytes: batch.reduce((sum, entry) => sum + entry.bytes, 0) };
|
|
168
|
+
for (const listener of appendObservers) { try { listener(change); } catch { /* Analytics cannot fail a log write. */ } }
|
|
169
|
+
}
|
|
159
170
|
}, {
|
|
160
171
|
timeoutMs: USAGE_WRITE_LOCK_TIMEOUT_MS,
|
|
161
172
|
staleMs: USAGE_WRITE_LOCK_STALE_MS,
|
|
@@ -351,22 +362,21 @@ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord
|
|
|
351
362
|
if (provider && provider !== usageProvider(record)) continue;
|
|
352
363
|
const one = summarizeUsage([record]);
|
|
353
364
|
onRecord?.(record, one);
|
|
354
|
-
summary
|
|
355
|
-
addUsageTotals(summary.totals, one.totals);
|
|
356
|
-
addUsageTotals(summary.providers, one.providers);
|
|
357
|
-
for (const [model, values] of Object.entries(one.byModel)) {
|
|
358
|
-
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
359
|
-
addUsageTotals(summary.byModel[model], values);
|
|
360
|
-
}
|
|
361
|
-
for (const [model, values] of Object.entries(one.bySourceModel)) {
|
|
362
|
-
if (!Object.hasOwn(summary.bySourceModel, model)) summary.bySourceModel[model] = {};
|
|
363
|
-
addUsageTotals(summary.bySourceModel[model], values);
|
|
364
|
-
}
|
|
365
|
+
mergeUsageSummary(summary, one);
|
|
365
366
|
}
|
|
366
367
|
}
|
|
367
368
|
return summary;
|
|
368
369
|
}
|
|
369
370
|
|
|
371
|
+
export function mergeUsageSummary(summary, one) {
|
|
372
|
+
summary.requests += one.requests;
|
|
373
|
+
addUsageTotals(summary.totals, one.totals);addUsageTotals(summary.providers, one.providers);
|
|
374
|
+
for (const key of ["byModel", "bySourceModel"]) for (const [model, values] of Object.entries(one[key])) {
|
|
375
|
+
if (!Object.hasOwn(summary[key], model)) Object.defineProperty(summary[key], model, { value: {}, enumerable: true, configurable: true, writable: true });
|
|
376
|
+
addUsageTotals(summary[key][model], values);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
370
380
|
const SUMMARY_CACHE_MAX_BYTES = 256 * 1024;
|
|
371
381
|
const SUMMARY_CACHE_SETTLED_MS = 2000;
|
|
372
382
|
let cachedSummary = null;
|
package/src/usage.mjs
CHANGED
package/src/user-settings.mjs
CHANGED
|
@@ -56,7 +56,7 @@ export function readUserSettings({ env = process.env, home = os.homedir(), stric
|
|
|
56
56
|
delete parsed[key];
|
|
57
57
|
}
|
|
58
58
|
if (Object.hasOwn(parsed, "terminal_color_theme") && !isColorTheme(parsed.terminal_color_theme)) {
|
|
59
|
-
if (strict) throw invalidSettings(filePath, "terminal_color_theme must be green, klein or
|
|
59
|
+
if (strict) throw invalidSettings(filePath, "terminal_color_theme must be green, klein, pink, mono or orange");
|
|
60
60
|
delete parsed.terminal_color_theme;
|
|
61
61
|
}
|
|
62
62
|
if (Object.hasOwn(parsed, AUTO_REVIEW_MODEL_KEY)) {
|
|
@@ -152,7 +152,7 @@ export function terminalColorPreference(options = {}) {
|
|
|
152
152
|
}
|
|
153
153
|
|
|
154
154
|
export function writeTerminalColorTheme(theme, options = {}) {
|
|
155
|
-
if (!isColorTheme(theme)) throw new Error("Choose green, klein or
|
|
155
|
+
if (!isColorTheme(theme)) throw new Error("Choose green, klein, pink, mono or orange for the terminal color theme");
|
|
156
156
|
return withFileLockSync(`${userSettingsPath(options)}.lock`, () => {
|
|
157
157
|
const settings = readUserSettings({ ...options, strict: true });
|
|
158
158
|
const next = { ...settings };
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
2
|
-
|
|
3
|
-
const MAX_HEADER_BYTES = 32 * 1024 * 1024;
|
|
4
|
-
const MAX_SOURCE_BYTES = 36 * 1024 * 1024;
|
|
5
|
-
|
|
6
|
-
// Inspect only packed, named protocol/settings candidates in the installed
|
|
7
|
-
// archive. A small forwarding chunk must not hide its real implementation.
|
|
8
|
-
export function inspectPredictionArchive(archive) {
|
|
9
|
-
const fd = fs.openSync(archive, "r");
|
|
10
|
-
try {
|
|
11
|
-
const before = fs.fstatSync(fd);
|
|
12
|
-
const read = (size, offset) => {
|
|
13
|
-
if (!before.isFile() || !Number.isSafeInteger(size) || size < 0 || !Number.isSafeInteger(offset)
|
|
14
|
-
|| offset < 0 || offset + size > before.size) throw new Error("Invalid prediction App archive bounds");
|
|
15
|
-
const bytes = Buffer.alloc(size);
|
|
16
|
-
if (fs.readSync(fd, bytes, 0, size, offset) !== size) throw new Error("Prediction App archive changed during inspection");
|
|
17
|
-
return bytes;
|
|
18
|
-
};
|
|
19
|
-
const prefix = read(16, 0), headerSize = prefix.readUInt32LE(12);
|
|
20
|
-
if (headerSize > MAX_HEADER_BYTES) throw new Error("Prediction App archive header exceeds its inspection limit");
|
|
21
|
-
const tree = JSON.parse(read(headerSize, 16)).files;
|
|
22
|
-
const base = 8 + prefix.readUInt32LE(4);
|
|
23
|
-
let sourceBytes = 0;
|
|
24
|
-
const contains = (files, pattern, markers, maxEntryBytes) => {
|
|
25
|
-
const entries = Object.entries(files || {}).filter(([name]) => pattern.test(name));
|
|
26
|
-
if (entries.length > 16) throw new Error("Prediction App protocol candidates exceed their inspection limit");
|
|
27
|
-
for (const [, entry] of entries) {
|
|
28
|
-
if (!entry || typeof entry !== "object") throw new Error("Invalid prediction App archive entry");
|
|
29
|
-
if (entry.unpacked) continue;
|
|
30
|
-
if (!Number.isSafeInteger(entry.size) || entry.size > maxEntryBytes
|
|
31
|
-
|| sourceBytes + entry.size > MAX_SOURCE_BYTES) throw new Error("Prediction App source exceeds its inspection limit");
|
|
32
|
-
sourceBytes += entry.size;
|
|
33
|
-
const bytes = read(entry.size, base + Number(entry.offset));
|
|
34
|
-
if (markers.every(marker => bytes.includes(Buffer.from(marker)))) return true;
|
|
35
|
-
}
|
|
36
|
-
return false;
|
|
37
|
-
};
|
|
38
|
-
const compatible = contains(tree?.[".vite"]?.files?.build?.files, /^main-[\w-]+\.js$/,
|
|
39
|
-
["/wham/predictions/config", "experimentalPredictionMode"], 32 * 1024 * 1024)
|
|
40
|
-
&& contains(tree?.webview?.files?.assets?.files, /^general-settings-[\w-]+\.js$/, ["4290031608"], 4 * 1024 * 1024);
|
|
41
|
-
const after = fs.fstatSync(fd);
|
|
42
|
-
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) throw new Error("Prediction App archive changed during inspection");
|
|
43
|
-
return { compatible, size: after.size, mtimeMs: after.mtimeMs };
|
|
44
|
-
} finally { fs.closeSync(fd); }
|
|
45
|
-
}
|