codex-copilot-dx 1.3.19 → 1.3.21
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 +1 -0
- package/bin/cli.mjs +32 -3
- package/docs/ARCHITECTURE.md +11 -1
- package/docs/REFERENCE.md +9 -2
- package/package.json +1 -1
- package/src/access-settings.mjs +48 -0
- package/src/adapter.mjs +3 -3
- package/src/claude-capability-config.mjs +6 -0
- package/src/claude-gateway.mjs +78 -8
- package/src/client-versions.mjs +139 -0
- package/src/codex-client-doctor.mjs +3 -1
- package/src/codex-model-catalog.mjs +33 -10
- package/src/connection-client-sync.mjs +182 -0
- package/src/connection-management.mjs +264 -0
- package/src/connection-policy.mjs +321 -0
- package/src/connection-routing.mjs +183 -0
- package/src/connection-runtime.mjs +44 -1327
- package/src/connection-view.mjs +320 -0
- package/src/dashboard/console.js +17 -3
- package/src/dashboard/context.js +2 -1
- package/src/dashboard/features.js +8 -4
- package/src/dashboard/index.html +7 -3
- package/src/dashboard/language.js +5 -1
- package/src/dashboard/tools.js +1 -0
- package/src/doctor.mjs +8 -0
- package/src/local-tools.mjs +6 -3
- package/src/native-prediction-windows.mjs +8 -0
- package/src/observability.mjs +2 -1
- package/src/privacy-stream.mjs +10 -7
- package/src/privacy-transform.mjs +32 -7
- package/src/responses-handler.mjs +7 -1
- package/src/responses-proxy.mjs +125 -36
- package/src/service-control.mjs +7 -1
- package/src/source-lifecycle.mjs +61 -0
- package/src/stream-errors.mjs +29 -5
- package/src/stream.mjs +42 -5
package/README.md
CHANGED
|
@@ -67,6 +67,7 @@ Use the Web UI for accounts, APIs, models, client access, input suggestions, nat
|
|
|
67
67
|
- **Input suggestions:** new integrations attempt setup by default when Codex is closed. Saved off choices are retained. The Web UI can enable, disable, finish setup, open Codex and repair the bridge. Setup synchronizes Show predictions, adds App-profile trust and locally decrypts the prediction hosts' HTTPS traffic. App/thread eligibility still applies. [Details](docs/REFERENCE.md#optional-native-predictions).
|
|
68
68
|
- **Images:** Codex native host tools use the selected GitHub image model, with GPT Image 2.5 Flare as the default. Images start enabled; saved off choices are retained. On macOS with Codex 0.166+, fully quit a running App that lacks the host, start Codex through CCDX, and use a new chat. ChatGPT sign-in and Apps are retained. The Web UI provides model selection without an extra API key, MCP or CCDX image skill. [Details](docs/REFERENCE.md#native-image-generation).
|
|
69
69
|
- **Updates:** Settings → Install update downloads and verifies a stable release, then switches the installed service when idle. Busy work postpones the switch. Unmanaged launches require the installer or an installed command. [Details](docs/REFERENCE.md#installation-and-updates).
|
|
70
|
+
- **App updates:** Checks & repairs and `ccdx doctor` show observed installed Codex and Claude versions. A version change does not by itself verify the running App or its integrations. [Details](docs/REFERENCE.md#checks-and-troubleshooting).
|
|
70
71
|
|
|
71
72
|
Web UI activity updates through server push; the terminal uses the same in-process activity feed. Reconnecting restores current state and bounded recent records.
|
|
72
73
|
|
package/bin/cli.mjs
CHANGED
|
@@ -30,7 +30,16 @@ if (CLI.command === "manage") {
|
|
|
30
30
|
const { runManagementCommand } = await import("../src/cli-management.mjs");
|
|
31
31
|
const address = parseAdapterAddressOptions(process.env);
|
|
32
32
|
const result = await runManagementCommand(CLI, { host: address.adapterHost, port: address.adapterPort, version: LOCAL_VERSION });
|
|
33
|
-
if (result)
|
|
33
|
+
if (result) {
|
|
34
|
+
const error = await new Promise(resolve => {
|
|
35
|
+
process.stdout.once("error", resolve);
|
|
36
|
+
process.stdout.write(`${result}\n`, resolve);
|
|
37
|
+
});
|
|
38
|
+
if (error) {
|
|
39
|
+
if (error.code !== "EPIPE") console.error(status("err", `Could not write command output: ${error.message}`));
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
34
43
|
process.exit(0);
|
|
35
44
|
} catch (error) {
|
|
36
45
|
if (CLI.flags?.format === "json") console.log(JSON.stringify({ error: { code: error.code || "ccdx_command_failed", message: error.message } }));
|
|
@@ -315,6 +324,19 @@ let clientIntegration = null;
|
|
|
315
324
|
let providerRuntime = null;
|
|
316
325
|
let terminalConsole = null;
|
|
317
326
|
const webUiUrl = `http://${ADAPTER_HOST === "::1" ? "[::1]" : "127.0.0.1"}:${ADAPTER_PORT}`;
|
|
327
|
+
let versionMonitor = null, versionModule = null;
|
|
328
|
+
const clientVersions = {
|
|
329
|
+
snapshot: () => versionMonitor?.snapshot() || null,
|
|
330
|
+
refresh() {
|
|
331
|
+
if (shuttingDown || serviceWorker?.warming || serviceWorker?.draining || serviceWorker?.preserving) return Promise.resolve(clientVersions.snapshot());
|
|
332
|
+
versionModule ||= import("../src/client-versions.mjs").then(({ createClientVersionMonitor }) => {
|
|
333
|
+
if (shuttingDown) return null;
|
|
334
|
+
versionMonitor = createClientVersionMonitor({ onChange: names => console.log(status("info", `Installed ${names.map(name => name === "codex" ? "Codex" : "Claude").join(" and ")} App updated; check integration in the WebUI or ccdx doctor`)) });
|
|
335
|
+
return versionMonitor;
|
|
336
|
+
}).catch(error => { versionModule = null;throw error; });
|
|
337
|
+
return versionModule.then(monitor => monitor?.refresh());
|
|
338
|
+
},
|
|
339
|
+
};
|
|
318
340
|
async function launchDashboard() {
|
|
319
341
|
try {
|
|
320
342
|
const result = await openDashboard(webUiUrl, { enabled: !CLI.noBrowser && servicePreferences().open_webui });
|
|
@@ -349,6 +371,8 @@ async function reuseRunningAdapterIfAvailable() {
|
|
|
349
371
|
}
|
|
350
372
|
if (!running.ok) return false;
|
|
351
373
|
|
|
374
|
+
void fetch(`${webUiUrl}/_ccdx/ui/settings`, { method: "POST", headers: { "X-CCDX-Dashboard": "1", Origin: webUiUrl, "Content-Type": "application/json" },
|
|
375
|
+
body: JSON.stringify({ action: "client_versions" }), signal: AbortSignal.timeout(1000) }).catch(() => {});
|
|
352
376
|
const serviceStatus = readAdapterStatus({ host: ADAPTER_HOST, port: ADAPTER_PORT }).catch(() => null);
|
|
353
377
|
console.log(startupCheck("ok", "Service", `Using running service: ${running.baseUrl}`));
|
|
354
378
|
console.log(startupCheck("info", "Sign-in", "Using saved sign-in; not rechecked"));
|
|
@@ -455,6 +479,7 @@ try {
|
|
|
455
479
|
providerRuntime = createProviderRuntime({ githubClient: profileRuntime.codexClient, githubRegistry: profileModels.codexRegistry,
|
|
456
480
|
refreshGithubCatalog: () => profileModels.refreshCodex({ strict: true }),
|
|
457
481
|
corePort: ADAPTER_PORT, preserveClientConfiguration: () => serviceWorker?.preserving === true || serviceWorker?.draining === true,
|
|
482
|
+
clientVersionsSnapshot: clientVersions.snapshot,
|
|
458
483
|
clientAccessChanged: async enabled => { earlyIntegration.setPredictionActive(enabled && servicePreferences().prediction_enabled);if (enabled) await earlyIntegration.configure(); },
|
|
459
484
|
githubCredentialFingerprint: () => profileRuntime.codexCredentialFingerprint,
|
|
460
485
|
log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "M365", message)) });
|
|
@@ -498,7 +523,7 @@ try {
|
|
|
498
523
|
snapshot: () => activeServer?.ccdxSnapshot?.() || {},
|
|
499
524
|
subscribe: listener => activeServer?.ccdxSubscribeActivity?.(listener),
|
|
500
525
|
preferences: () => { const { saved, theme, color_theme } = serviceSettingsSnapshot();return { ...saved, theme, color_theme }; } });
|
|
501
|
-
const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole,
|
|
526
|
+
const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole, clientVersions,
|
|
502
527
|
adapterPort: ADAPTER_PORT, adapterHost: ADAPTER_HOST, manualUpdate: serviceWorker ? () => serviceWorker.requestUpdate() : undefined,
|
|
503
528
|
nightlyStatus: () => serviceWorker?.status() || null, nightlyChanged: enabled => serviceWorker?.preferenceChanged(enabled) });
|
|
504
529
|
const codexModelCatalog = createCodexModelCatalog();
|
|
@@ -516,7 +541,7 @@ try {
|
|
|
516
541
|
terminalAnimationTheme,
|
|
517
542
|
terminalActivity: terminalConsole,
|
|
518
543
|
handoffState: serviceWorker?.takeState(), isDraining: () => serviceWorker?.draining === true,
|
|
519
|
-
dashboardOptions: { serviceControl, host: ADAPTER_HOST, port: ADAPTER_PORT,
|
|
544
|
+
dashboardOptions: { serviceControl, clientVersions, host: ADAPTER_HOST, port: ADAPTER_PORT,
|
|
520
545
|
credentialsChanged: () => { defaultCopilotClient.invalidateCredentials();profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient }); },
|
|
521
546
|
applyAnimation: theme => terminalConsole.apply({ theme }) },
|
|
522
547
|
nativePredictionPac: () => clientIntegration?.pacUrl() || null,
|
|
@@ -547,12 +572,14 @@ try {
|
|
|
547
572
|
modelRefreshTimer = setInterval(() => {
|
|
548
573
|
if (providerRuntime.selection().codex === "github") profileModels.refreshAll().then(() => providerRuntime.selection().codex === "github" && providerRuntime.syncClients(["codex"])).catch(() => {});
|
|
549
574
|
providerRuntime.refresh().catch(() => {});
|
|
575
|
+
void clientVersions.refresh().catch(() => {});
|
|
550
576
|
}, refreshIntervalMs);
|
|
551
577
|
modelRefreshTimer.unref?.();
|
|
552
578
|
}
|
|
553
579
|
|
|
554
580
|
startupComplete = true;
|
|
555
581
|
if (!startupPresentation.enabled) console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
|
|
582
|
+
void clientVersions.refresh().catch(() => {});
|
|
556
583
|
runInBackground(printUpdateNotice);
|
|
557
584
|
await launchDashboard();
|
|
558
585
|
if (!serviceWorker?.warming) {
|
|
@@ -569,6 +596,7 @@ try {
|
|
|
569
596
|
let exitCode = 0;
|
|
570
597
|
try {
|
|
571
598
|
if (modelRefreshTimer) clearInterval(modelRefreshTimer);
|
|
599
|
+
versionMonitor?.close();
|
|
572
600
|
const result = await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });
|
|
573
601
|
if (result.forced) console.warn(status("warn", "Remaining service connections closed"));
|
|
574
602
|
await clientIntegration?.close();
|
|
@@ -612,6 +640,7 @@ try {
|
|
|
612
640
|
await LOGGING.cleanup();try { LOGGING = configureLogging(); } catch { LOGGING = configureLogging({ env: { ...process.env, CCDX_LOG_PATH: "" } }); }
|
|
613
641
|
terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
|
|
614
642
|
earlyIntegration.retireImages();
|
|
643
|
+
setImmediate(() => void clientVersions.refresh().catch(() => {}));
|
|
615
644
|
},
|
|
616
645
|
inspect: () => {
|
|
617
646
|
const data = activeServer.ccdxSnapshot(), routes = data.requests.by_route;
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -631,7 +631,9 @@ the lockfile fixes CI transitives, not consumers' future transitive resolution.
|
|
|
631
631
|
|
|
632
632
|
Stream performance retains existing route totals and adds `by_route.<route>.by_provider`. Each source has started/active/finished counts, terminal totals, bounded model outcomes, request-to-first-output timing and preparation histograms. Source assignment is pinned once. There are at most 18 source labels (two built-ins and 16 APIs) plus `other`, and 32 model labels plus `other` per source. Unassigned finished requests use `unknown`; request IDs, accounts and URLs never become metric labels. Recent requests remain capped at 20. `runtime_usage.by_provider` has at most 18 labels plus `other`; unknown usage stays partial and persisted historical records retain their source.
|
|
633
633
|
|
|
634
|
-
`operation-error.mjs` distinguishes client cancellation, unspecified abort, timeout, network/TLS/proxy, authentication and access denial. HTTP 403 is not proof of credential expiry. Claude and Codex cancellations are informational; request-body timeouts use 408, upstream/idle timeouts 504, and local client cancellation diagnostics 499.
|
|
634
|
+
`operation-error.mjs` distinguishes client cancellation, unspecified abort, timeout, network/TLS/proxy, authentication and access denial. HTTP 403 is not proof of credential expiry. Claude and Codex cancellations are informational; request-body timeouts use 408, upstream/idle timeouts 504, and local client cancellation diagnostics 499. Upstream HTTP error status and body retain their existing path. Responses SSE failures use a complete `response.failed` event, including locally supplied metadata when the upstream did not provide it.
|
|
635
|
+
|
|
636
|
+
After Claude `message_stop`, the downstream response ends before an upstream drain. A complete drain permits connection reuse; cancellation, failure, one second or more than 64 KiB of tail bytes closes the reader. The last received chunk can exceed the byte threshold. Privacy masking preserves numeric literals in JSON-encoded tool arguments while restoring only mapped string values.
|
|
635
637
|
|
|
636
638
|
Byte-weighted request admission is not a simultaneous-stream limit. The 1.2.0 load replay exercises 16/64/128 small-body held streams, management responsiveness and downstream cancellation against 1.1.1. It does not establish a universal safe concurrency maximum. Existing defaults remain unchanged; see the release receipt for measured bounds.
|
|
637
639
|
|
|
@@ -1132,3 +1134,11 @@ The image and input-suggestion panels share `codex-launch-control.mjs`. `codex-a
|
|
|
1132
1134
|
The managed Codex catalog projects explicit source input modalities ahead of native templates and checks GitHub priority eligibility against the full live source registry. Unknown modality metadata keeps the prior fallback. Source identities, selected models and routing remain unchanged.
|
|
1133
1135
|
|
|
1134
1136
|
`safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks release request admission before the optional body read; image processing slots are released at the same point. Count-token singleflight forwards those callbacks only to the appropriate waiters. Successful requests never invoke the reader.
|
|
1137
|
+
|
|
1138
|
+
## Client updates and streaming boundaries (1.3.20)
|
|
1139
|
+
|
|
1140
|
+
`client-versions.mjs` inspects bounded local App metadata asynchronously after service readiness. It coalesces checks, preserves a corrupt observation file, and atomically records only installed versions, builds and change times. A timed-out inspection cannot block service startup or inference. The current App process and actual capability adoption remain unverified. A detected unrecognized system Claude App major prevents later writes to shared capability fields without changing existing routing or model aliases. The existing model-refresh timer, manual checks and a nonblocking service-reuse notification schedule observation; a disabled timer leaves startup and manual checks available.
|
|
1141
|
+
|
|
1142
|
+
The Codex catalog retains at most two previously verified bundled catalogs in memory when the client supplies an exact prerelease/build version. A binary identity change during extraction, or two binaries reporting the same exact version, prevents that retained fallback. Requests containing only a core version keep their existing matching behavior and report its limited precision. No catalog is fetched from the network and no new persistent model cache is introduced.
|
|
1143
|
+
|
|
1144
|
+
Responses and Messages parsers, Chat line reading and the privacy restoration layer accept LF, CRLF and CR SSE lines. Existing output ordering, retry eligibility, error handling, comment heartbeats and backpressure remain. Source-lock cancellation signals reach both Responses handlers without changing ownership rules.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -106,10 +106,13 @@ Catalog diagnostics distinguish local cached data from an online response and ex
|
|
|
106
106
|
- **Request failure:** use Requests or `ccdx requests --failed`. HTTP failures and model completion outcomes are separate. A successful HTTP transport can still carry a model error.
|
|
107
107
|
- **Token counting unavailable:** an observed API count-endpoint 404 is cached briefly per model/header scope. Inference and token counting are separate capabilities; no synthetic count is returned.
|
|
108
108
|
- **Local checks:** `doctor` is read-only by default. `--online` checks access; `--compat` sends minimal inference and consumes usage. `--fix` backs up owned configuration and performs bounded repairs. It does not enable optional features, change company policy or force-restart apps. Partial repairs exit 1.
|
|
109
|
+
- **App updates:** after the service is ready, CCDX observes installed App versions in the background. Checks & repairs shows the result; `ccdx doctor` can inspect it locally. On macOS this uses known App bundle metadata and, when available, the bundled Codex CLI version. On Windows the registered Codex package is inspected; Claude App remains unknown if reliable metadata is unavailable. The running process may still be an older build, and a version observation does not verify images, predictions, model access or protocol compatibility. A detected unrecognized Claude App major version preserves existing shared capability fields during later synchronization. The compact local version record contains only App versions, builds and observation times, not credentials or conversation data. It is refreshed on startup, local checks and the existing model-refresh cadence; a reused service receives a nonblocking refresh notification.
|
|
109
110
|
- **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
|
|
110
111
|
|
|
111
112
|
Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input from records with valid counts for both. Unknown/invalid records remain in token totals but are excluded from both sides of the rate, with partial coverage indicated. It is not a request-based cache rate or a billing receipt.
|
|
112
113
|
|
|
114
|
+
For an identified conversation, hovering a point in the input-history chart shows that request's available cache-reuse ratio. Missing or invalid counts remain unknown; the bounded in-memory history and retained usage do not change.
|
|
115
|
+
|
|
113
116
|
## Settings and appearance
|
|
114
117
|
|
|
115
118
|
Settings separates saved preferences from effective state. Auto-save applies changes by default; required restarts remain explicit. Restore-defaults creates a backup first and keeps accounts, keys, model plans and chats. CLI preference reset/restore uses its own service-only backup; it does not change browser appearance or replace the Web UI's backup.
|
|
@@ -736,7 +739,7 @@ When expanded history exceeds Copilot's 50-image request limit, CCDX removes old
|
|
|
736
739
|
|
|
737
740
|
For `/v1/responses/compact`, CCDX sends one terminal `compaction_trigger`, validates completed compaction state, and preserves the complete returned window as the canonical next context. Only a validated window becomes a new local history root. Existing older branches remain available until normal history eviction.
|
|
738
741
|
|
|
739
|
-
Changing the model or transport of a continuation can require removing incompatible encrypted history from the forwarded request. A specific upstream encrypted-state verification failure can also trigger one sanitized retry, including when a nominally successful HTTP response ends with `response.failed`. CCDX withholds only the pre-output prelude of an encrypted continuation while evaluating that terminal event; it never retries after visible model output, so it cannot duplicate an already-started answer. Unrelated failures
|
|
742
|
+
Changing the model or transport of a continuation can require removing incompatible encrypted history from the forwarded request. A specific upstream encrypted-state verification failure can also trigger one sanitized retry, including when a nominally successful HTTP response ends with `response.failed`. CCDX withholds only the pre-output prelude of an encrypted continuation while evaluating that terminal event; it never retries after visible model output, so it cannot duplicate an already-started answer. Unrelated failures are not retried. CCDX does not decrypt that state locally.
|
|
740
743
|
|
|
741
744
|
Native Responses forwards Codex `agent_message` items unchanged. When a model requires Chat Completions, CCDX frames them as messages from another agent, not human input or approval, retaining author/recipient, typed text/refusal/reasoning and representable image/screenshot content. Content unsupported by Chat, including file, audio or opaque encrypted parts, receives an explicit compatibility error instead of being serialized into ordinary text. This projection does not introduce another model request or change native Responses, Fast, Auto-review or compaction routing.
|
|
742
745
|
|
|
@@ -756,6 +759,10 @@ Downstream backpressure waits also observe cancellation and the stream deadline.
|
|
|
756
759
|
|
|
757
760
|
Successful streaming responses are accepted only when the upstream body is SSE and reaches its protocol terminal event. Unexpected EOF becomes a protocol-native stream error, and repeated blank tool-argument deltas are stopped per tool call. Allowlisted rate-limit, retry, model, trace, and upstream request-ID metadata are forwarded; cookies, authorization, body-length, and encoding headers are not.
|
|
758
761
|
|
|
762
|
+
Responses stream errors, including untyped upstream error frames and interrupted streams, end in a `response.failed` event carrying the failure message. Missing response IDs and creation times are supplied locally. After a successful Claude `message_stop`, the client response ends immediately; CCDX reads toward upstream EOF to allow connection reuse. The reader is canceled after one second or when received tail bytes exceed 64 KiB; the last chunk can exceed that threshold. Errors and cancellation also close the reader.
|
|
763
|
+
|
|
764
|
+
Responses, Chat fallback, Messages and local response restoration accept LF, CRLF and CR SSE line endings. Existing comment heartbeats, upstream timeouts, retry eligibility, output and usage remain unchanged.
|
|
765
|
+
|
|
759
766
|
CCDX keeps each native Responses message on its first upstream ID when Copilot changes that ID during streaming. Message deltas, completion events, and cached history stay consistent, addressing this cause of duplicate live messages in Codex App. Tool identities, reasoning/encrypted content, message phases, and speed-tier routing are unchanged by this ID normalization. Stable events retain their original SSE bytes; changed events are rewritten with bounded, backpressured streaming.
|
|
760
767
|
|
|
761
768
|
Newer Codex App builds can advertise an `image_gen` namespace that already exists upstream. CCDX removes that exact conflicting client tool before forwarding and retries once only when Copilot explicitly reports an image namespace collision. Image input and screenshot optimization remain enabled.
|
|
@@ -796,7 +803,7 @@ Covered text includes conversation instructions, message text, tool results, too
|
|
|
796
803
|
|
|
797
804
|
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.
|
|
798
805
|
|
|
799
|
-
Tool data is interpreted in its own context: ordinary argument fields named `id`, `signature`, `data` or `type` are restored, while protocol identifiers and signed blocks remain unchanged. Streaming restoration retains SSE event metadata and restores Responses custom-tool text across fragments. Incomplete parameters are discarded when the upstream emits a failure rather than replacing that failure with a restoration error.
|
|
806
|
+
Tool data is interpreted in its own context: ordinary argument fields named `id`, `signature`, `data` or `type` are restored, while protocol identifiers and signed blocks remain unchanged. JSON-encoded Responses and Chat tool arguments retain their numeric values, including integers beyond JavaScript's safe range, when masked or restored. Streaming restoration retains SSE event metadata and restores Responses custom-tool text across fragments. Incomplete parameters are discarded when the upstream emits a failure rather than replacing that failure with a restoration error.
|
|
800
807
|
|
|
801
808
|
Each request pins its masking choice, including compatibility retries. Checks normally wait up to 15 seconds; a plan with at least one 16 KiB batch of uncached or in-flight text, or more than one pending native window, receives a bounded 60-second wait. A request still exceeding its wait is rejected before any upstream call. Submitted native batches finish and remain reusable; callers share in-flight work, and unused queued work stops. The 1.3.13 component reuses exact natural token-window predictions. Independent short CPU sequences run in bounded groups, with at most 512 total tokens including sequence markers and 16 KiB text. Each sequence keeps its tokenization, positions, attention and quantization scale; fields are not joined into a shared context. A single uncached sequence and accelerator-eligible windows retain their previous execution path. CPU batch-group and computed-window counts are exposed in the existing status metadata. Sparse non-O labels and exact scores use a separate 4 MiB/5,000-entry memory cache; original tokenization, window overlaps and current-text byte offsets are unchanged. Up to two text batches run concurrently, toward 16 KiB or 64 entries, keeping a larger individual text whole. Exact completed texts retain hot aliases. When the last waiter leaves, supporting components finish current windows, cache them and acknowledge cancellation before releasing the native slot. A waiter joining during cancellation resumes after acknowledgement; older compatible components finish whole batches as before. No request uses an incomplete model check. A native job retains its five-minute deadline and the native eight-job/16 MiB limits; the detection queue adds a 16 MiB/8,192-entry bound. Cache metadata remains within 5,000 entries/4 MiB, without storing detection history on disk. Cold-check cost and recovery are measured separately from hot reuse. Fully cached checks do not create native-work wait timers or cancellation listeners; they still honor caller cancellation before returning. CPU intermediate matrices are reused only within one inference. CoreML reuses one C-owned input array/provider per model under its existing mutex and clears its buffers after every successful or failed prediction. Go input memory is not retained by CoreML; classification mathematics and thread budgets are unchanged.
|
|
802
809
|
|
package/package.json
CHANGED
package/src/access-settings.mjs
CHANGED
|
@@ -64,6 +64,54 @@ export function checkedApi(value) {
|
|
|
64
64
|
if (value.checked_at !== undefined && (typeof value.checked_at !== "string" || !Number.isFinite(Date.parse(value.checked_at)))) throw accessError("ccdx_api_config_invalid");
|
|
65
65
|
return value;
|
|
66
66
|
}
|
|
67
|
+
export function prepareSourceAccess(input, next) {
|
|
68
|
+
if (
|
|
69
|
+
!["github", "m365", ...next.apis.map(api => api.id)].includes(input.id) ||
|
|
70
|
+
!Array.isArray(input.allowed) ||
|
|
71
|
+
new Set(input.allowed).size !== input.allowed.length ||
|
|
72
|
+
input.allowed.some(id => !CLIENT_IDS.includes(id))
|
|
73
|
+
)
|
|
74
|
+
throw accessError("ccdx_connections_action_invalid");
|
|
75
|
+
const api = next.apis.find(api => api.id === input.id);
|
|
76
|
+
if (
|
|
77
|
+
input.allowed.some(
|
|
78
|
+
id =>
|
|
79
|
+
(input.id === "github" && id !== "codex") ||
|
|
80
|
+
(api && !api.endpoints[id === "codex" ? "responses" : "messages"])
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
throw accessError("ccdx_api_protocol_required");
|
|
84
|
+
const affected = CLIENT_IDS.filter(
|
|
85
|
+
id => next.clients[id].allowed.includes(input.id) !== input.allowed.includes(id)
|
|
86
|
+
);
|
|
87
|
+
const sharedClaude = ["claude_app", "claude_code"].filter(
|
|
88
|
+
id => next.clients[id].enabled && next.clients[id].source === "m365"
|
|
89
|
+
);
|
|
90
|
+
const migrateClaude =
|
|
91
|
+
input.id === "m365" &&
|
|
92
|
+
!next.claude_private_keys &&
|
|
93
|
+
sharedClaude.length > 0 &&
|
|
94
|
+
affected.some(id => id !== "codex");
|
|
95
|
+
const targets = new Set();
|
|
96
|
+
for (const id of affected) {
|
|
97
|
+
const c = next.clients[id];
|
|
98
|
+
c.allowed = [
|
|
99
|
+
...c.allowed.filter(source => source !== input.id),
|
|
100
|
+
...(input.allowed.includes(id) ? [input.id] : []),
|
|
101
|
+
];
|
|
102
|
+
if (!input.allowed.includes(id)) {
|
|
103
|
+
if (c.source === input.id || c.deployments?.some(item => item.source === input.id)) targets.add(id);
|
|
104
|
+
if (c.source === input.id) c.source = null;
|
|
105
|
+
if (Array.isArray(c.deployments))
|
|
106
|
+
c.deployments = c.deployments.filter(item => item.source !== input.id);
|
|
107
|
+
c.history_isolation = true;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (migrateClaude) next.claude_private_keys = true;
|
|
111
|
+
if (migrateClaude)
|
|
112
|
+
for (const id of ["claude_app", "claude_code"]) if (next.clients[id].source === "m365") targets.add(id);
|
|
113
|
+
return { targets, migrateClaude };
|
|
114
|
+
}
|
|
67
115
|
export function defaultAccessSettings() {
|
|
68
116
|
return { version: 2, claude_private_keys: false, providers: { github: true, m365: true }, apis: [], clients: Object.fromEntries(CLIENT_IDS.map(id => [id,
|
|
69
117
|
{ enabled: true, allowed: id === "codex" ? ["github", "m365"] : ["m365"], source: null }])) };
|
package/src/adapter.mjs
CHANGED
|
@@ -237,7 +237,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
237
237
|
});
|
|
238
238
|
const responsesHandler = createResponsesHandler({
|
|
239
239
|
privacy,
|
|
240
|
-
validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
|
|
240
|
+
validateConversation: (body, headers, source, signal) => options.providerRuntime?.validateConversation?.(body, headers, source, signal),
|
|
241
241
|
resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
|
|
242
242
|
providerPreference: id => options.providerRuntime?.providerPreference?.(id),
|
|
243
243
|
provider: options.provider || options.providerRuntime?.github,
|
|
@@ -260,7 +260,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
260
260
|
});
|
|
261
261
|
const responsesCompactHandler = createResponsesCompactHandler({
|
|
262
262
|
privacy,
|
|
263
|
-
validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
|
|
263
|
+
validateConversation: (body, headers, source, signal) => options.providerRuntime?.validateConversation?.(body, headers, source, signal),
|
|
264
264
|
resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
|
|
265
265
|
providerPreference: id => options.providerRuntime?.providerPreference?.(id),
|
|
266
266
|
provider: options.provider || options.providerRuntime?.github,
|
|
@@ -282,7 +282,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
282
282
|
if (!provider || provider.id === "github") return githubHandlers;
|
|
283
283
|
if (!providerHandlers.has(provider)) {
|
|
284
284
|
const common = { provider, privacy, acquireRequest, imagePressure, keepaliveIntervalMs: options.keepaliveIntervalMs,
|
|
285
|
-
validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
|
|
285
|
+
validateConversation: (body, headers, source, signal) => options.providerRuntime?.validateConversation?.(body, headers, source, signal),
|
|
286
286
|
resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
|
|
287
287
|
providerPreference: id => options.providerRuntime?.providerPreference?.(id),
|
|
288
288
|
modelRegistry: provider.registry, now: options.now, openAIModelEnv: { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" },
|
|
@@ -26,6 +26,12 @@ export function inspectClaudeCapabilitySupport({ platform = process.platform, en
|
|
|
26
26
|
return { app_version: appVersion || null, app: /^[34]\./.test(appVersion || ""), code_version: codeVersion || null, code: /^2\.1\./.test(codeVersion || "") && Number(codeVersion.split(".")[2]) >= 293 };
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
export function claudeSupportForSync(support, observations) {
|
|
30
|
+
const rows = Array.isArray(observations?.claude) ? observations.claude : [];
|
|
31
|
+
const app = rows.find(entry => entry.id === "claude_system_claude");
|
|
32
|
+
return observations?.claude_unrecognized === true || app?.version && !/^[34]\./.test(app.version) ? { ...support, app: false } : support;
|
|
33
|
+
}
|
|
34
|
+
|
|
29
35
|
export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} } = {}) {
|
|
30
36
|
const limitations = [], budgets = {}, caps = [], consumers = [...app.map(model => ({ model, app: true })), ...code.map(model => ({ model, app: false }))];
|
|
31
37
|
let context = 0, output = 0, safeContext = consumers.length > 0, knownAdapters = true;
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -39,6 +39,25 @@ function send(res, code, value) {
|
|
|
39
39
|
res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
|
|
40
40
|
}
|
|
41
41
|
const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
|
|
42
|
+
const MAX_TERMINAL_DRAIN_BYTES = 64 * 1024;
|
|
43
|
+
const TERMINAL_DRAIN_TIMEOUT_MS = 1000;
|
|
44
|
+
async function drainAfterMessageStop(reader) {
|
|
45
|
+
let bytes = 0, ended = false;
|
|
46
|
+
const cancel = () => { try { void reader.cancel().catch(() => {}); } catch {} };
|
|
47
|
+
const timer = setTimeout(cancel, TERMINAL_DRAIN_TIMEOUT_MS);timer.unref?.();
|
|
48
|
+
try {
|
|
49
|
+
while (true) {
|
|
50
|
+
const { done, value } = await reader.read();
|
|
51
|
+
if (done) { ended = true;break; }
|
|
52
|
+
bytes += value.byteLength;
|
|
53
|
+
if (bytes > MAX_TERMINAL_DRAIN_BYTES) break;
|
|
54
|
+
}
|
|
55
|
+
} catch { /* The response has already ended for the client. */ }
|
|
56
|
+
finally {
|
|
57
|
+
clearTimeout(timer);if (!ended) cancel();
|
|
58
|
+
try { reader.releaseLock(); } catch {}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
42
61
|
const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
|
|
43
62
|
|| typeof block.text === "string" && block.text.length || typeof block.thinking === "string" && block.thinking.length));
|
|
44
63
|
function authenticated(headers, key) {
|
|
@@ -51,6 +70,7 @@ function authenticated(headers, key) {
|
|
|
51
70
|
// other frames retain their wire text. Client backpressure controls upstream reads.
|
|
52
71
|
export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clientModel = null) {
|
|
53
72
|
const decoder = new TextDecoder("utf-8", { fatal: true });let fragments = [], lineBytes = 0, data = [], frameBytes = 0, wire = [], wireBytes = 0, output = [];
|
|
73
|
+
let pendingCR = false, bareCR = false, optionalLF = false;
|
|
54
74
|
const frame = () => {
|
|
55
75
|
let value;
|
|
56
76
|
if (data.length) { try { value = JSON.parse(data.join("\n")); } catch { throw new Error("Invalid Claude stream event"); }onEvent(value); }
|
|
@@ -60,16 +80,16 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
|
|
|
60
80
|
wire = wire.map(line => {
|
|
61
81
|
if (!line.startsWith("data:")) return line;
|
|
62
82
|
if (replaced) return "";replaced = true;
|
|
63
|
-
return `data: ${replacement}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : ""}`;
|
|
83
|
+
return `data: ${replacement}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : line.endsWith("\r") ? "\r" : ""}`;
|
|
64
84
|
});
|
|
65
85
|
}
|
|
66
86
|
output.push(Buffer.from(wire.join("")));wire = [];wireBytes = 0;
|
|
67
87
|
}
|
|
68
88
|
data = [];frameBytes = 0;
|
|
69
89
|
};
|
|
70
|
-
const line = (value, newline = true) => {
|
|
90
|
+
const line = (value, newline = true, bytes) => {
|
|
71
91
|
{
|
|
72
|
-
wireBytes += Buffer.byteLength(value) + (newline ? 1 : 0);
|
|
92
|
+
wireBytes += (bytes ?? Buffer.byteLength(value)) + (newline ? 1 : 0);
|
|
73
93
|
if (wireBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");
|
|
74
94
|
wire.push(value + (newline ? "\n" : ""));
|
|
75
95
|
}
|
|
@@ -87,19 +107,63 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
|
|
|
87
107
|
if (frameBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");data.push(part);
|
|
88
108
|
}
|
|
89
109
|
};
|
|
110
|
+
const completeLine = ending => { line(fragments.join("") + (ending.startsWith("\r") ? "\r" : ""), ending.endsWith("\n"));fragments = [];lineBytes = 0; };
|
|
90
111
|
function consume(text) {
|
|
91
112
|
let start = 0;
|
|
113
|
+
if (!bareCR && text.length) {
|
|
114
|
+
const tailCR = fragments.at(-1)?.endsWith("\r") === true;
|
|
115
|
+
if (tailCR && text[0] !== "\n") {
|
|
116
|
+
bareCR = true;
|
|
117
|
+
fragments[fragments.length - 1] = fragments.at(-1).slice(0, -1);lineBytes--;
|
|
118
|
+
completeLine("\r");
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!bareCR) {
|
|
122
|
+
let nextCR = text.indexOf("\r", start);
|
|
123
|
+
while (start < text.length) {
|
|
124
|
+
const newline = text.indexOf("\n", start), end = newline < 0 ? text.length : newline, part = text.slice(start, end);
|
|
125
|
+
if (nextCR >= 0 && nextCR < end - 1) { bareCR = true;break; }
|
|
126
|
+
lineBytes += Buffer.byteLength(part);
|
|
127
|
+
if (lineBytes > maxBytes || wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
|
|
128
|
+
fragments.push(part);
|
|
129
|
+
if (newline < 0) break;
|
|
130
|
+
line(fragments.length === 1 ? fragments[0] : fragments.join(""), true, lineBytes);
|
|
131
|
+
fragments = [];lineBytes = 0;start = newline + 1;
|
|
132
|
+
if (nextCR >= 0 && nextCR === end - 1) nextCR = text.indexOf("\r", start);
|
|
133
|
+
}
|
|
134
|
+
if (!bareCR) return;
|
|
135
|
+
}
|
|
136
|
+
if (optionalLF) {
|
|
137
|
+
optionalLF = false;
|
|
138
|
+
if (text.startsWith("\n")) { output.push(Buffer.from("\n"));start = 1; }
|
|
139
|
+
}
|
|
140
|
+
if (pendingCR && start < text.length) {
|
|
141
|
+
pendingCR = false;
|
|
142
|
+
if (text[start] === "\n") { completeLine("\r\n");start++; }
|
|
143
|
+
else { bareCR = true;completeLine("\r"); }
|
|
144
|
+
}
|
|
92
145
|
while (start < text.length) {
|
|
93
|
-
const
|
|
146
|
+
const lf = text.indexOf("\n", start), cr = text.indexOf("\r", start);
|
|
147
|
+
const end = lf < 0 ? (cr < 0 ? text.length : cr) : cr < 0 ? lf : Math.min(lf, cr);
|
|
148
|
+
const part = text.slice(start, end);
|
|
94
149
|
lineBytes += Buffer.byteLength(part);
|
|
95
150
|
if (lineBytes > maxBytes || wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
|
|
96
151
|
fragments.push(part);
|
|
97
|
-
if (
|
|
98
|
-
|
|
152
|
+
if (end === text.length) break;
|
|
153
|
+
if (text[end] === "\n") { completeLine("\n");start = end + 1;continue; }
|
|
154
|
+
if (end + 1 === text.length) {
|
|
155
|
+
if (bareCR && lineBytes === 0) { completeLine("\r");optionalLF = true; }
|
|
156
|
+
else pendingCR = true;
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
if (text[end + 1] === "\n") { completeLine("\r\n");start = end + 2; }
|
|
160
|
+
else { bareCR = true;completeLine("\r");start = end + 1; }
|
|
99
161
|
}
|
|
100
162
|
}
|
|
101
163
|
return { write(chunk) { output = [];consume(decoder.decode(chunk, { stream: true }));return output; },
|
|
102
|
-
finish() { output = [];consume(decoder.decode());if (
|
|
164
|
+
finish() { output = [];consume(decoder.decode());if (pendingCR) { pendingCR = false;completeLine("\r"); }
|
|
165
|
+
if (!bareCR && fragments.at(-1)?.endsWith("\r")) { fragments[fragments.length - 1] = fragments.at(-1).slice(0, -1);lineBytes--;completeLine("\r"); }
|
|
166
|
+
if (fragments.length) completeLine("");if (wire.length) wire.push("\n\n");frame();return output; } };
|
|
103
167
|
}
|
|
104
168
|
|
|
105
169
|
export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
|
|
@@ -261,6 +325,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
261
325
|
if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
|
|
262
326
|
}, config.maxSseBufferBytes, clientModel);
|
|
263
327
|
const reader = upstream.body.getReader();
|
|
328
|
+
let draining = false;
|
|
264
329
|
try {
|
|
265
330
|
while (true) {
|
|
266
331
|
const { value, done } = await reader.read();if (done) break;
|
|
@@ -276,7 +341,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
276
341
|
for (const chunk of tail) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
|
|
277
342
|
if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
|
|
278
343
|
if (!res.writableEnded) res.end();
|
|
279
|
-
|
|
344
|
+
if (sawStop && !failedEvent && !abort.signal.aborted && !res.destroyed) {
|
|
345
|
+
draining = true;void drainAfterMessageStop(reader);
|
|
346
|
+
}
|
|
347
|
+
} finally {
|
|
348
|
+
if (!draining) { await reader.cancel().catch(() => {});reader.releaseLock(); }
|
|
349
|
+
}
|
|
280
350
|
}
|
|
281
351
|
} catch (error) {
|
|
282
352
|
rejectionReason = error.jsonBody?.error?.reason || (error.code === "ccdx_client_source_disabled" ? error.code : undefined);
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { atomicWriteFile } from "./atomic-file.mjs";
|
|
5
|
+
import { readBoundedFile } from "./bounded-file.mjs";
|
|
6
|
+
import { userSettingsPath } from "./user-settings.mjs";
|
|
7
|
+
|
|
8
|
+
const MAX_METADATA_BYTES = 64 * 1024;
|
|
9
|
+
const validVersion = value => typeof value === "string" && /^[0-9][0-9A-Za-z.+_-]{0,63}$/.test(value);
|
|
10
|
+
const optionalVersion = value => value == null || validVersion(value);
|
|
11
|
+
const validDate = value => value == null || typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(value);
|
|
12
|
+
const fields = (value, allowed) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => allowed.includes(key));
|
|
13
|
+
const validEntry = value => fields(value, ["version", "build", "cli_version", "previous", "changed_at"])
|
|
14
|
+
&& validVersion(value.version) && optionalVersion(value.build) && optionalVersion(value.cli_version)
|
|
15
|
+
&& validDate(value.changed_at) && (value.previous == null || fields(value.previous, ["version", "build", "cli_version"])
|
|
16
|
+
&& validVersion(value.previous.version) && optionalVersion(value.previous.build) && optionalVersion(value.previous.cli_version));
|
|
17
|
+
const changed = (left, right) => left.version !== right.version
|
|
18
|
+
|| Boolean(left.build && right.build && left.build !== right.build)
|
|
19
|
+
|| Boolean(left.cli_version && right.cli_version && left.cli_version !== right.cli_version);
|
|
20
|
+
const sameFile = (left, right) => left.size === right.size && left.mtimeMs === right.mtimeMs && left.ino === right.ino && left.dev === right.dev;
|
|
21
|
+
const installed = value => ({ version: value.version, build: value.build || null, cli_version: value.cli_version || null });
|
|
22
|
+
const tag = (text, key) => new RegExp(`<key>${key}</key>\\s*<(string|integer)>([^<]+)</\\1>`).exec(text)?.[2]?.trim();
|
|
23
|
+
|
|
24
|
+
async function stableRead(file) {
|
|
25
|
+
const before = await fs.stat(file), data = await readBoundedFile(file, { maxBytes: MAX_METADATA_BYTES, encoding: "utf8" }), after = await fs.stat(file);
|
|
26
|
+
if (!sameFile(before, after)) throw new Error("App metadata changed during inspection");
|
|
27
|
+
return { data, identity: after };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function macBundle(root, scope, name, client) {
|
|
31
|
+
const bundle = path.join(root, name), infoPath = path.join(bundle, "Contents", "Info.plist"), info = await stableRead(infoPath), plist = info.data;
|
|
32
|
+
const expected = client === "codex" ? "com.openai.codex" : "com.anthropic.claudefordesktop";
|
|
33
|
+
const version = tag(plist, "CFBundleShortVersionString"), build = tag(plist, "CFBundleVersion");
|
|
34
|
+
if (tag(plist, "CFBundleIdentifier") !== expected || !validVersion(version) || !optionalVersion(build)) return null;
|
|
35
|
+
let cliVersion = null;
|
|
36
|
+
if (client === "codex") try {
|
|
37
|
+
const metadata = JSON.parse((await stableRead(path.join(bundle, "Contents", "Resources", "codex-cli", "codex-package.json"))).data);
|
|
38
|
+
if (validVersion(metadata.version)) cliVersion = metadata.version;
|
|
39
|
+
} catch { /* Older App bundles need not provide CLI metadata. */ }
|
|
40
|
+
if (client === "codex" && !sameFile(info.identity, await fs.stat(infoPath))) return null;
|
|
41
|
+
return { id: `${client}_${scope}_${name.slice(0, -4).toLowerCase()}`, name, client, scope, version, build: build || null, cli_version: cliVersion };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function inspectInstalledClientVersions({ home = os.homedir(), env = process.env, platform = process.platform,
|
|
45
|
+
systemApplications = "/Applications", windowsCodexVersion } = {}) {
|
|
46
|
+
if (platform === "darwin") {
|
|
47
|
+
const roots = [["system", systemApplications], ["user", path.join(home, "Applications")]], jobs = [];
|
|
48
|
+
for (const [scope, root] of roots) for (const [name, client] of [["ChatGPT.app", "codex"], ["Codex.app", "codex"], ["Claude.app", "claude"]]) {
|
|
49
|
+
jobs.push(macBundle(root, scope, name, client).catch(() => null));
|
|
50
|
+
}
|
|
51
|
+
return (await Promise.all(jobs)).filter(Boolean);
|
|
52
|
+
}
|
|
53
|
+
if (platform === "win32") {
|
|
54
|
+
const inspect = windowsCodexVersion || (await import("./native-prediction-windows.mjs")).inspectWindowsCodexVersion;
|
|
55
|
+
const version = await inspect({ env }).catch(() => null);
|
|
56
|
+
return validVersion(version) ? [{ id: "codex_windows_codex", name: "Codex", client: "codex", scope: "windows", version, build: null, cli_version: null }] : [];
|
|
57
|
+
}
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function createClientVersionMonitor({ home = os.homedir(), env = process.env, platform = process.platform,
|
|
62
|
+
inspect = inspectInstalledClientVersions, persist = true, timeoutMs = 3000, now = Date.now, onChange = () => {}, ...options } = {}) {
|
|
63
|
+
const file = path.join(path.dirname(userSettingsPath({ home, env })), "client-versions.json");
|
|
64
|
+
let saved, writable = true, flight = null, closed = false;
|
|
65
|
+
let state = { checked_at: null, codex: [], claude: [], claude_unrecognized: false, persistence: "unknown" };
|
|
66
|
+
const snapshot = () => structuredClone(state);
|
|
67
|
+
async function load() {
|
|
68
|
+
if (saved) return saved;
|
|
69
|
+
try {
|
|
70
|
+
const value = JSON.parse(await readBoundedFile(file, { maxBytes: MAX_METADATA_BYTES, encoding: "utf8" }));
|
|
71
|
+
if (!fields(value, ["version", "apps"]) || value.version !== 1 || !value.apps || typeof value.apps !== "object" || Array.isArray(value.apps)
|
|
72
|
+
|| Object.entries(value.apps).length > 7 || Object.entries(value.apps).some(([id, entry]) =>
|
|
73
|
+
!/^(?:codex|claude)_(?:system|user|windows)_(?:chatgpt|codex|claude)$/.test(id) || !validEntry(entry))) throw new Error("Invalid saved App versions");
|
|
74
|
+
saved = value.apps;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error.code !== "ENOENT") writable = false;
|
|
77
|
+
saved = {};
|
|
78
|
+
}
|
|
79
|
+
return saved;
|
|
80
|
+
}
|
|
81
|
+
async function run() {
|
|
82
|
+
const baseline = await load(), rows = await inspect({ home, env, platform, ...options });
|
|
83
|
+
if (!Array.isArray(rows) || rows.length > 7) throw new Error("Invalid App version results");
|
|
84
|
+
const at = new Date(now()).toISOString(), next = { ...baseline }, updates = [];
|
|
85
|
+
const groups = { codex: [], claude: [] };
|
|
86
|
+
for (const row of rows) {
|
|
87
|
+
if (!/^(?:codex|claude)_(?:system|user|windows)_(?:chatgpt|codex|claude)$/.test(row.id || "")
|
|
88
|
+
|| !["codex", "claude"].includes(row.client) || !validVersion(row.version) || !optionalVersion(row.build) || !optionalVersion(row.cli_version)) continue;
|
|
89
|
+
const current = installed(row), previous = baseline[row.id];let entry;
|
|
90
|
+
if (!previous) entry = { ...current, previous: null, changed_at: null };
|
|
91
|
+
else if (changed(previous, current)) {
|
|
92
|
+
entry = { ...current, previous: installed(previous), changed_at: at };updates.push(row.client);
|
|
93
|
+
} else entry = { ...current, build: current.build || previous.build || null, cli_version: current.cli_version || previous.cli_version || null,
|
|
94
|
+
previous: previous.previous || null, changed_at: previous.changed_at || null };
|
|
95
|
+
next[row.id] = entry;
|
|
96
|
+
groups[row.client].push({ id: row.id, name: row.name, scope: row.scope, ...entry, ...current, first_observed: !previous });
|
|
97
|
+
}
|
|
98
|
+
if (closed) return snapshot();
|
|
99
|
+
const modified = JSON.stringify(next) !== JSON.stringify(baseline);
|
|
100
|
+
saved = next;
|
|
101
|
+
const observed = { checked_at: at, ...groups, claude_unrecognized: Boolean(next.claude_system_claude?.version && !/^[34]\./.test(next.claude_system_claude.version)) };
|
|
102
|
+
state = { ...observed, persistence: persist ? writable && modified ? "pending" : writable ? "saved" : "unavailable" : "read_only" };
|
|
103
|
+
if (updates.length) try { onChange([...new Set(updates)], snapshot()); } catch { /* Display only. */ }
|
|
104
|
+
if (persist && writable && modified) try {
|
|
105
|
+
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
106
|
+
if (!closed) await atomicWriteFile(file, `${JSON.stringify({ version: 1, apps: next })}\n`, { mode: 0o600, preserveMode: false });
|
|
107
|
+
} catch { writable = false; }
|
|
108
|
+
if (!closed) state = { ...observed, persistence: persist ? writable ? "saved" : "unavailable" : "read_only" };
|
|
109
|
+
return snapshot();
|
|
110
|
+
}
|
|
111
|
+
function refresh() {
|
|
112
|
+
if (closed) return Promise.resolve(snapshot());
|
|
113
|
+
if (flight) return flight.result;
|
|
114
|
+
let timer, task;
|
|
115
|
+
const work = Promise.resolve().then(run);
|
|
116
|
+
const timeout = new Promise(resolve => { timer = setTimeout(() => resolve(null), timeoutMs); });
|
|
117
|
+
const result = Promise.race([work, timeout]).then(value => {
|
|
118
|
+
if (value) return value;
|
|
119
|
+
state = { ...state, checked_at: new Date(now()).toISOString(), codex: [], claude: [], persistence: "unavailable" };
|
|
120
|
+
return snapshot();
|
|
121
|
+
}).catch(() => {
|
|
122
|
+
state = { ...state, checked_at: new Date(now()).toISOString(), codex: [], claude: [], persistence: "unavailable" };
|
|
123
|
+
return snapshot();
|
|
124
|
+
}).finally(() => clearTimeout(timer));
|
|
125
|
+
task = { result };flight = task;
|
|
126
|
+
work.finally(() => { if (flight === task) flight = null; }).catch(() => {});
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
return { snapshot, refresh, close() { closed = true; } };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function clientVersionChecks(snapshot) {
|
|
133
|
+
return ["codex", "claude"].map(client => {
|
|
134
|
+
const rows = snapshot?.[client] || [], name = client === "codex" ? "Codex App" : "Claude App";
|
|
135
|
+
if (!rows.length) return { id: "client-versions", kind: "info", message: `${name}: installed version not observed` };
|
|
136
|
+
const versions = rows.map(row => `${row.name} ${row.version}${row.build ? ` (build ${row.build})` : ""}${row.cli_version ? `, CLI ${row.cli_version}` : ""}${row.changed_at ? `, changed ${row.changed_at}` : ""}`).join("; ");
|
|
137
|
+
return { id: "client-versions", kind: "info", message: `${name}: ${versions}. Running version and feature compatibility are not confirmed` };
|
|
138
|
+
});
|
|
139
|
+
}
|
|
@@ -75,7 +75,9 @@ export async function inspectCodexClient({
|
|
|
75
75
|
} else if (observed) {
|
|
76
76
|
const version = /^[0-9]+\.[0-9]+\.[0-9]+$/.test(observed.client_version || "") ? observed.client_version : "unknown";
|
|
77
77
|
const app = ["ChatGPT.app", "Codex.app", "custom binary"].includes(observed.application) ? observed.application : "unknown App";
|
|
78
|
-
|
|
78
|
+
const source = observed.source === "cached_bundled" ? "previously verified bundled" : observed.source === "bundled" ? "bundled" : "unavailable";
|
|
79
|
+
const precision = observed.match_precision === "exact" ? "exact version" : observed.match_precision === "core_only" ? "base version only" : "not specified";
|
|
80
|
+
checks.push({ kind: "info", message: `Last catalog request: client ${version}, ${app}, ${source}; version match ${observed.matched === true ? "observed" : "not verified"} (${precision})` });
|
|
79
81
|
} else checks.push({ kind: "info", message: "No client model-catalog request observed by this adapter" });
|
|
80
82
|
} catch { checks.push({ kind: "info", message: "Client model-catalog diagnostics unavailable from the running adapter" }); }
|
|
81
83
|
}
|