codex-copilot-dx 1.3.19 → 1.3.20
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 +22 -2
- package/docs/ARCHITECTURE.md +8 -0
- package/docs/REFERENCE.md +5 -0
- package/package.json +1 -1
- package/src/adapter.mjs +3 -3
- package/src/claude-capability-config.mjs +6 -0
- package/src/claude-gateway.mjs +52 -7
- 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-runtime.mjs +10 -2
- 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/responses-proxy.mjs +95 -27
- package/src/service-control.mjs +7 -1
- 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
|
@@ -315,6 +315,19 @@ let clientIntegration = null;
|
|
|
315
315
|
let providerRuntime = null;
|
|
316
316
|
let terminalConsole = null;
|
|
317
317
|
const webUiUrl = `http://${ADAPTER_HOST === "::1" ? "[::1]" : "127.0.0.1"}:${ADAPTER_PORT}`;
|
|
318
|
+
let versionMonitor = null, versionModule = null;
|
|
319
|
+
const clientVersions = {
|
|
320
|
+
snapshot: () => versionMonitor?.snapshot() || null,
|
|
321
|
+
refresh() {
|
|
322
|
+
if (shuttingDown || serviceWorker?.warming || serviceWorker?.draining || serviceWorker?.preserving) return Promise.resolve(clientVersions.snapshot());
|
|
323
|
+
versionModule ||= import("../src/client-versions.mjs").then(({ createClientVersionMonitor }) => {
|
|
324
|
+
if (shuttingDown) return null;
|
|
325
|
+
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`)) });
|
|
326
|
+
return versionMonitor;
|
|
327
|
+
}).catch(error => { versionModule = null;throw error; });
|
|
328
|
+
return versionModule.then(monitor => monitor?.refresh());
|
|
329
|
+
},
|
|
330
|
+
};
|
|
318
331
|
async function launchDashboard() {
|
|
319
332
|
try {
|
|
320
333
|
const result = await openDashboard(webUiUrl, { enabled: !CLI.noBrowser && servicePreferences().open_webui });
|
|
@@ -349,6 +362,8 @@ async function reuseRunningAdapterIfAvailable() {
|
|
|
349
362
|
}
|
|
350
363
|
if (!running.ok) return false;
|
|
351
364
|
|
|
365
|
+
void fetch(`${webUiUrl}/_ccdx/ui/settings`, { method: "POST", headers: { "X-CCDX-Dashboard": "1", Origin: webUiUrl, "Content-Type": "application/json" },
|
|
366
|
+
body: JSON.stringify({ action: "client_versions" }), signal: AbortSignal.timeout(1000) }).catch(() => {});
|
|
352
367
|
const serviceStatus = readAdapterStatus({ host: ADAPTER_HOST, port: ADAPTER_PORT }).catch(() => null);
|
|
353
368
|
console.log(startupCheck("ok", "Service", `Using running service: ${running.baseUrl}`));
|
|
354
369
|
console.log(startupCheck("info", "Sign-in", "Using saved sign-in; not rechecked"));
|
|
@@ -455,6 +470,7 @@ try {
|
|
|
455
470
|
providerRuntime = createProviderRuntime({ githubClient: profileRuntime.codexClient, githubRegistry: profileModels.codexRegistry,
|
|
456
471
|
refreshGithubCatalog: () => profileModels.refreshCodex({ strict: true }),
|
|
457
472
|
corePort: ADAPTER_PORT, preserveClientConfiguration: () => serviceWorker?.preserving === true || serviceWorker?.draining === true,
|
|
473
|
+
clientVersionsSnapshot: clientVersions.snapshot,
|
|
458
474
|
clientAccessChanged: async enabled => { earlyIntegration.setPredictionActive(enabled && servicePreferences().prediction_enabled);if (enabled) await earlyIntegration.configure(); },
|
|
459
475
|
githubCredentialFingerprint: () => profileRuntime.codexCredentialFingerprint,
|
|
460
476
|
log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "M365", message)) });
|
|
@@ -498,7 +514,7 @@ try {
|
|
|
498
514
|
snapshot: () => activeServer?.ccdxSnapshot?.() || {},
|
|
499
515
|
subscribe: listener => activeServer?.ccdxSubscribeActivity?.(listener),
|
|
500
516
|
preferences: () => { const { saved, theme, color_theme } = serviceSettingsSnapshot();return { ...saved, theme, color_theme }; } });
|
|
501
|
-
const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole,
|
|
517
|
+
const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole, clientVersions,
|
|
502
518
|
adapterPort: ADAPTER_PORT, adapterHost: ADAPTER_HOST, manualUpdate: serviceWorker ? () => serviceWorker.requestUpdate() : undefined,
|
|
503
519
|
nightlyStatus: () => serviceWorker?.status() || null, nightlyChanged: enabled => serviceWorker?.preferenceChanged(enabled) });
|
|
504
520
|
const codexModelCatalog = createCodexModelCatalog();
|
|
@@ -516,7 +532,7 @@ try {
|
|
|
516
532
|
terminalAnimationTheme,
|
|
517
533
|
terminalActivity: terminalConsole,
|
|
518
534
|
handoffState: serviceWorker?.takeState(), isDraining: () => serviceWorker?.draining === true,
|
|
519
|
-
dashboardOptions: { serviceControl, host: ADAPTER_HOST, port: ADAPTER_PORT,
|
|
535
|
+
dashboardOptions: { serviceControl, clientVersions, host: ADAPTER_HOST, port: ADAPTER_PORT,
|
|
520
536
|
credentialsChanged: () => { defaultCopilotClient.invalidateCredentials();profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient }); },
|
|
521
537
|
applyAnimation: theme => terminalConsole.apply({ theme }) },
|
|
522
538
|
nativePredictionPac: () => clientIntegration?.pacUrl() || null,
|
|
@@ -547,12 +563,14 @@ try {
|
|
|
547
563
|
modelRefreshTimer = setInterval(() => {
|
|
548
564
|
if (providerRuntime.selection().codex === "github") profileModels.refreshAll().then(() => providerRuntime.selection().codex === "github" && providerRuntime.syncClients(["codex"])).catch(() => {});
|
|
549
565
|
providerRuntime.refresh().catch(() => {});
|
|
566
|
+
void clientVersions.refresh().catch(() => {});
|
|
550
567
|
}, refreshIntervalMs);
|
|
551
568
|
modelRefreshTimer.unref?.();
|
|
552
569
|
}
|
|
553
570
|
|
|
554
571
|
startupComplete = true;
|
|
555
572
|
if (!startupPresentation.enabled) console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
|
|
573
|
+
void clientVersions.refresh().catch(() => {});
|
|
556
574
|
runInBackground(printUpdateNotice);
|
|
557
575
|
await launchDashboard();
|
|
558
576
|
if (!serviceWorker?.warming) {
|
|
@@ -569,6 +587,7 @@ try {
|
|
|
569
587
|
let exitCode = 0;
|
|
570
588
|
try {
|
|
571
589
|
if (modelRefreshTimer) clearInterval(modelRefreshTimer);
|
|
590
|
+
versionMonitor?.close();
|
|
572
591
|
const result = await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });
|
|
573
592
|
if (result.forced) console.warn(status("warn", "Remaining service connections closed"));
|
|
574
593
|
await clientIntegration?.close();
|
|
@@ -612,6 +631,7 @@ try {
|
|
|
612
631
|
await LOGGING.cleanup();try { LOGGING = configureLogging(); } catch { LOGGING = configureLogging({ env: { ...process.env, CCDX_LOG_PATH: "" } }); }
|
|
613
632
|
terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
|
|
614
633
|
earlyIntegration.retireImages();
|
|
634
|
+
setImmediate(() => void clientVersions.refresh().catch(() => {}));
|
|
615
635
|
},
|
|
616
636
|
inspect: () => {
|
|
617
637
|
const data = activeServer.ccdxSnapshot(), routes = data.requests.by_route;
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -1132,3 +1132,11 @@ The image and input-suggestion panels share `codex-launch-control.mjs`. `codex-a
|
|
|
1132
1132
|
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
1133
|
|
|
1134
1134
|
`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.
|
|
1135
|
+
|
|
1136
|
+
## Client updates and streaming boundaries (1.3.20)
|
|
1137
|
+
|
|
1138
|
+
`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.
|
|
1139
|
+
|
|
1140
|
+
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.
|
|
1141
|
+
|
|
1142
|
+
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.
|
|
@@ -756,6 +759,8 @@ 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, 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.
|
|
763
|
+
|
|
759
764
|
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
765
|
|
|
761
766
|
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.
|
package/package.json
CHANGED
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
|
@@ -51,6 +51,7 @@ function authenticated(headers, key) {
|
|
|
51
51
|
// other frames retain their wire text. Client backpressure controls upstream reads.
|
|
52
52
|
export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clientModel = null) {
|
|
53
53
|
const decoder = new TextDecoder("utf-8", { fatal: true });let fragments = [], lineBytes = 0, data = [], frameBytes = 0, wire = [], wireBytes = 0, output = [];
|
|
54
|
+
let pendingCR = false, bareCR = false, optionalLF = false;
|
|
54
55
|
const frame = () => {
|
|
55
56
|
let value;
|
|
56
57
|
if (data.length) { try { value = JSON.parse(data.join("\n")); } catch { throw new Error("Invalid Claude stream event"); }onEvent(value); }
|
|
@@ -60,16 +61,16 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
|
|
|
60
61
|
wire = wire.map(line => {
|
|
61
62
|
if (!line.startsWith("data:")) return line;
|
|
62
63
|
if (replaced) return "";replaced = true;
|
|
63
|
-
return `data: ${replacement}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : ""}`;
|
|
64
|
+
return `data: ${replacement}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : line.endsWith("\r") ? "\r" : ""}`;
|
|
64
65
|
});
|
|
65
66
|
}
|
|
66
67
|
output.push(Buffer.from(wire.join("")));wire = [];wireBytes = 0;
|
|
67
68
|
}
|
|
68
69
|
data = [];frameBytes = 0;
|
|
69
70
|
};
|
|
70
|
-
const line = (value, newline = true) => {
|
|
71
|
+
const line = (value, newline = true, bytes) => {
|
|
71
72
|
{
|
|
72
|
-
wireBytes += Buffer.byteLength(value) + (newline ? 1 : 0);
|
|
73
|
+
wireBytes += (bytes ?? Buffer.byteLength(value)) + (newline ? 1 : 0);
|
|
73
74
|
if (wireBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");
|
|
74
75
|
wire.push(value + (newline ? "\n" : ""));
|
|
75
76
|
}
|
|
@@ -87,19 +88,63 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
|
|
|
87
88
|
if (frameBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");data.push(part);
|
|
88
89
|
}
|
|
89
90
|
};
|
|
91
|
+
const completeLine = ending => { line(fragments.join("") + (ending.startsWith("\r") ? "\r" : ""), ending.endsWith("\n"));fragments = [];lineBytes = 0; };
|
|
90
92
|
function consume(text) {
|
|
91
93
|
let start = 0;
|
|
94
|
+
if (!bareCR && text.length) {
|
|
95
|
+
const tailCR = fragments.at(-1)?.endsWith("\r") === true;
|
|
96
|
+
if (tailCR && text[0] !== "\n") {
|
|
97
|
+
bareCR = true;
|
|
98
|
+
fragments[fragments.length - 1] = fragments.at(-1).slice(0, -1);lineBytes--;
|
|
99
|
+
completeLine("\r");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (!bareCR) {
|
|
103
|
+
let nextCR = text.indexOf("\r", start);
|
|
104
|
+
while (start < text.length) {
|
|
105
|
+
const newline = text.indexOf("\n", start), end = newline < 0 ? text.length : newline, part = text.slice(start, end);
|
|
106
|
+
if (nextCR >= 0 && nextCR < end - 1) { bareCR = true;break; }
|
|
107
|
+
lineBytes += Buffer.byteLength(part);
|
|
108
|
+
if (lineBytes > maxBytes || wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
|
|
109
|
+
fragments.push(part);
|
|
110
|
+
if (newline < 0) break;
|
|
111
|
+
line(fragments.length === 1 ? fragments[0] : fragments.join(""), true, lineBytes);
|
|
112
|
+
fragments = [];lineBytes = 0;start = newline + 1;
|
|
113
|
+
if (nextCR >= 0 && nextCR === end - 1) nextCR = text.indexOf("\r", start);
|
|
114
|
+
}
|
|
115
|
+
if (!bareCR) return;
|
|
116
|
+
}
|
|
117
|
+
if (optionalLF) {
|
|
118
|
+
optionalLF = false;
|
|
119
|
+
if (text.startsWith("\n")) { output.push(Buffer.from("\n"));start = 1; }
|
|
120
|
+
}
|
|
121
|
+
if (pendingCR && start < text.length) {
|
|
122
|
+
pendingCR = false;
|
|
123
|
+
if (text[start] === "\n") { completeLine("\r\n");start++; }
|
|
124
|
+
else { bareCR = true;completeLine("\r"); }
|
|
125
|
+
}
|
|
92
126
|
while (start < text.length) {
|
|
93
|
-
const
|
|
127
|
+
const lf = text.indexOf("\n", start), cr = text.indexOf("\r", start);
|
|
128
|
+
const end = lf < 0 ? (cr < 0 ? text.length : cr) : cr < 0 ? lf : Math.min(lf, cr);
|
|
129
|
+
const part = text.slice(start, end);
|
|
94
130
|
lineBytes += Buffer.byteLength(part);
|
|
95
131
|
if (lineBytes > maxBytes || wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
|
|
96
132
|
fragments.push(part);
|
|
97
|
-
if (
|
|
98
|
-
|
|
133
|
+
if (end === text.length) break;
|
|
134
|
+
if (text[end] === "\n") { completeLine("\n");start = end + 1;continue; }
|
|
135
|
+
if (end + 1 === text.length) {
|
|
136
|
+
if (bareCR && lineBytes === 0) { completeLine("\r");optionalLF = true; }
|
|
137
|
+
else pendingCR = true;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
if (text[end + 1] === "\n") { completeLine("\r\n");start = end + 2; }
|
|
141
|
+
else { bareCR = true;completeLine("\r");start = end + 1; }
|
|
99
142
|
}
|
|
100
143
|
}
|
|
101
144
|
return { write(chunk) { output = [];consume(decoder.decode(chunk, { stream: true }));return output; },
|
|
102
|
-
finish() { output = [];consume(decoder.decode());if (
|
|
145
|
+
finish() { output = [];consume(decoder.decode());if (pendingCR) { pendingCR = false;completeLine("\r"); }
|
|
146
|
+
if (!bareCR && fragments.at(-1)?.endsWith("\r")) { fragments[fragments.length - 1] = fragments.at(-1).slice(0, -1);lineBytes--;completeLine("\r"); }
|
|
147
|
+
if (fragments.length) completeLine("");if (wire.length) wire.push("\n\n");frame();return output; } };
|
|
103
148
|
}
|
|
104
149
|
|
|
105
150
|
export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
|
|
@@ -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
|
}
|
|
@@ -260,6 +260,8 @@ export function createCodexModelCatalog({
|
|
|
260
260
|
const versionFailures = new Map();
|
|
261
261
|
const versionPending = new Map();
|
|
262
262
|
const catalogCache = new Map();
|
|
263
|
+
const exactCatalogCache = new Map();
|
|
264
|
+
const ambiguousVersions = new Set();
|
|
263
265
|
const catalogFailures = new Map();
|
|
264
266
|
const catalogPending = new Map();
|
|
265
267
|
let activeBinaryKeys = new Set();
|
|
@@ -280,8 +282,8 @@ export function createCodexModelCatalog({
|
|
|
280
282
|
const promise = (async () => {
|
|
281
283
|
try {
|
|
282
284
|
const stdout = await runCodexCommand(execFileFn, candidate.binaryPath, ["--version"], commandOptions);
|
|
283
|
-
const version =
|
|
284
|
-
if (!version) throw new Error("Invalid Codex version output");
|
|
285
|
+
const version = parsedCodexVersion(stdout);
|
|
286
|
+
if (!wholeSemver(version)) throw new Error("Invalid Codex version output");
|
|
285
287
|
if (activeBinaryKeys.has(candidate.key)) {
|
|
286
288
|
versionCache.set(candidate.key, version);
|
|
287
289
|
versionFailures.delete(candidate.key);
|
|
@@ -313,8 +315,10 @@ export function createCodexModelCatalog({
|
|
|
313
315
|
if (!rawVersion) return installed[0];
|
|
314
316
|
const expectedVersion = wholeSemver(rawVersion);
|
|
315
317
|
if (!expectedVersion) return null;
|
|
318
|
+
const exact = rawVersion !== expectedVersion;
|
|
316
319
|
for (const candidate of installed) {
|
|
317
|
-
|
|
320
|
+
const version = await probeVersion(candidate);
|
|
321
|
+
if (version && (exact ? version === rawVersion : wholeSemver(version) === expectedVersion)) return { ...candidate, fullVersion: version, precision: exact ? "exact" : "core_only" };
|
|
318
322
|
}
|
|
319
323
|
return null;
|
|
320
324
|
}
|
|
@@ -356,14 +360,33 @@ export function createCodexModelCatalog({
|
|
|
356
360
|
}
|
|
357
361
|
|
|
358
362
|
async function load({ clientVersion = "" } = {}) {
|
|
363
|
+
const requested = String(clientVersion || "").trim(), core = wholeSemver(requested);
|
|
364
|
+
const exact = Boolean(core && requested !== core);
|
|
359
365
|
const candidate = await selectBinary(clientVersion);
|
|
360
|
-
|
|
361
|
-
|
|
366
|
+
let catalog = candidate ? await loadCatalog(candidate) : null;
|
|
367
|
+
let app = candidate?.binaryPath.match(/(?:^|\/)(ChatGPT|Codex)\.app\//)?.[1];
|
|
368
|
+
let source = catalog ? "bundled" : "unavailable";
|
|
369
|
+
if (candidate && catalog && exact && !ambiguousVersions.has(requested)) {
|
|
370
|
+
const previous = exactCatalogCache.get(requested);
|
|
371
|
+
if (previous && previous.key !== candidate.key) {
|
|
372
|
+
exactCatalogCache.delete(requested);ambiguousVersions.add(requested);
|
|
373
|
+
if (ambiguousVersions.size > 8) ambiguousVersions.delete(ambiguousVersions.values().next().value);
|
|
374
|
+
} else if (!previous) try {
|
|
375
|
+
const stats = await statFn(candidate.binaryPath);
|
|
376
|
+
if (stats?.isFile?.() && binaryCacheKey(candidate.binaryPath, stats) === candidate.key) {
|
|
377
|
+
exactCatalogCache.set(requested, { key: candidate.key, catalog, app: app || null });
|
|
378
|
+
while (exactCatalogCache.size > 2) exactCatalogCache.delete(exactCatalogCache.keys().next().value);
|
|
379
|
+
}
|
|
380
|
+
} catch { /* A changing App cannot supply a verified retained catalog. */ }
|
|
381
|
+
} else if (!candidate && exact && exactCatalogCache.has(requested) && !ambiguousVersions.has(requested)) {
|
|
382
|
+
const previous = exactCatalogCache.get(requested);catalog = previous.catalog;app = previous.app;source = "cached_bundled";
|
|
383
|
+
}
|
|
362
384
|
lastObservation = {
|
|
363
|
-
client_version:
|
|
364
|
-
application: app ? `${app}.app` : candidate ? "custom binary" : null,
|
|
365
|
-
source
|
|
366
|
-
matched: Boolean(catalog &&
|
|
385
|
+
client_version: core || null,
|
|
386
|
+
application: app ? `${app}.app` : candidate || source === "cached_bundled" ? "custom binary" : null,
|
|
387
|
+
source,
|
|
388
|
+
matched: Boolean(catalog && core),
|
|
389
|
+
match_precision: catalog && core ? exact ? "exact" : "core_only" : null,
|
|
367
390
|
observed_at: new Date(now()).toISOString(),
|
|
368
391
|
};
|
|
369
392
|
return catalog;
|
|
@@ -371,7 +394,7 @@ export function createCodexModelCatalog({
|
|
|
371
394
|
|
|
372
395
|
return { load, snapshot: () => ({
|
|
373
396
|
last_request: lastObservation ? { ...lastObservation } : null,
|
|
374
|
-
observed_versions: [...new Set(versionCache.values())].slice(0, 8),
|
|
397
|
+
observed_versions: [...new Set([...versionCache.values()].map(wholeSemver).filter(Boolean))].slice(0, 8),
|
|
375
398
|
client_cache_verified: false,
|
|
376
399
|
}) };
|
|
377
400
|
}
|
|
@@ -35,6 +35,7 @@ import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.m
|
|
|
35
35
|
import { currentRequestContext } from "./request-context.mjs";
|
|
36
36
|
import {
|
|
37
37
|
claudeSharedCapabilityPlan,
|
|
38
|
+
claudeSupportForSync,
|
|
38
39
|
syncClaudeCapabilities,
|
|
39
40
|
inspectClaudeCapabilitySupport,
|
|
40
41
|
inspectClaudeCapabilityConfiguration,
|
|
@@ -61,6 +62,7 @@ export function createConnectionRuntime({
|
|
|
61
62
|
inspectDesktop = inspectClaudeDesktopPolicy,
|
|
62
63
|
clientAccessChanged,
|
|
63
64
|
preserveClientConfiguration,
|
|
65
|
+
clientVersionsSnapshot,
|
|
64
66
|
now = Date.now,
|
|
65
67
|
log = () => {},
|
|
66
68
|
} = {}) {
|
|
@@ -105,6 +107,12 @@ export function createConnectionRuntime({
|
|
|
105
107
|
onState: (id, state) => (state ? discoveries.set(id, state) : discoveries.delete(id)),
|
|
106
108
|
});
|
|
107
109
|
const capabilitySupport = inspectClaudeCapabilitySupport(options);
|
|
110
|
+
function capabilitySupportForSync() {
|
|
111
|
+
try {
|
|
112
|
+
return claudeSupportForSync(capabilitySupport, clientVersionsSnapshot?.());
|
|
113
|
+
} catch { /* Optional observations cannot change routing or interrupt synchronization. */ }
|
|
114
|
+
return capabilitySupport;
|
|
115
|
+
}
|
|
108
116
|
let sharedSync = null,
|
|
109
117
|
syncFlight = null,
|
|
110
118
|
syncAgain = false,
|
|
@@ -608,7 +616,7 @@ export function createConnectionRuntime({
|
|
|
608
616
|
const shared = claudeSharedCapabilityPlan({
|
|
609
617
|
app: setup.claude_app === "configured" ? plan("claude_app").models : [],
|
|
610
618
|
code: setup.claude_code === "configured" ? plan("claude_code").models : [],
|
|
611
|
-
support:
|
|
619
|
+
support: capabilitySupportForSync(),
|
|
612
620
|
});
|
|
613
621
|
if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
|
|
614
622
|
sharedSync = {
|
|
@@ -1008,7 +1016,7 @@ export function createConnectionRuntime({
|
|
|
1008
1016
|
: claudeSharedCapabilityPlan({
|
|
1009
1017
|
app: input.id === "claude_app" ? proposed.models : plan("claude_app").models,
|
|
1010
1018
|
code: input.id === "claude_code" ? proposed.models : plan("claude_code").models,
|
|
1011
|
-
support:
|
|
1019
|
+
support: capabilitySupportForSync(),
|
|
1012
1020
|
});
|
|
1013
1021
|
return {
|
|
1014
1022
|
...snapshot(),
|
package/src/dashboard/console.js
CHANGED
|
@@ -8,6 +8,17 @@
|
|
|
8
8
|
let settingsReadAt = null;
|
|
9
9
|
let accountsPending = false;
|
|
10
10
|
const accountReasons = new Set(["m365_account_ambiguous", "m365_account_unavailable", "m365_account_conflict", "m365_interaction_required", "m365_llm_permission_unavailable", "m365_account_busy", "m365_account_selection_stale"]);
|
|
11
|
+
function renderClientVersions(value) {
|
|
12
|
+
for (const client of ["codex", "claude"]) {
|
|
13
|
+
const node = el(`client-version-${client}`);if (!node) continue;
|
|
14
|
+
const rows = Array.isArray(value?.[client]) ? value[client] : [];
|
|
15
|
+
if (!rows.length) { node.removeAttribute("data-i18n");node.textContent = "—";node.title = "";continue; }
|
|
16
|
+
const version = rows.map(row => `${rows.length > 1 ? `${row.name} ` : ""}${row.version}${row.build && row.build !== row.version ? ` (${row.build})` : ""}${row.cli_version ? ` · CLI ${row.cli_version}` : ""}`).join(" / ");
|
|
17
|
+
label(node, rows.some(row => row.changed_at) ? "client_version_changed" : "client_version_observed", { version });
|
|
18
|
+
node.title = rows.filter(row => row.changed_at).map(row => `${row.previous?.version || "—"} → ${row.version} · ${time(row.changed_at, { date: true })}`).join(" / ");
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
globalThis.ccdxClientVersions = { render: renderClientVersions };
|
|
11
22
|
function syncAccountControls() {
|
|
12
23
|
el("m365-accounts-refresh").disabled = accountsPending || settingsPending;
|
|
13
24
|
el("m365-account-choice").disabled = accountsPending || settingsPending;
|
|
@@ -115,6 +126,7 @@
|
|
|
115
126
|
window.addEventListener("ccdx:providers", () => { syncSources();if (current === "codex") void loadSourceModels(); });
|
|
116
127
|
function applySettings(data, meta) {
|
|
117
128
|
globalThis.ccdxPrivacy?.sync(data.local_privacy);
|
|
129
|
+
renderClientVersions(data.client_versions);
|
|
118
130
|
settings = data;
|
|
119
131
|
features?.render(data);
|
|
120
132
|
const nightly = data.nightly_update;
|
|
@@ -194,18 +206,18 @@
|
|
|
194
206
|
}
|
|
195
207
|
finally { settingsPending = false;el("m365-enabled").disabled = !settings;el("terminal-color-theme").disabled = !settings;el("apply-source").disabled = !sourceReady();syncReviewButton();syncAccountControls(); }
|
|
196
208
|
}
|
|
197
|
-
async function change(body, button) {
|
|
209
|
+
async function change(body, button, { quiet = false } = {}) {
|
|
198
210
|
if (settingsPending) return;
|
|
199
211
|
settingsPending = true;
|
|
200
212
|
syncAccountControls();
|
|
201
213
|
const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-enabled, #prediction-continue, #prediction-open, #prediction-setup, #prediction-remove, #image-models input, #image-check, #image-repair, #image-open, #decoded-limit, #decoded-limit-save, #decoded-limit-default, #install-update")];
|
|
202
214
|
controls.forEach(input => { input.disabled = true; });
|
|
203
|
-
const note = el(body.action === "codex_app" ? body.intent === "prediction" ? "prediction-
|
|
215
|
+
const note = el(body.action === "codex_app" ? body.intent === "prediction" ? "prediction-open-note" : "image-action-note" : body.action === "prediction" ? body.operation === "open" ? "prediction-open-note" : "prediction-action-note" : body.action === "image" ? "effect-image_enabled" : body.action === "update" ? "manual-update-note" : body.action === "decoded_limit" ? "decoded-limit-note" : body.action === "nightly_update" ? "nightly-state" : body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
|
|
204
216
|
: body.action.startsWith("history_") ? "effect-history" : body.action === "prediction_fix" ? "prediction-note"
|
|
205
217
|
: body.operation === "switch" ? "source-control-note" : body.operation === "auto-review" ? "review-control-note"
|
|
206
218
|
: body.operation === "account" ? "m365-account-note" : "m365-control-note");
|
|
207
219
|
const initialSourceSave = body.operation === "switch" && Boolean(body.auto_review_model);
|
|
208
|
-
label(note, "applying");
|
|
220
|
+
if (!quiet) { if (note.id === "prediction-open-note") note.hidden = false;label(note, "applying"); }
|
|
209
221
|
if (button) button.setAttribute("aria-busy", "true");
|
|
210
222
|
try {
|
|
211
223
|
const data = await api(body);
|
|
@@ -214,6 +226,7 @@
|
|
|
214
226
|
if (body.action === "provider" && body.operation === "off") { sourceDirty = false;reviewDirty = false; }
|
|
215
227
|
el("review-control-note").textContent = "";
|
|
216
228
|
applySettings(data);
|
|
229
|
+
if (body.action === "prediction" && body.operation === "open") { note.hidden = false;label(note, data.last_operation?.result?.opened ? "codex_action_opened" : "image_action_open_failed"); }
|
|
217
230
|
if (body.action === "image") void globalThis.ccdxConnections?.load();
|
|
218
231
|
if (initialSourceSave) label(el("source-control-note"), "source_initial_review_saved");
|
|
219
232
|
if (body.operation === "account") {
|
|
@@ -227,6 +240,7 @@
|
|
|
227
240
|
}
|
|
228
241
|
catch (error) {
|
|
229
242
|
if (settings) applySettings(settings);
|
|
243
|
+
if (note.id === "prediction-open-note") note.hidden = false;
|
|
230
244
|
if (body.operation === "account") { label(el("m365-account-note"), "company_account_not_saved", { reason: { key: accountReasons.has(error.code) ? error.code : error.message } });return; }
|
|
231
245
|
if (body.action === "color_theme") { label(el("terminal-color-note"), "not_saved_error", { error: error.message });return; }
|
|
232
246
|
if (error.code === "ccdx_prediction_app_open") label(note, error.code);
|
package/src/dashboard/context.js
CHANGED
|
@@ -43,7 +43,8 @@
|
|
|
43
43
|
if (!valid(point.input_tokens)) { continuing = false;return; }
|
|
44
44
|
path += `${continuing ? "L" : "M"}${x(index)} ${y(point.input_tokens)} `;continuing = true;
|
|
45
45
|
const dot = shape("circle", { cx: x(index), cy: y(point.input_tokens), r: 3, class: "context-point" });
|
|
46
|
-
const
|
|
46
|
+
const description = language.format("context_point_usage", { time: time(point.at), input: number(point.input_tokens), reuse: ratio(point.cached_input_tokens, point.input_tokens) });
|
|
47
|
+
const title = document.createElementNS(ns, "title");title.textContent = description;dot.setAttribute("aria-label", description);dot.append(title);
|
|
47
48
|
});
|
|
48
49
|
if (!entry.concurrent) shape("path", { d: path, class: "context-line" });
|
|
49
50
|
for (const index of new Set([0, Math.floor((points.length - 1) / 2), points.length - 1])) {
|
|
@@ -13,12 +13,12 @@
|
|
|
13
13
|
: connected ? imageApp.tool_registration === "observed" ? "image_host_registered" : "image_host_connected" : "image_host_unconfirmed");
|
|
14
14
|
}
|
|
15
15
|
async function codexAction(operation, intent, button, { quiet = false } = {}) {
|
|
16
|
-
const data = await change({ action: "codex_app", operation, intent, ...(operation === "restart" ? { confirmed: true } : {}) }, button);
|
|
16
|
+
const data = await change({ action: "codex_app", operation, intent, ...(operation === "restart" ? { confirmed: true } : {}) }, button, { quiet });
|
|
17
17
|
const result = data?.last_operation?.feature === "codex_app" ? data.last_operation.result : null;
|
|
18
18
|
if (!result) return;
|
|
19
19
|
if (result.app) imageApp = result.app;
|
|
20
20
|
if (!quiet) {
|
|
21
|
-
const note = el(intent === "prediction" ? "prediction-
|
|
21
|
+
const note = el(intent === "prediction" ? "prediction-open-note" : "image-action-note");
|
|
22
22
|
note.dataset.operation = operation;note.hidden = false;
|
|
23
23
|
const key = operation === "check" ? "codex_action_checked" : result.status === "opened_with_pending"
|
|
24
24
|
? result.prediction_pending && result.image_pending ? "codex_action_both_pending" : result.prediction_pending ? "codex_action_prediction_pending" : "codex_action_image_pending"
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
el("additional-capabilities").addEventListener("toggle", () => {
|
|
54
54
|
if (el("additional-capabilities").open) void codexAction("check", "image", el("image-check"), { quiet: true });
|
|
55
55
|
});
|
|
56
|
-
const prediction = operation => change({ action: "prediction", operation }, el("prediction-continue"));
|
|
56
|
+
const prediction = operation => change({ action: "prediction", operation }, el(operation === "open" ? "prediction-open" : "prediction-continue"));
|
|
57
57
|
el("setting-prediction_enabled").addEventListener("change", () => void prediction(el("setting-prediction_enabled").checked ? "enable" : "disable"));
|
|
58
58
|
el("prediction-continue").addEventListener("click", () => void prediction(saved?.features?.prediction?.enabled ? "enable" : "disable"));
|
|
59
59
|
el("fix-prediction").addEventListener("click", () => void prediction("repair"));
|
|
@@ -77,10 +77,14 @@
|
|
|
77
77
|
el("setting-prediction_enabled").checked = value?.enabled === true;
|
|
78
78
|
el("setting-prediction_enabled").disabled = !value || value.status === "unavailable";
|
|
79
79
|
const pending = value?.display_pending || value?.enabled && (!value.configured || value.display?.enabled === false);
|
|
80
|
+
el("prediction-continue-actions").hidden = !pending;
|
|
80
81
|
el("prediction-continue").hidden = !pending;
|
|
81
82
|
el("prediction-open").disabled = !value?.configured && !value?.display_pending;
|
|
82
83
|
el("prediction-remove").disabled = !value?.configured;
|
|
83
|
-
if (notes)
|
|
84
|
+
if (notes) {
|
|
85
|
+
el("prediction-open-note").hidden = true;
|
|
86
|
+
localize(el("prediction-action-note"), !value ? "feature_unavailable" : value.status === "unavailable" ? "feature_read_failed" : pending ? "prediction_quit_continue" : value.enabled && value.bridge !== "running" ? "prediction_bridge_missing" : value.enabled ? "prediction_ready" : "prediction_disabled");
|
|
87
|
+
}
|
|
84
88
|
el("effect-prediction_enabled").hidden = !pending;
|
|
85
89
|
if (pending) localize(el("effect-prediction_enabled"), "feature_pending");
|
|
86
90
|
renderImageApp();
|
package/src/dashboard/index.html
CHANGED
|
@@ -121,14 +121,15 @@
|
|
|
121
121
|
<details class="panel dashboard-section" id="prediction-settings" open>
|
|
122
122
|
<summary class="panel-heading"><h2 data-i18n="codex_input_predictions">INPUT SUGGESTIONS</h2></summary>
|
|
123
123
|
<div class="setting-row"><label for="setting-prediction_enabled" data-i18n="predictions_enable">Input suggestions</label><input id="setting-prediction_enabled" type="checkbox" role="switch" disabled><span id="effect-prediction_enabled" class="hint" role="status"></span></div>
|
|
124
|
-
<p id="prediction-action-note" class="hint" role="status"></p><div
|
|
125
|
-
<p id="prediction-restart-warning" class="hint" role="status" data-i18n="image_restart_warning" hidden>Restarting Codex interrupts its running tasks. Finish or save them first.</p>
|
|
124
|
+
<p id="prediction-action-note" class="hint" role="status"></p><div id="prediction-continue-actions" class="section-actions" hidden><button id="prediction-continue" type="button" data-i18n="feature_continue" hidden>Continue setup</button></div>
|
|
126
125
|
<details class="tool-details"><summary data-i18n="status_and_repair">Status and repair</summary>
|
|
127
126
|
<dl class="stats"><div><dt data-i18n="prediction_integration_setup">Suggestion setup</dt><dd id="prediction-preference">—</dd></div><div><dt data-i18n="local_bridge">Local service</dt><dd id="prediction-bridge">—</dd></div><div><dt data-i18n="client_route">App settings requests</dt><dd id="prediction-route">—</dd></div><div><dt data-i18n="visible_candidate">Suggestion displayed</dt><dd id="prediction-candidate">—</dd></div></dl>
|
|
128
127
|
<p id="prediction-note" class="hint">—</p>
|
|
129
128
|
|
|
130
129
|
|
|
131
|
-
<div class="section-actions"><button id="fix-prediction" type="button" data-i18n="check_and_repair">Check and repair</button><button id="prediction-setup" type="button" data-i18n="prediction_setup_again">Set up again</button><button id="prediction-remove" type="button" data-i18n="feature_remove">Remove setup</button></div>
|
|
130
|
+
<div class="section-actions"><button id="fix-prediction" type="button" data-i18n="check_and_repair">Check and repair</button><button id="prediction-setup" type="button" data-i18n="prediction_setup_again">Set up again</button><button id="prediction-open" type="button" data-i18n="prediction_open">Open Codex</button><button id="prediction-remove" type="button" data-i18n="feature_remove">Remove setup</button></div>
|
|
131
|
+
<p id="prediction-restart-warning" class="hint" role="status" data-i18n="image_restart_warning" hidden>Restarting Codex interrupts its running tasks. Finish or save them first.</p>
|
|
132
|
+
<p id="prediction-open-note" class="hint" role="status" hidden></p>
|
|
132
133
|
</details>
|
|
133
134
|
</details>
|
|
134
135
|
<details class="panel dashboard-section" id="additional-capabilities">
|
|
@@ -270,6 +271,9 @@
|
|
|
270
271
|
<section class="panel dashboard-section">
|
|
271
272
|
<h2 data-i18n="tools_check_local">Check this computer</h2>
|
|
272
273
|
<p class="hint" data-i18n="tools_local_scope">Local checks do not contact external services.</p>
|
|
274
|
+
<p>Codex App: <strong id="client-version-codex">—</strong></p>
|
|
275
|
+
<p>Claude App: <strong id="client-version-claude">—</strong></p>
|
|
276
|
+
<p class="hint" data-i18n="client_versions_scope">Installed versions only; running App adoption and compatibility are separate.</p>
|
|
273
277
|
<div class="section-actions"><button id="check-local" type="button" data-i18n="tools_check_local">Check this computer</button></div>
|
|
274
278
|
<p id="checks-note" class="table-note" role="status" aria-live="polite" data-i18n="tools_checks_empty">Run a check to see the results.</p>
|
|
275
279
|
<div class="table-wrap" id="checks-results" hidden><table class="checks-table"><thead><tr><th data-i18n="tools_check_item">Check</th><th data-i18n="state">State</th><th data-i18n="tools_details">Details</th></tr></thead><tbody id="checks-body"></tbody></table></div>
|
|
@@ -99,6 +99,7 @@
|
|
|
99
99
|
"context_latest_input": ["Latest input", "最近输入"],
|
|
100
100
|
"context_reuse": ["Cache reuse", "缓存复用"],
|
|
101
101
|
"context_history": ["Input history", "输入变化"],
|
|
102
|
+
"context_point_usage": ["{time} · input {input} tokens · cache reuse {reuse}", "{time} · 输入 {input} Token · 缓存复用 {reuse}"],
|
|
102
103
|
"context_compactions": ["Gateway compactions", "网关压缩"],
|
|
103
104
|
"context_elapsed": ["Elapsed", "耗时"],
|
|
104
105
|
"context_conversation": ["Conversation {id}", "会话 {id}"],
|
|
@@ -566,6 +567,9 @@
|
|
|
566
567
|
"tools_access_denied": ["GitHub sign-in is valid. Check your Copilot access or company policy.", "GitHub 登录有效。请检查 Copilot 权限或公司策略。"],
|
|
567
568
|
"tools_network_hint": ["Connection could not be verified. Check network settings; saved sign-in is kept.", "连接未能验证。请检查网络,原登录已保留。"],
|
|
568
569
|
"tools_local_scope": ["Local checks only", "仅检查本机"],
|
|
570
|
+
"client_versions_scope": ["Installed versions only; running App adoption and compatibility are separate.", "显示已安装版本;运行中的版本和接入状态需分别确认。"],
|
|
571
|
+
"client_version_observed": ["{version}", "{version}"],
|
|
572
|
+
"client_version_changed": ["{version} · updated, access unverified", "{version} · 已更新,接入待确认"],
|
|
569
573
|
"tools_check_local": ["Check this computer", "本机检查"],
|
|
570
574
|
"tools_export_report": ["Export report", "导出报告"],
|
|
571
575
|
"tools_checks_empty": ["Run a local check to see results.", "运行本机检查后查看结果。"],
|
|
@@ -999,7 +1003,7 @@
|
|
|
999
1003
|
"entries_entries_trees_trees_misses_misses_evicted_evicted": ["Records: {entries} / groups: {trees}\nNot found: {misses} / removed: {evicted}", "暂存:{entries}条/分组:{trees}\n未找到:{misses}\n清理后未找到:{evicted}"],
|
|
1000
1004
|
"count_succeeded": ["{count} succeeded", "成功:{count}次"],
|
|
1001
1005
|
"not_initialized": ["NOT CONFIRMED", "未确认"],
|
|
1002
|
-
"active_active_failed_failed_delivery_failures_delivery": ["Running: {active} / generation failed: {failed}
|
|
1006
|
+
"active_active_failed_failed_delivery_failures_delivery": ["Running: {active} / generation failed: {failed} / file delivery failed: {delivery}", "进行中:{active}/生成失败:{failed}/文件交付失败:{delivery}"],
|
|
1003
1007
|
"setup_state_unknown_ccdx_image_status": ["Uses the existing GitHub Copilot account.", "使用现有 GitHub Copilot 账号。"],
|
|
1004
1008
|
"snapshot_time": ["Status updated {time}", "状态更新:{time}"],
|
|
1005
1009
|
"status_unavailable_check_ccdx_then_refresh": ["Cannot read status. Check CCDX and refresh.", "无法读取状态。\n请检查 CCDX 后刷新。"],
|
package/src/dashboard/tools.js
CHANGED
|
@@ -137,6 +137,7 @@
|
|
|
137
137
|
el("github-logout").addEventListener("click", () => { if (window.confirm(language.format("tools_logout_confirm"))) void accountAction({ action: "logout", confirmed: true }); });
|
|
138
138
|
async function loadAccount() { const generation = accountGeneration;try { const data = await api("account");if (generation === accountGeneration && !pending) renderAccount(data); } catch { if (generation === accountGeneration) text("github-account-note", "tools_read_failed"); } }
|
|
139
139
|
function renderChecks(data) {
|
|
140
|
+
if (Object.hasOwn(data, "client_versions")) globalThis.ccdxClientVersions?.render(data.client_versions);
|
|
140
141
|
const body = el("checks-body");body.replaceChildren();
|
|
141
142
|
const groups = new Map();
|
|
142
143
|
for (const check of data.checks || []) { if (!groups.has(check.id)) groups.set(check.id, []);groups.get(check.id).push(check); }
|
package/src/doctor.mjs
CHANGED
|
@@ -315,6 +315,14 @@ export async function runDoctor(options = {}) {
|
|
|
315
315
|
].filter(Boolean);
|
|
316
316
|
if (!options.json) log(`${options.commandName || "ccdx"} doctor${options.configOnly ? " config" : flags.length ? ` ${flags.join(" ")}` : ""}`);
|
|
317
317
|
let checks = await collectDoctorChecks(options);
|
|
318
|
+
if (!options.configOnly) {
|
|
319
|
+
try {
|
|
320
|
+
const { createClientVersionMonitor, clientVersionChecks } = await import("./client-versions.mjs");
|
|
321
|
+
const monitor = options.clientVersions || createClientVersionMonitor({ home: options.home, env: options.env, platform: options.platform, persist: false });
|
|
322
|
+
try { checks.push(...clientVersionChecks(await monitor.refresh())); }
|
|
323
|
+
finally { if (!options.clientVersions) monitor.close(); }
|
|
324
|
+
} catch { checks.push({ id: "client-versions", kind: "info", message: "App version observations are unavailable" }); }
|
|
325
|
+
}
|
|
318
326
|
const before = options.fix ? checks : undefined;
|
|
319
327
|
if (options.fix && !options.configOnly) {
|
|
320
328
|
const repair = options.repairDoctorFn || (await import("./doctor-repair.mjs")).repairDoctor;
|
package/src/local-tools.mjs
CHANGED
|
@@ -12,18 +12,21 @@ import { inspectAdapterCompatibility } from "./doctor-compat.mjs";
|
|
|
12
12
|
|
|
13
13
|
export function createLocalTools({ home = os.homedir(), env = process.env, host = "127.0.0.1", port = 2026,
|
|
14
14
|
platform = process.platform, collect = collectDoctorChecks, inspectConfig = inspectCodexConfig, repairConfig = repairCodexConfig,
|
|
15
|
-
inspectNetwork = inspectPredictionEnvironment, inspectCompatibility = inspectAdapterCompatibility } = {}) {
|
|
15
|
+
inspectNetwork = inspectPredictionEnvironment, inspectCompatibility = inspectAdapterCompatibility, clientVersions } = {}) {
|
|
16
16
|
const options = { home, env, host, port, platform };
|
|
17
17
|
let last = null, flight = null;
|
|
18
18
|
const safe = text => redactDiagnosticText(String(text || "")).split(home).join("~")
|
|
19
19
|
.replace(/[\w.+-]+@[\w.-]+/g, "[account]").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 600);
|
|
20
20
|
const project = checks => checks.slice(0, 80).map(check => ({ id: /^[a-z-]{1,60}$/.test(check.id || "") ? check.id : "local",
|
|
21
21
|
kind: ["ok", "info", "warn", "err"].includes(check.kind) ? check.kind : "info", message: safe(check.message) }));
|
|
22
|
-
function snapshot() { return { source: "local_tools", ...last }; }
|
|
22
|
+
function snapshot() { let versions = null;try { versions = clientVersions?.snapshot?.() || null; } catch {}return { source: "local_tools", ...last, ...(clientVersions ? { client_versions: versions } : {}) }; }
|
|
23
23
|
async function check() {
|
|
24
24
|
if (flight) return flight;
|
|
25
25
|
flight = Promise.resolve().then(async () => {
|
|
26
|
-
|
|
26
|
+
const versions = clientVersions?.refresh ? Promise.resolve().then(() => clientVersions.refresh()).catch(() => null) : null;
|
|
27
|
+
const checks = await collect({ ...options, checkAdapter: false });
|
|
28
|
+
await versions;
|
|
29
|
+
last = { checked_at: new Date().toISOString(), checks: project(checks) };
|
|
27
30
|
return snapshot();
|
|
28
31
|
}).finally(() => { flight = null; });
|
|
29
32
|
return flight;
|
|
@@ -57,6 +57,14 @@ const WINDOWS_APP_SCRIPT = `$p=@(Get-AppxPackage -Name OpenAI.Codex | Where-Obje
|
|
|
57
57
|
if($a.Count -ne 1){throw 'Unknown Windows App executable'};
|
|
58
58
|
@{root=$p[0].InstallLocation;executable=$a[0].Executable;family=$p[0].PackageFamilyName} | ConvertTo-Json -Compress`;
|
|
59
59
|
|
|
60
|
+
export async function inspectWindowsCodexVersion({ env = process.env, exec = execFileAsync } = {}) {
|
|
61
|
+
const 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}' });if($p.Count -ne 1){throw 'Unknown App registration'};[string]$p[0].Version`;
|
|
62
|
+
const [command, args] = powershellCommand(script, env);
|
|
63
|
+
const result = await exec(command, args, { encoding: "utf8", timeout: 2500, maxBuffer: 4096, env: windowsPowerShellEnvironment(env), windowsHide: true });
|
|
64
|
+
const version = String(result?.stdout ?? result).trim();
|
|
65
|
+
return /^\d+(?:\.\d+){1,3}$/.test(version) ? version : null;
|
|
66
|
+
}
|
|
67
|
+
|
|
60
68
|
function registeredApp(raw) {
|
|
61
69
|
let metadata;
|
|
62
70
|
try { metadata = JSON.parse(raw); } catch { throw new Error("Could not read the registered Windows Codex App"); }
|
package/src/observability.mjs
CHANGED
|
@@ -185,8 +185,9 @@ export function runtimeStatusPayload({
|
|
|
185
185
|
last_request: observed ? {
|
|
186
186
|
client_version: version(observed.client_version),
|
|
187
187
|
application: ["ChatGPT.app", "Codex.app", "custom binary"].includes(observed.application) ? observed.application : null,
|
|
188
|
-
source:
|
|
188
|
+
source: ["bundled", "cached_bundled"].includes(observed.source) ? observed.source : "unavailable",
|
|
189
189
|
matched: observed.matched === true,
|
|
190
|
+
match_precision: ["exact", "core_only"].includes(observed.match_precision) ? observed.match_precision : null,
|
|
190
191
|
observed_at: typeof observed.observed_at === "string" && /^\d{4}-\d{2}-\d{2}T[0-9:.]+Z$/.test(observed.observed_at) ? observed.observed_at : null,
|
|
191
192
|
} : null,
|
|
192
193
|
observed_versions: (Array.isArray(snapshot?.observed_versions) ? snapshot.observed_versions : []).filter(version).slice(0, 8),
|
package/src/privacy-stream.mjs
CHANGED
|
@@ -114,12 +114,12 @@ function fragments(session, json, onRetained) {
|
|
|
114
114
|
|
|
115
115
|
function rewrite(wire, event, named = false) {
|
|
116
116
|
let written = false;
|
|
117
|
-
const output = wire.split(/(?<=\n)/).map(line => {
|
|
117
|
+
const output = wire.split(/(?<=\n)|(?<=\r)(?!\n)/).map(line => {
|
|
118
118
|
if (!line.startsWith("data:")) return line;
|
|
119
119
|
if (written) return "";written = true;
|
|
120
|
-
return "data: " + JSON.stringify(event) + (line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : "");
|
|
120
|
+
return "data: " + JSON.stringify(event) + (line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : line.endsWith("\r") ? "\r" : "");
|
|
121
121
|
}).join("");
|
|
122
|
-
return named && !/^event:/m.test(output) ? "event: " + event.type + "\n" + output : output;
|
|
122
|
+
return named && !/^event:/m.test(output) ? "event: " + event.type + (wire.match(/\r\n|\r|\n/)?.[0] || "\n") + output : output;
|
|
123
123
|
}
|
|
124
124
|
|
|
125
125
|
export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 1024, maxChannels = 1024 } = {}) {
|
|
@@ -184,7 +184,7 @@ export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 10
|
|
|
184
184
|
forget(id);return output;
|
|
185
185
|
}
|
|
186
186
|
function transform(wire) {
|
|
187
|
-
const lines = wire.split(/\r
|
|
187
|
+
const lines = wire.split(/\r\n|\r|\n/), data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
|
|
188
188
|
if (!data || data === "[DONE]") return wire;
|
|
189
189
|
let event;
|
|
190
190
|
try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
|
|
@@ -269,8 +269,10 @@ export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 10
|
|
|
269
269
|
pending += decoder.write(chunk);pendingBytes += chunk.length;
|
|
270
270
|
if (pendingBytes > 8 * 1024 * 1024) throw fail("stream_limit");
|
|
271
271
|
let output = "", match;
|
|
272
|
-
while ((match =
|
|
273
|
-
const end = match.index + match[0].length
|
|
272
|
+
while ((match = /(?:\r\n|\r(?!\n)|(?<!\r)\n){2}/.exec(pending))) {
|
|
273
|
+
const end = match.index + match[0].length;
|
|
274
|
+
if (end === pending.length && match[0].endsWith("\r") && match[0].includes("\n")) break;
|
|
275
|
+
const wire = pending.slice(0, end);pending = pending.slice(end);
|
|
274
276
|
pendingBytes = Buffer.byteLength(pending);output += transform(wire);
|
|
275
277
|
}
|
|
276
278
|
return output;
|
|
@@ -278,7 +280,8 @@ export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 10
|
|
|
278
280
|
},
|
|
279
281
|
finish() {
|
|
280
282
|
try {
|
|
281
|
-
pending += decoder.end();const
|
|
283
|
+
pending += decoder.end();const complete = /(?:\r\n|\r(?!\n)|(?<!\r)\n){2}$/.test(pending);
|
|
284
|
+
const output = pending ? transform(pending + (complete ? "" : "\n\n")) : "";pending = "";
|
|
282
285
|
if (channels.size) throw fail("stream_incomplete");return output;
|
|
283
286
|
} catch (error) { completed = false;throw error; }
|
|
284
287
|
finally { clear();pending = "";pendingBytes = 0; }
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -172,6 +172,7 @@ function createResponseSseTransformer(state) {
|
|
|
172
172
|
let previous1 = -1;
|
|
173
173
|
let previous2 = -1;
|
|
174
174
|
let previous3 = -1;
|
|
175
|
+
let bareCR = false;
|
|
175
176
|
|
|
176
177
|
const ensureCapacity = (required) => {
|
|
177
178
|
if (required > MAX_SSE_BUFFER_BYTES + 4) {
|
|
@@ -198,7 +199,7 @@ function createResponseSseTransformer(state) {
|
|
|
198
199
|
throw httpError(`Upstream SSE buffer exceeds ${MAX_SSE_BUFFER_BYTES} bytes`, 502);
|
|
199
200
|
}
|
|
200
201
|
const chunk = frame.subarray(0, contentLength).toString("utf8");
|
|
201
|
-
const lines = chunk.split(/\r?\n/);
|
|
202
|
+
const lines = bareCR ? chunk.split(/\r\n|\r|\n/) : chunk.split(/\r?\n/);
|
|
202
203
|
const eventName = lines
|
|
203
204
|
.find((line) => line.startsWith("event:"))
|
|
204
205
|
?.slice(6)
|
|
@@ -216,7 +217,8 @@ function createResponseSseTransformer(state) {
|
|
|
216
217
|
wroteData = true;
|
|
217
218
|
return true;
|
|
218
219
|
}).map((line) => line.startsWith("data:") ? `data: ${JSON.stringify(changed)}` : line);
|
|
219
|
-
|
|
220
|
+
const newline = bareCR ? chunk.match(/\r\n|\r|\n/)?.[0] || "\n" : chunk.includes("\r\n") ? "\r\n" : "\n";
|
|
221
|
+
return Buffer.from(rewritten.join(newline)
|
|
220
222
|
+ frame.subarray(contentLength).toString("ascii"));
|
|
221
223
|
};
|
|
222
224
|
|
|
@@ -233,40 +235,97 @@ function createResponseSseTransformer(state) {
|
|
|
233
235
|
return output;
|
|
234
236
|
};
|
|
235
237
|
let segmentStart = 0;
|
|
238
|
+
if (!bareCR) {
|
|
239
|
+
if (previous1 === 0x0d && value.length && value[0] !== 0x0a) bareCR = true;
|
|
240
|
+
for (let at = value.indexOf(0x0d); !bareCR && at >= 0; at = value.indexOf(0x0d, at + 1)) {
|
|
241
|
+
if (at + 1 < value.length && value[at + 1] !== 0x0a) bareCR = true;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (!bareCR) {
|
|
245
|
+
// The common LF/CRLF path searches newline bytes in native code;
|
|
246
|
+
// the three-byte carry keeps delimiters split across reads intact.
|
|
247
|
+
for (let index = value.indexOf(0x0a); index >= 0; index = value.indexOf(0x0a, index + 1)) {
|
|
248
|
+
const available = index - segmentStart;
|
|
249
|
+
const p1 = available >= 1 ? value[index - 1] : segmentStart === 0 ? previous1 : -1;
|
|
250
|
+
const p2 = available >= 2 ? value[index - 2] : segmentStart === 0 ? available === 1 ? previous1 : previous2 : -1;
|
|
251
|
+
const p3 = available >= 3 ? value[index - 3] : segmentStart === 0 ? available === 2 ? previous1 : available === 1 ? previous2 : previous3 : -1;
|
|
252
|
+
let delimiterLength = 0;
|
|
253
|
+
if (p1 === 0x0a) {
|
|
254
|
+
delimiterLength = p2 === 0x0d ? 3 : 2;
|
|
255
|
+
} else if (p1 === 0x0d && p2 === 0x0a) {
|
|
256
|
+
delimiterLength = p3 === 0x0d ? 4 : 3;
|
|
257
|
+
}
|
|
258
|
+
if (delimiterLength) {
|
|
259
|
+
let frame = value.subarray(segmentStart, index + 1);
|
|
260
|
+
if (eventLength > 0) {
|
|
261
|
+
append(frame);
|
|
262
|
+
if (eventLength > SSE_WRITE_BATCH_BYTES) {
|
|
263
|
+
frame = eventBuffer.subarray(0, eventLength);
|
|
264
|
+
eventBuffer = Buffer.allocUnsafe(Math.min(4096, MAX_SSE_BUFFER_BYTES + 4));
|
|
265
|
+
} else frame = Buffer.from(eventBuffer.subarray(0, eventLength));
|
|
266
|
+
}
|
|
267
|
+
eventLength = 0;previous1 = -1;previous2 = -1;previous3 = -1;segmentStart = index + 1;
|
|
268
|
+
const forwarded = inspectEvent(frame, delimiterLength), last = pending.at(-1);
|
|
269
|
+
if (last && last.buffer === forwarded.buffer && last.byteOffset + last.byteLength === forwarded.byteOffset)
|
|
270
|
+
pending[pending.length - 1] = Buffer.from(last.buffer, last.byteOffset, last.byteLength + forwarded.byteLength);
|
|
271
|
+
else pending.push(forwarded);
|
|
272
|
+
pendingBytes += forwarded.byteLength;
|
|
273
|
+
if (state.sawTerminal) return flush();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
for (let index = Math.max(segmentStart, value.byteLength - 3); index < value.byteLength; index++) {
|
|
277
|
+
previous3 = previous2;previous2 = previous1;previous1 = value[index];
|
|
278
|
+
}
|
|
279
|
+
append(value.subarray(segmentStart));
|
|
280
|
+
if (eventLength > MAX_SSE_BUFFER_BYTES + 3) throw httpError(`Upstream SSE buffer exceeds ${MAX_SSE_BUFFER_BYTES} bytes`, 502);
|
|
281
|
+
return pendingBytes > 0 ? flush() : null;
|
|
282
|
+
}
|
|
283
|
+
const forward = (end, delimiterLength) => {
|
|
284
|
+
let frame = value.subarray(segmentStart, end);
|
|
285
|
+
if (eventLength > 0) {
|
|
286
|
+
append(frame);
|
|
287
|
+
// Writes may retain a Buffer after returning; never expose the reusable buffer.
|
|
288
|
+
if (eventLength > SSE_WRITE_BATCH_BYTES) {
|
|
289
|
+
frame = eventBuffer.subarray(0, eventLength);
|
|
290
|
+
eventBuffer = Buffer.allocUnsafe(Math.min(4096, MAX_SSE_BUFFER_BYTES + 4));
|
|
291
|
+
} else {
|
|
292
|
+
frame = Buffer.from(eventBuffer.subarray(0, eventLength));
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
eventLength = 0;
|
|
296
|
+
previous1 = -1;
|
|
297
|
+
previous2 = -1;
|
|
298
|
+
previous3 = -1;
|
|
299
|
+
segmentStart = end;
|
|
300
|
+
const forwarded = inspectEvent(frame, delimiterLength);
|
|
301
|
+
const last = pending.at(-1);
|
|
302
|
+
if (last && last.buffer === forwarded.buffer
|
|
303
|
+
&& last.byteOffset + last.byteLength === forwarded.byteOffset) {
|
|
304
|
+
pending[pending.length - 1] = Buffer.from(last.buffer, last.byteOffset, last.byteLength + forwarded.byteLength);
|
|
305
|
+
} else {
|
|
306
|
+
pending.push(forwarded);
|
|
307
|
+
}
|
|
308
|
+
pendingBytes += forwarded.byteLength;
|
|
309
|
+
};
|
|
236
310
|
for (let index = 0; index < value.byteLength; index += 1) {
|
|
237
311
|
const byte = value[index];
|
|
312
|
+
// A CR after an LF may be the last byte of a blank line. Wait for
|
|
313
|
+
// the next byte so split CRLF frames retain their original bytes.
|
|
314
|
+
if (previous1 === 0x0d && previous2 === 0x0a && byte !== 0x0a) {
|
|
315
|
+
forward(index, previous3 === 0x0d ? 3 : 2);
|
|
316
|
+
if (state.sawTerminal) return flush();
|
|
317
|
+
}
|
|
238
318
|
let delimiterLength = 0;
|
|
239
319
|
if (byte === 0x0a && previous1 === 0x0a) {
|
|
240
320
|
delimiterLength = previous2 === 0x0d ? 3 : 2;
|
|
241
321
|
} else if (byte === 0x0a && previous1 === 0x0d && previous2 === 0x0a) {
|
|
242
322
|
delimiterLength = previous3 === 0x0d ? 4 : 3;
|
|
323
|
+
} else if (byte === 0x0d && previous1 === 0x0d) {
|
|
324
|
+
delimiterLength = 2;
|
|
325
|
+
if (value[index + 1] === 0x0a) { index += 1;delimiterLength += 1; }
|
|
243
326
|
}
|
|
244
327
|
if (delimiterLength) {
|
|
245
|
-
|
|
246
|
-
if (eventLength > 0) {
|
|
247
|
-
append(frame);
|
|
248
|
-
// Writes may retain a Buffer after returning; never expose the reusable buffer.
|
|
249
|
-
if (eventLength > SSE_WRITE_BATCH_BYTES) {
|
|
250
|
-
frame = eventBuffer.subarray(0, eventLength);
|
|
251
|
-
eventBuffer = Buffer.allocUnsafe(Math.min(4096, MAX_SSE_BUFFER_BYTES + 4));
|
|
252
|
-
} else {
|
|
253
|
-
frame = Buffer.from(eventBuffer.subarray(0, eventLength));
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
eventLength = 0;
|
|
257
|
-
previous1 = -1;
|
|
258
|
-
previous2 = -1;
|
|
259
|
-
previous3 = -1;
|
|
260
|
-
segmentStart = index + 1;
|
|
261
|
-
const forwarded = inspectEvent(frame, delimiterLength);
|
|
262
|
-
const last = pending.at(-1);
|
|
263
|
-
if (last && last.buffer === forwarded.buffer
|
|
264
|
-
&& last.byteOffset + last.byteLength === forwarded.byteOffset) {
|
|
265
|
-
pending[pending.length - 1] = Buffer.from(last.buffer, last.byteOffset, last.byteLength + forwarded.byteLength);
|
|
266
|
-
} else {
|
|
267
|
-
pending.push(forwarded);
|
|
268
|
-
}
|
|
269
|
-
pendingBytes += forwarded.byteLength;
|
|
328
|
+
forward(index + 1, delimiterLength);
|
|
270
329
|
if (state.sawTerminal) return flush();
|
|
271
330
|
continue;
|
|
272
331
|
}
|
|
@@ -280,6 +339,14 @@ function createResponseSseTransformer(state) {
|
|
|
280
339
|
}
|
|
281
340
|
return pendingBytes > 0 ? flush() : null;
|
|
282
341
|
},
|
|
342
|
+
finish() {
|
|
343
|
+
if (previous1 !== 0x0d || previous2 !== 0x0a || !eventLength) return null;
|
|
344
|
+
bareCR = true;
|
|
345
|
+
const delimiterLength = previous3 === 0x0d ? 3 : 2;
|
|
346
|
+
const frame = Buffer.from(eventBuffer.subarray(0, eventLength));
|
|
347
|
+
eventLength = 0;previous1 = -1;previous2 = -1;previous3 = -1;
|
|
348
|
+
return inspectEvent(frame, delimiterLength);
|
|
349
|
+
},
|
|
283
350
|
};
|
|
284
351
|
}
|
|
285
352
|
|
|
@@ -452,6 +519,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
452
519
|
while (true) {
|
|
453
520
|
const { done, value } = await reader.read();
|
|
454
521
|
if (done) {
|
|
522
|
+
if (!await forwardFrame(transformer.finish())) return { successful: false, compacted: false };
|
|
455
523
|
if (!streamState.sawTerminal) throw incompleteUpstreamStream("a terminal Responses event");
|
|
456
524
|
break;
|
|
457
525
|
}
|
package/src/service-control.mjs
CHANGED
|
@@ -14,6 +14,7 @@ import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
|
|
|
14
14
|
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
15
15
|
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
16
16
|
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage, codexLaunchControl = controlCodexLaunch,
|
|
17
|
+
clientVersions,
|
|
17
18
|
adapterPort = 2026, adapterHost = "127.0.0.1",
|
|
18
19
|
readImages = () => imageSetupSummary({ env, home }).configured, readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
19
20
|
const options = { env, home };
|
|
@@ -41,7 +42,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
41
42
|
prediction_enabled: { value: prediction?.active === true, state: !predictionConfigured ? "needs_setup"
|
|
42
43
|
: prediction?.environment?.status === "needs_app_relaunch" ? "needs_app_relaunch" : prediction?.bridge !== "running" ? "needs_service_restart" : "next_config_request", configured: predictionConfigured },
|
|
43
44
|
}, history: { ...historyLimit, ...cacheRuntimeSnapshot().response_history },
|
|
44
|
-
providers: providerRuntime?.snapshot() || null, terminal: terminal?.snapshot?.() || null };
|
|
45
|
+
providers: providerRuntime?.snapshot() || null, terminal: terminal?.snapshot?.() || null, client_versions: featureSnapshot(() => clientVersions?.snapshot?.() || null) };
|
|
45
46
|
}
|
|
46
47
|
async function apply(input) {
|
|
47
48
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
@@ -112,6 +113,11 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
112
113
|
return snapshot();
|
|
113
114
|
}
|
|
114
115
|
return { snapshot, busy: () => pending > 0, action(input) {
|
|
116
|
+
if (input?.action === "client_versions") {
|
|
117
|
+
if (Object.keys(input).some(key => key !== "action")) return Promise.reject(new Error("Unknown setting action or field"));
|
|
118
|
+
if (clientVersions?.refresh) void Promise.resolve().then(() => clientVersions.refresh()).catch(() => {});
|
|
119
|
+
return Promise.resolve({ source: "client_versions", scheduled: Boolean(clientVersions) });
|
|
120
|
+
}
|
|
115
121
|
// Image-host evidence must not wait behind a user-initiated App restart:
|
|
116
122
|
// the host sends it with a short deadline as the new App starts.
|
|
117
123
|
if (input?.action === "image" && input.operation === "report") {
|
package/src/stream.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Yield fetch Response body lines while preserving SSE semantics for callers.
|
|
2
|
-
//
|
|
2
|
+
// Handle LF, CRLF and CR endings, and release the reader if iteration stops early.
|
|
3
3
|
import { loadRuntimeConfig } from "./runtime-config.mjs";
|
|
4
4
|
|
|
5
5
|
const MAX_SSE_BUFFER_BYTES = loadRuntimeConfig().maxSseBufferBytes;
|
|
@@ -19,6 +19,7 @@ export async function* webStreamLines(response, { onChunk, maxBufferBytes = MAX_
|
|
|
19
19
|
const decoder = new TextDecoder();
|
|
20
20
|
let lineParts = [];
|
|
21
21
|
let lineBytes = 0;
|
|
22
|
+
let skipLF = false, bareCR = false;
|
|
22
23
|
try {
|
|
23
24
|
while (true) {
|
|
24
25
|
const { done, value } = await reader.read();
|
|
@@ -26,24 +27,60 @@ export async function* webStreamLines(response, { onChunk, maxBufferBytes = MAX_
|
|
|
26
27
|
onChunk?.(value);
|
|
27
28
|
const decoded = decoder.decode(value, { stream: true });
|
|
28
29
|
let start = 0;
|
|
30
|
+
if (!bareCR && decoded.length) {
|
|
31
|
+
const tailCR = lineParts.at(-1)?.endsWith("\r") === true;
|
|
32
|
+
if (tailCR && decoded[0] !== "\n") {
|
|
33
|
+
bareCR = true;
|
|
34
|
+
lineParts[lineParts.length - 1] = lineParts.at(-1).slice(0, -1);lineBytes--;
|
|
35
|
+
yield lineParts.length > 1 ? lineParts.join("") : lineParts[0];
|
|
36
|
+
lineParts = [];lineBytes = 0;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (!bareCR) {
|
|
40
|
+
let nextCR = decoded.indexOf("\r", start);
|
|
41
|
+
while (start < decoded.length) {
|
|
42
|
+
const newline = decoded.indexOf("\n", start), end = newline < 0 ? decoded.length : newline;
|
|
43
|
+
if (nextCR >= 0 && nextCR < end - 1) { bareCR = true;break; }
|
|
44
|
+
const part = decoded.slice(start, end);
|
|
45
|
+
if (newline < 0) { lineBytes = appendLineFragment(lineParts, part, lineBytes, maxBufferBytes);break; }
|
|
46
|
+
let line;
|
|
47
|
+
if (!lineParts.length) {
|
|
48
|
+
if (Buffer.byteLength(part) > maxBufferBytes) throw new Error(`Upstream SSE buffer exceeds ${maxBufferBytes} bytes`);
|
|
49
|
+
line = part;
|
|
50
|
+
} else {
|
|
51
|
+
lineBytes = appendLineFragment(lineParts, part, lineBytes, maxBufferBytes);
|
|
52
|
+
line = lineParts.length > 1 ? lineParts.join("") : lineParts[0];
|
|
53
|
+
}
|
|
54
|
+
lineParts = [];lineBytes = 0;start = newline + 1;
|
|
55
|
+
if (nextCR >= 0 && nextCR === end - 1) nextCR = decoded.indexOf("\r", start);
|
|
56
|
+
yield line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
57
|
+
}
|
|
58
|
+
if (!bareCR) continue;
|
|
59
|
+
}
|
|
60
|
+
if (skipLF && decoded.length) { if (decoded[0] === "\n") start = 1;skipLF = false; }
|
|
29
61
|
while (start < decoded.length) {
|
|
30
|
-
const
|
|
31
|
-
|
|
62
|
+
const lf = decoded.indexOf("\n", start), cr = decoded.indexOf("\r", start);
|
|
63
|
+
const newline = lf < 0 ? cr : cr < 0 ? lf : Math.min(lf, cr);
|
|
64
|
+
if (newline < 0) {
|
|
32
65
|
lineBytes = appendLineFragment(lineParts, decoded.slice(start), lineBytes, maxBufferBytes);
|
|
33
66
|
break;
|
|
34
67
|
}
|
|
35
68
|
lineBytes = appendLineFragment(lineParts, decoded.slice(start, newline), lineBytes, maxBufferBytes);
|
|
36
69
|
const line = lineParts.length > 1 ? lineParts.join("") : (lineParts[0] || "");
|
|
37
|
-
yield line
|
|
70
|
+
yield line;
|
|
38
71
|
lineParts = [];
|
|
39
72
|
lineBytes = 0;
|
|
40
73
|
start = newline + 1;
|
|
74
|
+
if (decoded[newline] === "\r") {
|
|
75
|
+
if (start === decoded.length) skipLF = true;
|
|
76
|
+
else if (decoded[start] === "\n") start++;
|
|
77
|
+
}
|
|
41
78
|
}
|
|
42
79
|
}
|
|
43
80
|
lineBytes = appendLineFragment(lineParts, decoder.decode(), lineBytes, maxBufferBytes);
|
|
44
81
|
if (lineParts.length > 0) {
|
|
45
82
|
const line = lineParts.length > 1 ? lineParts.join("") : lineParts[0];
|
|
46
|
-
yield line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
83
|
+
yield !bareCR && line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
47
84
|
}
|
|
48
85
|
} finally {
|
|
49
86
|
await reader.cancel().catch(() => {});
|