codex-copilot-dx 0.9.34 → 0.9.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,6 +39,7 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
39
39
  | `ccdx usage` | Recorded tokens and upstream prompt-cache hit rate |
40
40
  | `ccdx auto-review-model` | Select model, then reasoning effort; `0` follows client |
41
41
  | `ccdx animation` | Preview and select terminal animation |
42
+ | `ccdx prediction fix` | Repair an enabled prediction bridge; never force-restart Codex |
42
43
  | `ccdx cache --limit 128` | Set the history-cache budget in MiB |
43
44
  | `ccdx cache --clean` | Clear the rebuildable image-transform cache |
44
45
  | `ccdx limits --decoded 256` | Set the decoded request-body budget; restart to apply |
@@ -82,15 +83,14 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
82
83
  use public HTTPS URLs; well-known NAT64 mappings follow IPv4 address rules.
83
84
  - Keep the adapter on loopback. LAN mode is only for trusted networks; do not
84
85
  expose it to the public internet. The dashboard is not an authentication wall
85
- for the API. Diagnostic errors may contain sensitive upstream text.
86
+ for the API. Inference rejects browser Origin headers; native clients remain supported. Diagnostic errors may contain sensitive upstream text.
86
87
 
87
88
  Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`.
88
89
  Updates install the exact stable tag; dependencies still use npm's configured registry. Lookup errors identify HTTP refusal, timeout, network failure or invalid redirects.
89
- Updates warn about mismatched npm targets without changing PATH/prefix. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
90
+ Updates warn about mismatched npm targets without changing PATH/prefix and verify the installed target version (exact tag for GitHub). Restart the adapter separately. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
90
91
  Recent errors separate HTTP and model failures. HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged.
91
92
 
92
- The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown.
93
- Inference, client integration, optional images and management have separate ownership. See [architecture boundaries](docs/ARCHITECTURE.md).
93
+ The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown. Inference, client integration, optional images and management have separate ownership. See [architecture boundaries](docs/ARCHITECTURE.md).
94
94
 
95
95
  See the [complete reference](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/REFERENCE.md) for authentication, configuration, limits, logging, images and compatibility. It is also included as `docs/REFERENCE.md` in the npm package.
96
96
 
package/bin/cli.mjs CHANGED
@@ -89,11 +89,15 @@ if (CLI.command === "suggestion") {
89
89
  if (CLI.command === "prediction") {
90
90
  try {
91
91
  const { runPredictionCommand } = await import("../src/native-prediction.mjs");
92
- await runPredictionCommand({ action: CLI.action, runtimeSnapshot: () => {
92
+ const result = await runPredictionCommand({ action: CLI.action, repairRuntime: async () => {
93
+ const { requestPredictionFix } = await import("../src/native-prediction-fix.mjs");
94
+ const probe = parseAdapterProbeOptions(process.env);
95
+ return requestPredictionFix({ host: probe.adapterHost, port: probe.adapterPort });
96
+ }, runtimeSnapshot: () => {
93
97
  const probe = parseAdapterProbeOptions(process.env);
94
98
  return readAdapterStatus({ host: probe.adapterHost, port: probe.adapterPort, timeoutMs: probe.existingAdapterTimeoutMs }).then(({ data }) => data);
95
99
  } });
96
- process.exit(0);
100
+ process.exit(CLI.action === "fix" ? result.exitCode : 0);
97
101
  } catch (error) {
98
102
  console.error(status("err", error.message));
99
103
  process.exit(1);
@@ -372,13 +376,14 @@ try {
372
376
  await ensureAuth({ log: startupLogger("Auth") });
373
377
 
374
378
  const profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient });
379
+ let startupComplete = false;
375
380
  const profileModels = createProfileModelRuntime({
376
381
  codexClient: profileRuntime.codexClient,
377
382
  codexCredentialFingerprint: profileRuntime.codexCredentialFingerprint,
378
383
  timeoutMs: MODEL_REFRESH_TIMEOUT_MS,
379
384
  commandName: CLI_NAME,
380
385
  autoReviewModelResolver: () => autoReviewModelPreference().model,
381
- log: (kind, message) => console.log(startupCheck(kind, "Models", message)),
386
+ log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "Models", message)),
382
387
  });
383
388
 
384
389
  // Refresh the VS Code version in the background; fallback is non-blocking.
@@ -406,7 +411,8 @@ try {
406
411
  streamHandshakeTimeoutMs: RUNTIME.streamHandshakeTimeoutMs,
407
412
  streamIdleTimeoutMs: RUNTIME.streamIdleTimeoutMs,
408
413
  terminalAnimationTheme,
409
- nativePredictionPac: () => nativePrediction?.pacUrl || null,
414
+ nativePredictionPac: () => clientIntegration?.pacUrl() || null,
415
+ fixPrediction: async () => (await clientIntegrations()).fix(),
410
416
  clientIntegrationSnapshot: () => clientIntegration?.snapshot() || null,
411
417
  });
412
418
 
@@ -435,6 +441,7 @@ try {
435
441
  modelRefreshTimer.unref?.();
436
442
  }
437
443
 
444
+ startupComplete = true;
438
445
  console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
439
446
 
440
447
  const shutdown = async (signal) => {
@@ -17,6 +17,8 @@ The CLI composes the service. Client integration owns its `configure`, `start`,
17
17
  `snapshot` and `close` operations. It does not forward inference requests or
18
18
  render the dashboard. The adapter exposes integration snapshots and keeps
19
19
  management/MCP routes separate from the Responses path.
20
+ The HTTP dispatch boundary rejects browser Origin-bearing inference requests
21
+ before body admission, credential use or provider dispatch; native LAN opt-in is unchanged.
20
22
 
21
23
  Package installation is an explicit management operation in `package-update.mjs`,
22
24
  not part of inference or optional client integration. Windows uses the system
@@ -29,6 +31,9 @@ global target. A different target warns, but never changes PATH or prefix. Its
29
31
  bounded npm probe is limited to explicit update and full doctor commands.
30
32
  Its stdout/stderr are captured separately; npm configuration warnings do not
31
33
  leak into doctor output. The real installer's inherited streams are unchanged.
34
+ After installation, the updater verifies bounded package metadata at that same
35
+ selected target, with exact-version verification for GitHub. It never equates
36
+ installation with replacement of an already-running service.
32
37
 
33
38
  Authentication keeps its public facade in `auth.mjs`. Device-code polling and
34
39
  cancellation live in `auth-device-flow.mjs`; local discovery and transactional
@@ -76,6 +81,23 @@ only, preserves company/user routing, and never treats a saved preference as
76
81
  proof of a running route or visible candidate. App compatibility is rechecked only
77
82
  when its recorded identity changes, before existing trust/port checks are reused.
78
83
 
84
+ `native-prediction-protocol.mjs` owns bounded archive recognition only, independent
85
+ of certificates, networking and the CLI. It accepts multiple named hashed chunks
86
+ without assuming the first general-settings chunk is the implementation. Signature
87
+ and profile checks remain in the existing platform boundary.
88
+
89
+ Explicit `prediction fix` uses the optional integration's serialized lifecycle,
90
+ not a second adapter or detached predictor. Startup, repair and shutdown cannot
91
+ create overlapping owned listeners. Healthy/current bridges are retained; explicit
92
+ recreation preserves the saved port and existing trust and starts one new supervised
93
+ lifecycle. The supervisor delegates health/route checks to its current bridge after
94
+ recovery, not a closed initial transport. The health endpoint advertises repair
95
+ capability only when the composition root supplies that operation.
96
+ `native-prediction-fix.mjs` is the bounded local management client; the adapter
97
+ enforces loopback/Host/Origin/method/media/body boundaries before dispatch. No new
98
+ inference-path work, watcher, runtime dependency, forced App restart or unverified
99
+ hot-attachment mechanism is introduced.
100
+
79
101
  `startup-ui.mjs` is pure terminal presentation: a static A atom, aligned checks
80
102
  and the common new/reused-service footer. It depends only on terminal/status
81
103
  utilities, not on inference or platform probes. The CLI feeds existing lifecycle
@@ -95,6 +117,10 @@ Without a complete verified local source, rejection still returns
95
117
  `ccdx_history_rebuild_required`, without modifying stored history. Diagnostic
96
118
  metadata cannot reconstruct unavailable encrypted memory. LAN/browser callers
97
119
  and referenced/split histories do not gain filesystem recovery access.
120
+ The recovery module reuses the existing abort-aware singleflight for equivalent
121
+ source reads, not prepared requests or reservation handles. Caller validation and
122
+ admission remain independent. Only bounded snapshot-bound failure codes survive
123
+ settlement for two seconds; no successful plaintext cache or transcript index exists.
98
124
 
99
125
  ## Dashboard reads
100
126
 
@@ -146,6 +172,9 @@ dashboard merges recent HTTP, model and request-timeline failures for display.
146
172
  Tests cover module dependency direction, default-off behavior, concurrent writers,
147
173
  proxy handshakes, TLS validation, streaming, history isolation and release lookup.
148
174
  Performance measurements distinguish request preparation from model latency.
175
+ Actual loopback HTTP tests gate first-delta delivery before provider completion
176
+ and cancellation propagation for both native Responses and Chat translation.
177
+ Empty-stream diagnostics are additive scalar metadata, not a new retry policy.
149
178
  Release reports describe a specific environment, not an SLA or a guarantee of
150
179
  compatibility with every future client or corporate network policy.
151
180
  CI runs Node 22.15 and 24 on Linux, Windows and macOS. The owned temporary-prefix
package/docs/REFERENCE.md CHANGED
@@ -112,6 +112,8 @@ ccdx prediction on
112
112
  # Restart the running CCDX process, then launch Codex through ccdx.
113
113
  ccdx
114
114
  ccdx prediction status
115
+ # Repair only an already-enabled bridge in a compatible running CCDX service:
116
+ ccdx prediction fix
115
117
 
116
118
  # To remove the optional setup, fully quit Codex first:
117
119
  ccdx prediction off
@@ -200,7 +202,7 @@ Since `0.9.34`, an enabled bridge has a lightweight 30-second listener check.
200
202
  Healthy checks do not spawn processes, call upstream, inspect transcripts or
201
203
  probe model endpoints. A failed owned listener/native company-routing worker can
202
204
  be recreated on the saved port, using the same checked profile and certificate.
203
- There are at most three recovery attempts per CCDX process, with 30/60/120-second
205
+ There are at most three automatic recovery attempts per bridge lifecycle, with 30/60/120-second
204
206
  backoff gates; checks themselves run every 30 seconds. Occupied ports are not
205
207
  stolen or rotated. Startup failures do not gain a retry loop, and configuration
206
208
  HTTP errors or missing gray text alone do not trigger transport restarts. Existing
@@ -208,6 +210,36 @@ requests can fail during an outage and are never replayed by this supervisor.
208
210
  Disabled prediction startup creates no recovery timer. The existing in-memory
209
211
  overlay switch still observes explicit on/off changes independently.
210
212
 
213
+ `ccdx prediction fix` asks the running adapter for one explicit repair, without
214
+ starting another core service or forcibly restarting Codex. Disabled predictions
215
+ remain off. Healthy/current bridges are kept; a failed bridge or changed App identity
216
+ reuses the saved port, certificate and verified profile. Compatibility, certificate,
217
+ company proxy and port-ownership checks are not bypassed. Certificates are not renewed
218
+ by fix; setup problems can still require a normal closed-App `prediction on` action.
219
+ An explicit successful recreation starts a fresh three-attempt automatic recovery
220
+ lifecycle; it is not an automatic retry loop for initialization failures.
221
+
222
+ The command checks the adapter's advertised `prediction-fix-v1` capability before
223
+ posting bounded JSON to the native-loopback-only `/_ccdx/prediction/fix` endpoint.
224
+ Browser Origin headers, remote peers and non-JSON bodies are refused. A repair does
225
+ not count as model traffic. An older running adapter needs one upgrade/service restart
226
+ to gain this endpoint; the new CLI cannot hot-upgrade an old Node process.
227
+
228
+ Repair reports bridge readiness separately from the inspected App launch route.
229
+ If a running App has no verified route, fix returns a partial result (exit 1), preserves
230
+ its process and asks for a normal full quit followed by `ccdx`. A closed App is not
231
+ launched by fix; run `ccdx` to open it. Neither HTTP 200 nor a verified route proves
232
+ that gray text appeared. Normal replies, image setup and account state are not changed.
233
+ Unavailable/ambiguous process inspection reports `route_unverified` (exit 1), not
234
+ a definite missing route or an instruction to restart an otherwise healthy App.
235
+
236
+ App compatibility inspection checks up to 16 named main candidates and 16 named
237
+ general-settings candidates, rather than assuming the first hashed chunk owns the
238
+ implementation. A forwarding chunk therefore cannot hide a later real settings
239
+ module. Reads retain a 32 MiB header limit, 32/4 MiB per-entry main/settings limits,
240
+ a combined 36 MiB source limit, archive bounds/snapshot checks and platform signature
241
+ verification. Unknown layouts remain unsupported instead of being patched blindly.
242
+
211
243
  Before enabled App launch, CCDX can persist its PAC in that verified profile's
212
244
  `Default/Preferences`, but only in a direct environment, with initialized regular
213
245
  profile files and the App closed. Existing explicit App proxies and all company
@@ -262,6 +294,13 @@ One in-process adapter listens on `127.0.0.1:2026` by default and exposes:
262
294
 
263
295
  Responses-only models and compaction use Copilot's Responses transport directly. For requests routed through Chat Completions, CCDX converts the supported text, image, and function-tool subset and rejects incompatible message content rather than turning it into JSON text. Chat `length` and `content_filter` finish reasons become incomplete Responses in both streaming and non-streaming modes. Both streaming SSE and non-streaming responses are supported.
264
296
 
297
+ Chat conversion maps an explicitly supplied `reasoning.effort` to `reasoning_effort`.
298
+ Known effort values are checked against the existing model catalog when it advertises
299
+ an effort array; without that metadata, upstream validation remains authoritative.
300
+ No extra model lookup is made. Malformed function tools, forced undeclared functions,
301
+ unsupported tool-choice strings and unknown text formats receive a local compatibility
302
+ error instead of being dropped. Native Responses request fields are not changed by this check.
303
+
265
304
  The adapter handles response history, encrypted reasoning state, function/custom tools, images, compaction, cancellation, retries, and usage metadata within the compatibility boundaries below. Routing prefers endpoint metadata from Copilot's live or cached catalog; when metadata is unavailable, a small built-in set identifies known Responses-only GPT models.
266
305
 
267
306
  ### Local compaction recovery
@@ -297,6 +336,15 @@ a 16-candidate bound. Decoded reads and the rebuilt body are bounded by the
297
336
  running adapter's decoded-body limit; history admission reservations cover
298
337
  recovery preparation. Requests cannot retry after visible output has begun.
299
338
 
339
+ Overlapping equivalent recovery readers share in-flight source discovery/decoding,
340
+ with independent cancellation and independent restored requests. Every caller retains
341
+ its admission reservation; exclusive admission can serialize reads instead of sharing.
342
+ Successful plaintext is not retained after the flight settles. Up to 32 failure-code
343
+ records last two seconds, keyed by the exact source file identity/size/timestamps,
344
+ thread, compaction digest and byte limit. Directory discovery still runs; missing
345
+ sources, cancellation, deadlines and unstable snapshots are not cached. Source changes
346
+ invalidate reuse. No transcript index, watcher or healthy-request scan is added.
347
+
300
348
  Neither the original rollout nor client configuration is rewritten. Recovery
301
349
  diagnostics contain type/count/status metadata, not transcript text, ciphertext
302
350
  or file paths. If verification fails, `ccdx_history_rebuild_required` includes
@@ -411,6 +459,9 @@ Credentials found are not labeled online-authorized, cached model lists are not
411
459
  labeled fresh upstream data, and image configuration is not a provider test.
412
460
  Ready reports core readiness independently of optional prediction/image warnings.
413
461
  Model refresh logs show counts; `ccdx models` retains the complete live list.
462
+ After Ready, background refresh uses the same two-column status/message layout as
463
+ other runtime logs. Status messages remove terminal controls and collapse newlines;
464
+ the static banner and multiline interactive prompts retain their own presentation.
414
465
  VS Code compatibility-version details remain available in debug logging. Startup
415
466
  does not wait for optional update/compression work or add online doctor/model probes.
416
467
 
@@ -574,6 +625,14 @@ Installer errors and nonzero exits fail the update without a success message or
574
625
  automatic retry. Missing Git, blocked dependency downloads or npm cache-only
575
626
  settings remain npm/environment errors, not fixed by changing the launcher.
576
627
 
628
+ After a zero installer exit, CCDX reads bounded metadata from npm's selected global
629
+ target and verifies the package name and stable version. GitHub requires the exact
630
+ selected release version. A missing/mismatched target fails verification without
631
+ retrying installation; if the global target could not be discovered, the command
632
+ explicitly reports that the installed version is unverified rather than announcing
633
+ an update. This check neither changes PATH/prefix/registry nor restarts a running
634
+ adapter, and it does not verify package-file integrity or npm's current latest tag.
635
+
577
636
  Normal startup checks the official GitHub `releases/latest` web endpoint once in
578
637
  the background, without accessing the npm registry or REST API. The anonymous
579
638
  check requires no PAT or Copilot credentials, has a two-second deadline, validates
@@ -697,6 +756,12 @@ curl -s http://127.0.0.1:2026/_ccdx/status | jq
697
756
 
698
757
  The status endpoint is restricted to the socket's real loopback address even when LAN binding is explicitly enabled. It reports fixed-size HTTP request counters separately from bounded `completed` / `incomplete` / `failed` / `cancelled` response outcomes by model and origin, plus bounded incomplete-reason counts, TTFT/TPOT histograms, admission pressure, memory use, response-history size/tree concentration/lookup misses, image queue/cache and adaptive-history state, model-cache counts, token expiry state, and the ten most recent upstream `response.failed` diagnostics retained by the running process. HTTP errors without a model terminal remain "without terminal" and retain their known origin; they are not counted as model failures. History eviction markers are not failed-request counts; `ccdx status` warns near the cache limit without deleting or compressing history. Failure diagnostics include the event type, model, error code/message, response/request IDs when supplied upstream, and retry outcome. Common credential forms, long opaque encrypted values, and explicitly labelled input/prompt/tool-content echoes are redacted. They are cleared when the adapter restarts. No request/response bodies, credential fields, or account profiles are copied into status. Arbitrary upstream prose cannot be guaranteed free of sensitive content; review diagnostics before sharing them.
699
758
 
759
+ `stream_performance.by_route.*.empty_stream_completions` counts completed streams
760
+ with no observed output and an explicit zero output-token count. The recent request's
761
+ `empty_stream_completion` flag records the same condition. Missing usage is not zero;
762
+ non-streaming replies and observed tool/refusal output are excluded. This diagnostic
763
+ does not change completion status, trigger a retry or reject legitimate empty replies.
764
+
700
765
  `image_mcp` has its own HTTP route counter. After the image handler has been used, `image_generation` separately reports active, succeeded, failed, busy, cancelled, and chat-file delivery-failure counts, including tool errors returned with HTTP 200. A delivery failure can accompany a successful generation; it never causes another generation. Before handler initialization this field is `null`, meaning not observed, not necessarily disabled. Status never initializes that handler, reads its provider credential, installs guidance, or probes the provider. Input-image optimization metrics remain separate. `logging` reports pending records/bytes, queue caps, overflow drops, and write failures for usage and enabled debug-file logging.
701
766
 
702
767
  `stream_performance.by_route` also reports `request_ttft_ms`, measured from adapter entry to the first observed output delta, including local preparation. The existing `ttft_ms` continues to start at upstream dispatch. Neither timestamp means the client has drained or displayed the output. `preparation_ms` contains bounded histograms for admission (including history reservations), body reading/decompression/JSON parsing, history materialization/compact preparation, image optimization, and request serialization. Each sample measures one operation, including failed operations; retries can add samples. These are diagnostic intervals rather than a complete breakdown of request time: body reading includes internal decoded-body admission waits; authentication, routing, and other preparation are not individually timed. Non-streaming requests contribute preparation samples without inventing a first-token measurement.
@@ -745,6 +810,7 @@ Recovery first tries compatible local credentials and starts Device Flow only wh
745
810
 
746
811
  - CCDX binds to loopback by default. Non-loopback hosts are rejected unless `CCDX_ALLOW_LAN=1` is set explicitly.
747
812
  - Enabling LAN binding exposes a Copilot-backed API to other reachable machines. Provide your own host firewall and network isolation; do not expose the listener to an untrusted network.
813
+ - Inference POSTs reject any browser `Origin` header before reading the body or contacting upstream, including simple `text/plain` requests. Native Codex/Node requests without Origin and deliberately enabled native LAN clients keep their existing access. This is not authentication or protection against untrusted local native programs.
748
814
  - The GitHub OAuth credential is stored locally at `~/.local/share/copilot-api/github_token`. Short-lived Copilot service tokens remain in process memory and are refreshed as needed.
749
815
  - The optional image API credential is stored separately with mode `0600` only after `ccdx enable-image`; it is never placed in Codex configuration or diagnostic output.
750
816
  - Runtime status and usage records retain metadata rather than request/response content. Diagnostic logging records status and error messages; it is not a general redaction layer for arbitrary error text. See Debug logging before sharing logs.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "0.9.34",
3
+ "version": "0.9.36",
4
4
  "description": "Use Codex App with GitHub Copilot",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -12,7 +12,7 @@ import { createRequestId, runWithRequestContext } from "./request-context.mjs";
12
12
  import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
13
13
  import { status } from "./status.mjs";
14
14
  import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
15
- import { ADAPTER_HEALTH_PATH, adapterHealthPayload } from "./running-adapter.mjs";
15
+ import { ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH, PREDICTION_FIX_CAPABILITY, adapterHealthPayload } from "./running-adapter.mjs";
16
16
  import { createResponsesCompactHandler, createResponsesHandler } from "./responses-handler.mjs";
17
17
  import { createResponsesImagePressureController } from "./responses-image-pressure.mjs";
18
18
  import { createResponseFailureDiagnostics, buildHttpFailureDetails } from "./response-failures.mjs";
@@ -204,6 +204,13 @@ export function createAdapterHandler(options = {}) {
204
204
  upstreamTimeoutMs,
205
205
  });
206
206
  const dispatch = async (req, res, pathname) => {
207
+ if (req.method === "POST" && ["/v1/responses", "/v1/responses/compact"].includes(pathname)
208
+ && Object.hasOwn(req.headers || {}, "origin")) {
209
+ const error = httpError("Browser origins are not allowed for inference", 403);
210
+ error.jsonBody = { error: { message: error.message, type: "invalid_request_error", code: "ccdx_browser_origin_forbidden" } };
211
+ sendJsonError(res, error, 403);
212
+ return;
213
+ }
207
214
  if (DASHBOARD_API_PATHS.has(pathname)) {
208
215
  const { handleDashboardApi } = await import("./dashboard-api.mjs");
209
216
  return handleDashboardApi(req, res, pathname, options.dashboardOptions);
@@ -246,7 +253,38 @@ export function createAdapterHandler(options = {}) {
246
253
  res.writeHead(200, { "Content-Type": "application/json" });
247
254
  const predictionPac = isLoopbackAddress(req.socket?.remoteAddress) && isLoopbackHostHeader(req.headers?.host)
248
255
  ? options.nativePredictionPac?.() : null;
249
- res.end(JSON.stringify({ ...adapterHealthPayload(), ...(predictionPac ? { native_prediction_pac: predictionPac } : {}) }));
256
+ const health = adapterHealthPayload();
257
+ res.end(JSON.stringify({ ...health,
258
+ capabilities: [...health.capabilities, ...(typeof options.fixPrediction === "function" ? [PREDICTION_FIX_CAPABILITY] : [])],
259
+ ...(predictionPac ? { native_prediction_pac: predictionPac } : {}) }));
260
+ return;
261
+ }
262
+
263
+ if (pathname === ADAPTER_PREDICTION_FIX_PATH) {
264
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers?.host === undefined
265
+ || !isLoopbackHostHeader(req.headers.host) || Object.hasOwn(req.headers, "origin")) {
266
+ sendJsonError(res, httpError("Prediction repair is available only to native loopback clients", 403));return;
267
+ }
268
+ if (req.method !== "POST") {
269
+ res.setHeader?.("Allow", "POST");sendJsonError(res, httpError("Prediction repair requires POST", 405));return;
270
+ }
271
+ if (String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase() !== "application/json") {
272
+ sendJsonError(res, httpError("Prediction repair requires application/json", 415));return;
273
+ }
274
+ if (typeof options.fixPrediction !== "function") {
275
+ sendJsonError(res, httpError("This adapter does not support prediction repair; upgrade and restart CCDX once", 503));return;
276
+ }
277
+ const abort = createRequestAbort(req, res);abort.setTimeout(2000);
278
+ try {
279
+ const body = await readJsonBody(req, { maxBodyBytes: 1024, maxDecodedBodyBytes: 1024, signal: abort.signal });
280
+ if (!body || Object.keys(body).length !== 1 || body.action !== "fix") throw httpError("Expected prediction repair action: fix", 400);
281
+ abort.clearTimeout();
282
+ const result = await options.fixPrediction();
283
+ if (!res.destroyed && !res.writableEnded) {
284
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(result));
285
+ }
286
+ } catch (error) { sendJsonError(res, error, 503); }
287
+ finally { abort.cleanup(); }
250
288
  return;
251
289
  }
252
290
 
@@ -390,6 +428,7 @@ export function createAdapterHandler(options = {}) {
390
428
  const trackRequest = pathname !== ADAPTER_HEALTH_PATH
391
429
  && pathname !== ADAPTER_STATUS_PATH
392
430
  && pathname !== ADAPTER_CACHE_PATH
431
+ && pathname !== ADAPTER_PREDICTION_FIX_PATH
393
432
  && !DASHBOARD_API_PATHS.has(pathname)
394
433
  && !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
395
434
  const routeName = classifyAdapterRoute(req.method, pathname);
@@ -255,7 +255,7 @@ export function parseCliArgs(args = []) {
255
255
  }
256
256
  if (command === "prediction") {
257
257
  const [action = "status", ...extra] = rest;
258
- if (!["on", "off", "status"].includes(action)) throw new Error("Prediction action must be on, off, or status");
258
+ if (!["on", "off", "status", "fix"].includes(action)) throw new Error("Prediction action must be on, off, status, or fix");
259
259
  if (extra.length) unexpectedArgs(extra);
260
260
  return baseCommand("prediction", { action });
261
261
  }
@@ -372,7 +372,7 @@ function topicHelp(name, topic) {
372
372
  "image-status": `Usage:\n ${name} image-status\n\nShows provider configuration and locally advertised generation/editing tools without generating an image or exposing its API key.`,
373
373
  "auto-review-model": `Usage:\n ${name} auto-review-model\n\nSelect a Responses model, then an advertised reasoning effort. Enter keeps the default/current choice; q cancels both steps without saving. Effort 0 follows the client (low when omitted). Settings apply only to Auto-review on the next request; no client patch or restart is required for adapters running 0.9.13 or newer.`,
374
374
  "suggestion": `The CCDX prediction panel has been retired. Run ${name} suggestion off to safely remove unchanged CCDX registrations. This cleanup does not change native predictions; see ${name} prediction --help for that separate opt-in feature.`,
375
- prediction: `Usage:\n ${name} prediction [status|on|off]\n\nOptional native next-message predictions; off by default. macOS and Windows. Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup. Quit Codex before on/off, then restart ccdx. On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com. HTTPS on those hosts is decrypted locally; only prediction configuration is changed. No client program files, OS trust, account permissions, MCP or Hooks are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved. Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD and CIDR bypass rules are reported as unsupported. The bridge port persists across restarts/updates; a busy saved port disables only predictions. Launch/reuse checks the App's actual route; an older random or missing route may require one full App quit. Official prediction configuration is preserved; the conversation's model is used. App updates require another compatibility check. Status distinguishes saved preference and observed config traffic from unverified candidate visibility.`,
375
+ prediction: `Usage:\n ${name} prediction [status|on|off|fix]\n\nOptional native next-message predictions; off by default. macOS and Windows. Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup. Quit Codex before on/off, then restart ccdx. On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com. HTTPS on those hosts is decrypted locally; only prediction configuration is changed. No client program files, OS trust, account permissions, MCP or Hooks are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved. Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD and CIDR bypass rules are reported as unsupported. The bridge port persists across restarts/updates; a busy saved port disables only predictions. Launch/reuse checks the App's actual route; an older random or missing route may require one full App quit. Official prediction configuration is preserved; the conversation's model is used. App updates require another compatibility check. Status distinguishes saved preference and observed config traffic from unverified candidate visibility.\n\nFix asks a compatible running CCDX adapter to repair the enabled bridge once on its saved port. It never enables predictions, renews certificates or force-restarts Codex. Healthy bridges are retained. Missing App routes require a normal full quit and ccdx launch; partial repair exits 1. An older adapter must first be upgraded and restarted once to gain this repair endpoint.`,
376
376
  update: `Usage:\n ${name} update [npm|github]\n\nUpdates the global package from the configured npm registry or the latest stable GitHub release. With no source, an interactive terminal prompts for one. Windows uses system cmd.exe to run npm.cmd without changing PowerShell policy; use the .cmd entrypoint if scripts are blocked. GitHub installs require Git on PATH and dependencies may still use the configured npm registry. Restart the running adapter after installation.`,
377
377
  version: `Usage:\n ${name} --version`,
378
378
  };
@@ -398,7 +398,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
398
398
  ${name} disable-image
399
399
  ${name} image-status
400
400
  ${name} auto-review-model
401
- ${name} prediction [status|on|off]
401
+ ${name} prediction [status|on|off|fix]
402
402
  ${name} update [npm|github]
403
403
  ${name} --version
404
404
  ${name} --help
@@ -7,9 +7,27 @@ import { supervisePrediction } from "./native-prediction-recovery.mjs";
7
7
 
8
8
  // The CLI composes the services; this module owns optional client integration
9
9
  // lifecycle. It never forwards model requests or depends on dashboard rendering.
10
- export function createClientIntegration({ port, host, info = () => {}, warning = () => {}, configLog } = {}) {
10
+ export function createClientIntegration({ port, host, info = () => {}, warning = () => {}, configLog,
11
+ startPrediction = async options => (await import("./native-prediction.mjs")).startNativePrediction(options) } = {}) {
11
12
  const prediction = createPredictionState();
12
13
  let native = null;
14
+ let operation = null, operationName = null, closed = false;
15
+ async function startPredictionBridge(expectedPort) {
16
+ const started = await startPrediction({ state: prediction, warning: info, ...(expectedPort ? { expectedPort } : {}) });
17
+ if (!started) return null;
18
+ if (closed) { await started.close();return null; }
19
+ const port = Number(new URL(started.pacUrl).port);
20
+ prediction.supervising();
21
+ return supervisePrediction({ native: started, state: prediction, warning,
22
+ restart: () => startPrediction({ state: prediction, warning: info, expectedPort: port }) });
23
+ }
24
+ function serialize(name, task) {
25
+ if (closed) return Promise.reject(new Error("Client integration is closing; repair was skipped"));
26
+ if (operation) return operationName === name ? operation : operation.then(() => serialize(name, task));
27
+ operationName = name;
28
+ operation = Promise.resolve().then(task).finally(() => { operation = null;operationName = null; });
29
+ return operation;
30
+ }
13
31
  return {
14
32
  async configure() {
15
33
  try {
@@ -28,21 +46,36 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
28
46
  }
29
47
  return { imageEnabled: enabled, imageMcpSkipped, compressionSetup: runInBackground(ensureCodexThreadCompression) };
30
48
  },
31
- async start() {
49
+ start() { return serialize("start", async () => {
32
50
  try {
33
- const { startNativePrediction } = await import("./native-prediction.mjs");
34
- native = await startNativePrediction({ state: prediction, warning: info });
35
- if (native) {
36
- const expectedPort = Number(new URL(native.pacUrl).port);
37
- native = supervisePrediction({ native, state: prediction, warning,
38
- restart: () => startNativePrediction({ state: prediction, warning: info, expectedPort }) });
39
- }
51
+ native ||= await startPredictionBridge();
40
52
  } catch (error) { prediction.unavailable(error); warning(`${error.message}. Core startup will continue.`); }
41
53
  return native;
42
- },
54
+ }); },
55
+ fix() { return serialize("fix", async () => {
56
+ let restarted = false, route = "unknown";
57
+ try {
58
+ if (!native?.healthy() || native.enabled?.() === false || native.appCurrent?.() === false) {
59
+ const expectedPort = native ? Number(new URL(native.pacUrl).port) : undefined;
60
+ await native?.close();native = null;
61
+ native = await startPredictionBridge(expectedPort);restarted = Boolean(native);
62
+ }
63
+ } catch (error) { prediction.unavailable(error); }
64
+ let routeError = false;
65
+ if (native && !closed) {
66
+ try {
67
+ await native.prepareRoute?.();
68
+ route = await native.inspectRoute?.() || "unverified";
69
+ } catch { routeError = true;warning("Prediction bridge is ready, but App route inspection failed"); }
70
+ }
71
+ const snapshot = prediction.snapshot();
72
+ const status = !snapshot.configured && snapshot.bridge !== "unavailable" ? "disabled" : snapshot.bridge !== "running" ? "failed"
73
+ : route === "verified" || route === "closed" ? "ready" : route === "missing" ? "needs_app_relaunch" : "route_unverified";
74
+ return { status, bridge_restarted: restarted, app_route: route, ...(routeError ? { route_error: true } : {}), prediction: snapshot };
75
+ }); },
43
76
  pacUrl() { return native?.pacUrl || null; },
44
77
  launched(route) { prediction.launch(route); },
45
78
  snapshot() { return { prediction: prediction.snapshot() }; },
46
- async close() { await native?.close(); native = null; },
79
+ async close() { closed = true;try { await operation; } finally { await native?.close();native = null; } },
47
80
  };
48
81
  }
@@ -23,7 +23,7 @@
23
23
 
24
24
  <main>
25
25
  <section class="intro">
26
- <h1><span aria-hidden="true">$</span> ccdx status</h1>
26
+ <h1><svg class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg> ccdx status</h1>
27
27
  <div class="snapshot-meta"><p id="auth-account" role="status" data-i18n data-i18n-title title="Saved GitHub Copilot account / local credentials only; not an online entitlement check.">GitHub / READING</p><p id="updated" data-i18n>Reading status…</p></div>
28
28
  </section>
29
29
 
@@ -24,7 +24,7 @@ button:disabled { opacity: .55; cursor: wait; }
24
24
  :root[data-theme="light"] .icon-moon { display: block; }
25
25
  .intro { display: flex; justify-content: space-between; align-items: baseline; gap: 20px; padding: 38px 0 25px; }
26
26
  h1 { margin: 0; font-size: clamp(20px, 3vw, 27px); font-weight: 650; letter-spacing: -.035em; }
27
- h1 span { color: var(--accent-soft); }
27
+ .status-icon { display: inline-block; width: 1em; height: 1em; vertical-align: -.125em; color: var(--accent); }
28
28
  .intro p { margin: 0; color: var(--subtle); font-size: 11px; }
29
29
  .snapshot-meta { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: baseline; gap: 8px 18px; min-width: 0; }
30
30
  .intro .snapshot-meta p { margin: 0; overflow-wrap: anywhere; }
@@ -8,9 +8,14 @@ import { isLoopbackAddress, isLoopbackHostHeader, isLanAllowed } from "./securit
8
8
  import { decodedBodyLimitPreference } from "./user-settings.mjs";
9
9
  import { isResponsesToolOutputItem, readResponsesToolOutputParts } from "./responses-content.mjs";
10
10
  import { prepareResponsesRequest } from "./responses-request.mjs";
11
+ import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
11
12
 
12
13
  const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
13
14
  const CALLS = new Map([["function_call", "function_call_output"], ["custom_tool_call", "custom_tool_call_output"]]);
15
+ const sourceFlights = createAbortAwareSingleflight();
16
+ const sourceFailures = new Map();
17
+ const REUSABLE_FAILURES = new Set(["invalid_rollout", "incomplete_rollout", "rollout_identity_mismatch",
18
+ "plaintext_content_missing", "unsupported_rollout_item", "unsupported_history_change", "matching_rollout_missing", "ambiguous_rollout"]);
14
19
 
15
20
  function unavailable(code) {
16
21
  return Object.assign(new Error("Verified local plaintext history is unavailable"), { code });
@@ -189,6 +194,52 @@ function joinHistory(source, input, compactionIndex, check) {
189
194
  return { items, currentInputStart: source.length + instructions.length };
190
195
  }
191
196
 
197
+ async function sourceVersion(files) {
198
+ return JSON.stringify(await Promise.all(files.map(async file => {
199
+ const stat = await fs.lstat(file);
200
+ if (!stat.isFile() || stat.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
201
+ return [file, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs];
202
+ })));
203
+ }
204
+
205
+ async function loadSource(directory, id, ciphertext, limit, timeoutMs, signal) {
206
+ const started = Date.now();
207
+ const check = () => {
208
+ if (signal.aborted) throw signal.reason;
209
+ if (Date.now() - started > timeoutMs) throw unavailable("rollout_read_timeout");
210
+ };
211
+ const files = await candidateFiles(directory, id, check);
212
+ const version = await sourceVersion(files);
213
+ // Cache only failure codes for exact file snapshots, never plaintext or a
214
+ // missing directory. Discovery still runs so added pages are not hidden.
215
+ const key = createHash("sha256").update(JSON.stringify([directory, id, ciphertext, limit, version])).digest("hex");
216
+ const cached = sourceFailures.get(key);
217
+ if (cached && cached.until > Date.now()) throw unavailable(cached.code);
218
+ sourceFailures.delete(key);
219
+ try {
220
+ let source;
221
+ const budget = { remaining: limit };
222
+ for (const file of files) {
223
+ check();
224
+ const candidate = await readPrefix(file, directory, id, ciphertext, budget, check, signal);
225
+ if (!candidate) continue;
226
+ if (source) throw unavailable("ambiguous_rollout");
227
+ source = candidate;
228
+ }
229
+ if (!source) throw unavailable("matching_rollout_missing");
230
+ if (await sourceVersion(files) !== version) throw unavailable("rollout_changed");
231
+ return source;
232
+ } catch (error) {
233
+ if (files.length && !signal.aborted && REUSABLE_FAILURES.has(error.code)
234
+ && await sourceVersion(files) === version) {
235
+ for (const [old, value] of sourceFailures) if (value.until <= Date.now()) sourceFailures.delete(old);
236
+ while (sourceFailures.size >= 32) sourceFailures.delete(sourceFailures.keys().next().value);
237
+ sourceFailures.set(key, { code: error.code, until: Date.now() + 2000 });
238
+ }
239
+ throw error;
240
+ }
241
+ }
242
+
192
243
  // Loaded only after a confirmed provider ownership rejection, never on startup
193
244
  // or healthy requests. It cannot serve remote/browser callers or mutate logs.
194
245
  export async function recoverLocalCompaction(reqContext, { request, env = process.env,
@@ -215,18 +266,11 @@ export async function recoverLocalCompaction(reqContext, { request, env = proces
215
266
  release = await reserveHistory?.(limit, { signal });
216
267
  check();
217
268
  const directory = await fs.realpath(codexPaths({ env }).directory);
218
- const files = await candidateFiles(directory, id, check);
219
- const budget = { remaining: limit };
220
- let source;
221
- for (const file of files) {
222
- check();
223
- const candidate = await readPrefix(file, directory, id, compactions[0].encrypted_content, budget, check, signal);
224
- if (!candidate) continue;
225
- if (source) throw unavailable("ambiguous_rollout");
226
- source = candidate;
227
- }
228
- if (!source) throw unavailable("matching_rollout_missing");
229
- const restored = joinHistory(source.items, input, input.indexOf(compactions[0]), check);
269
+ const ciphertext = compactions[0].encrypted_content;
270
+ const key = createHash("sha256").update(JSON.stringify([directory, id, ciphertext, limit, timeoutMs])).digest("hex");
271
+ const source = await sourceFlights.run(key, sharedSignal => loadSource(directory, id, ciphertext, limit, timeoutMs, sharedSignal), { signal });
272
+ check();
273
+ const restored = joinHistory(structuredClone(source.items), input, input.indexOf(compactions[0]), check);
230
274
  const body = { ...reqContext.body, input: restored.items };
231
275
  delete body.previous_response_id;
232
276
  const bodyBytes = Buffer.byteLength(JSON.stringify(body));
@@ -0,0 +1,27 @@
1
+ import { checkRunningAdapter, ADAPTER_PREDICTION_FIX_PATH, PREDICTION_FIX_CAPABILITY } from "./running-adapter.mjs";
2
+ import { readBoundedResponseText } from "./upstream-body.mjs";
3
+
4
+ // Management request only. An older running adapter cannot be hot-upgraded by
5
+ // a new CLI, and a successful HTTP response is not proof of a visible prediction.
6
+ export async function requestPredictionFix({ host = "127.0.0.1", port = 2026, fetchImpl = fetch,
7
+ timeoutMs = 45_000, probeTimeoutMs = 5000 } = {}) {
8
+ const probe = await checkRunningAdapter({ host, port, fetchImpl: (url, options) => fetchImpl(url, { ...options, redirect: "error" }), timeoutMs: probeTimeoutMs,
9
+ requiredCapabilities: [PREDICTION_FIX_CAPABILITY] });
10
+ if (!probe.ok) throw new Error(probe.incompatible
11
+ ? "The running adapter lacks compatible prediction repair. Upgrade and restart the CCDX service once; the App was not restarted."
12
+ : "Could not reach a running CCDX adapter. Start ccdx, then retry ccdx prediction fix.");
13
+ const signal = AbortSignal.timeout(timeoutMs);
14
+ const response = await fetchImpl(probe.baseUrl + ADAPTER_PREDICTION_FIX_PATH, {
15
+ method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" },
16
+ body: JSON.stringify({ action: "fix" }), redirect: "error", signal,
17
+ });
18
+ const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, label: "Prediction repair response", signal });
19
+ if (!response.ok) throw new Error(`Prediction repair returned HTTP ${response.status}; no App was restarted`);
20
+ let value;try { value = JSON.parse(text); } catch {}
21
+ if (!["ready", "disabled", "failed", "needs_app_relaunch", "route_unverified"].includes(value?.status)
22
+ || !["running", "stopped", "unavailable", "recovering"].includes(value?.prediction?.bridge)
23
+ || value.prediction.candidate !== "unknown"
24
+ || (["ready", "needs_app_relaunch", "route_unverified"].includes(value.status) && value.prediction.bridge !== "running")
25
+ || (value.status === "ready" && !["verified", "closed"].includes(value.app_route))) throw new Error("Adapter returned an invalid prediction repair result");
26
+ return value;
27
+ }
@@ -11,6 +11,7 @@ import { codexPaths } from "./codex-paths.mjs";
11
11
  import { assertWindowsCodexClosed, installedWindowsPredictionApp, windowsPredictionProfile,
12
12
  windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
13
13
  import { windowsPredictionCertificate } from "./windows-prediction-certificate.mjs";
14
+ import { inspectPredictionArchive } from "./native-prediction-protocol.mjs";
14
15
 
15
16
  export function predictionPaths({ env = process.env, home = os.homedir(), platform = process.platform, app } = {}) {
16
17
  const directory = path.join(path.dirname(userSettingsPath({ env, home })), "native-prediction");
@@ -64,35 +65,17 @@ export function installedPredictionApp({ exec = execFileSync, platform = process
64
65
  for (const candidate of candidates) {
65
66
  const { app, archive } = candidate;
66
67
  if (!fs.existsSync(archive)) continue;
67
- // Check only during explicit setup; startup uses the cheap identity check.
68
- const fd = fs.openSync(archive, "r");
69
- try {
70
- const prefix = Buffer.alloc(16); fs.readSync(fd, prefix, 0, 16, 0);
71
- const headerSize = prefix.readUInt32LE(12);
72
- if (headerSize > 32 * 1024 * 1024) continue;
73
- const header = Buffer.alloc(headerSize); fs.readSync(fd, header, 0, header.length, 16);
74
- const files = JSON.parse(header).files?.[".vite"]?.files?.build?.files;
75
- const entry = Object.entries(files || {}).find(([name]) => /^main-[\w-]+\.js$/.test(name))?.[1];
76
- if (!entry || entry.size > 32 * 1024 * 1024 || entry.unpacked) continue;
77
- const bytes = Buffer.alloc(entry.size);
78
- fs.readSync(fd, bytes, 0, bytes.length, 8 + prefix.readUInt32LE(4) + Number(entry.offset));
79
- const source = bytes.toString();
80
- if (!["/wham/predictions/config", "experimentalPredictionMode"].every((value) => source.includes(value))) continue;
81
- const renderer = Object.entries(JSON.parse(header).files?.webview?.files?.assets?.files || {})
82
- .find(([name]) => /^general-settings-[\w-]+\.js$/.test(name))?.[1];
83
- if (!renderer || renderer.unpacked || renderer.size > 4 * 1024 * 1024) continue;
84
- const rendererBytes = Buffer.alloc(renderer.size);
85
- fs.readSync(fd, rendererBytes, 0, rendererBytes.length, 8 + prefix.readUInt32LE(4) + Number(renderer.offset));
86
- if (!rendererBytes.includes(Buffer.from("4290031608"))) continue;
87
- if (platform !== "win32") exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
88
- const stat = fs.statSync(archive);
89
- if (platform === "win32") {
90
- const executable = fs.statSync(app);
91
- return { ...candidate, profile: windowsPredictionProfile({ app: candidate, env: options.env, preferredProfile: options.preferredProfile }),
92
- size: stat.size, mtimeMs: stat.mtimeMs, executableSize: executable.size, executableMtimeMs: executable.mtimeMs };
93
- }
94
- return { app, archive, size: stat.size, mtimeMs: stat.mtimeMs };
95
- } finally { fs.closeSync(fd); }
68
+ const inspected = inspectPredictionArchive(archive);
69
+ if (!inspected.compatible) continue;
70
+ if (platform !== "win32") exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
71
+ const stat = fs.statSync(archive);
72
+ if (stat.size !== inspected.size || stat.mtimeMs !== inspected.mtimeMs) throw new Error("Codex App changed during compatibility verification");
73
+ if (platform === "win32") {
74
+ const executable = fs.statSync(app);
75
+ return { ...candidate, profile: windowsPredictionProfile({ app: candidate, env: options.env, preferredProfile: options.preferredProfile }),
76
+ size: stat.size, mtimeMs: stat.mtimeMs, executableSize: executable.size, executableMtimeMs: executable.mtimeMs };
77
+ }
78
+ return { app, archive, size: stat.size, mtimeMs: stat.mtimeMs };
96
79
  }
97
80
  throw new Error("This Codex App does not expose the verified native prediction protocol; setup was skipped");
98
81
  }
@@ -0,0 +1,45 @@
1
+ import fs from "node:fs";
2
+
3
+ const MAX_HEADER_BYTES = 32 * 1024 * 1024;
4
+ const MAX_SOURCE_BYTES = 36 * 1024 * 1024;
5
+
6
+ // Inspect only packed, named protocol/settings candidates in the installed
7
+ // archive. A small forwarding chunk must not hide its real implementation.
8
+ export function inspectPredictionArchive(archive) {
9
+ const fd = fs.openSync(archive, "r");
10
+ try {
11
+ const before = fs.fstatSync(fd);
12
+ const read = (size, offset) => {
13
+ if (!before.isFile() || !Number.isSafeInteger(size) || size < 0 || !Number.isSafeInteger(offset)
14
+ || offset < 0 || offset + size > before.size) throw new Error("Invalid prediction App archive bounds");
15
+ const bytes = Buffer.alloc(size);
16
+ if (fs.readSync(fd, bytes, 0, size, offset) !== size) throw new Error("Prediction App archive changed during inspection");
17
+ return bytes;
18
+ };
19
+ const prefix = read(16, 0), headerSize = prefix.readUInt32LE(12);
20
+ if (headerSize > MAX_HEADER_BYTES) throw new Error("Prediction App archive header exceeds its inspection limit");
21
+ const tree = JSON.parse(read(headerSize, 16)).files;
22
+ const base = 8 + prefix.readUInt32LE(4);
23
+ let sourceBytes = 0;
24
+ const contains = (files, pattern, markers, maxEntryBytes) => {
25
+ const entries = Object.entries(files || {}).filter(([name]) => pattern.test(name));
26
+ if (entries.length > 16) throw new Error("Prediction App protocol candidates exceed their inspection limit");
27
+ for (const [, entry] of entries) {
28
+ if (!entry || typeof entry !== "object") throw new Error("Invalid prediction App archive entry");
29
+ if (entry.unpacked) continue;
30
+ if (!Number.isSafeInteger(entry.size) || entry.size > maxEntryBytes
31
+ || sourceBytes + entry.size > MAX_SOURCE_BYTES) throw new Error("Prediction App source exceeds its inspection limit");
32
+ sourceBytes += entry.size;
33
+ const bytes = read(entry.size, base + Number(entry.offset));
34
+ if (markers.every(marker => bytes.includes(Buffer.from(marker)))) return true;
35
+ }
36
+ return false;
37
+ };
38
+ const compatible = contains(tree?.[".vite"]?.files?.build?.files, /^main-[\w-]+\.js$/,
39
+ ["/wham/predictions/config", "experimentalPredictionMode"], 32 * 1024 * 1024)
40
+ && contains(tree?.webview?.files?.assets?.files, /^general-settings-[\w-]+\.js$/, ["4290031608"], 4 * 1024 * 1024);
41
+ const after = fs.fstatSync(fd);
42
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) throw new Error("Prediction App archive changed during inspection");
43
+ return { compatible, size: after.size, mtimeMs: after.mtimeMs };
44
+ } finally { fs.closeSync(fd); }
45
+ }
@@ -33,6 +33,10 @@ export function supervisePrediction({ native, restart, state, warning = () => {}
33
33
  return {
34
34
  ...native,
35
35
  check,
36
+ healthy() { return !closed && current.healthy(); },
37
+ enabled() { return !closed && current.enabled?.() !== false; },
38
+ appCurrent() { return current.appCurrent?.() !== false; },
39
+ inspectRoute() { return current.inspectRoute?.(); },
36
40
  prepareRoute() { return current.prepareRoute?.(); },
37
41
  async close() { closed = true;clearIntervalImpl(timer);await flight;await current?.close(); },
38
42
  };
@@ -12,6 +12,7 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
12
12
  launch(route) { state.launch_route = ["verified", "persisted"].includes(route) ? route : "unverified"; },
13
13
  persistence(value) { state.persistence = value.status; },
14
14
  checked() { state.recovery.last_check_at = now(); },
15
+ supervising() { state.recovery.attempts = 0;state.recovery.last_check_at = null; },
15
16
  recovering(attempt) { state.bridge = "recovering";state.recovery.attempts = attempt;state.recovery.last_check_at = now(); },
16
17
  recovered() { state.bridge = "running";state.reason = null;delete state.error;state.recovery.recovered++; },
17
18
  unavailable(error) {
@@ -7,7 +7,7 @@ import { predictionPaths, readPredictionSettings, writePredictionSettings, asser
7
7
  import { retirePredictionIntegration } from "./prediction-retirement.mjs";
8
8
  import { networkRouteSnapshot } from "./network-route.mjs";
9
9
  import { withFileLock } from "./lock.mjs";
10
- import { windowsSystemProxy, windowsProxySettings, windowsProxyText } from "./native-prediction-windows.mjs";
10
+ import { windowsSystemProxy, windowsProxySettings, windowsProxyText, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
11
11
  import { updatePredictionRoute } from "./native-prediction-route.mjs";
12
12
 
13
13
  function systemProxy(exec = execFileSync, { platform = process.platform, env = process.env } = {}) {
@@ -36,7 +36,7 @@ function certificateDirectory(settings, paths) {
36
36
  }
37
37
 
38
38
  export async function runPredictionCommand(options = {}) {
39
- if (!options.action || options.action === "status") return runPredictionCommandUnlocked(options);
39
+ if (!options.action || ["status", "fix"].includes(options.action)) return runPredictionCommandUnlocked(options);
40
40
  if (!["darwin", "win32"].includes(options.platform || process.platform)) return runPredictionCommandUnlocked(options);
41
41
  const { settings } = predictionPaths(options);
42
42
  return withFileLock(`${settings}.lock`, () => runPredictionCommandUnlocked(options), { timeoutMs: 2000 });
@@ -44,9 +44,26 @@ export async function runPredictionCommand(options = {}) {
44
44
 
45
45
  async function runPredictionCommandUnlocked({ action = "status", env = process.env,
46
46
  platform = process.platform, output = console.log, resolveApp = installedPredictionApp,
47
- writeSettings = writePredictionSettings, runtimeSnapshot, ...options } = {}) {
47
+ writeSettings = writePredictionSettings, runtimeSnapshot, repairRuntime, ...options } = {}) {
48
48
  const opts = { ...options, env, platform };
49
49
  const settings = readPredictionSettings(opts);
50
+ if (action === "fix") {
51
+ if (!settings.enabled) {
52
+ output("Native predictions are off; nothing was enabled or changed. Run ccdx prediction on to opt in.");
53
+ return { status: "disabled", exitCode: 0 };
54
+ }
55
+ if (!repairRuntime) throw new Error("Prediction repair needs a running CCDX adapter with prediction-fix support");
56
+ const result = await repairRuntime();
57
+ const prediction = result.prediction;
58
+ output(`Prediction repair: ${result.status}; bridge: ${prediction.bridge}; candidate: ${prediction.candidate}`);
59
+ if (result.status === "disabled") output("The running adapter has predictions off; no feature was enabled.");
60
+ else if (prediction.bridge !== "running") output(prediction.reason || "Prediction bridge is unavailable; core service was not changed.");
61
+ else if (result.app_route === "verified") output("App launch route verified. A visible suggestion still needs an App-side check.");
62
+ else if (result.app_route === "closed") output("Bridge is ready. Run ccdx to open Codex with its prediction route.");
63
+ else if (result.status === "route_unverified") output("Bridge is ready, but App route inspection was unavailable or ambiguous. Check ccdx prediction status; no App was restarted.");
64
+ else output("Bridge is ready, but the running App route is not verified. No App was restarted. Fully quit Codex, then run ccdx to attach the route.");
65
+ return { ...result, exitCode: ["ready", "disabled"].includes(result.status) ? 0 : 1 };
66
+ }
50
67
  if (action === "status") {
51
68
  output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (default: off)`);
52
69
  output("Uses the conversation's model. No prediction MCP, Hook, or panel.");
@@ -65,7 +82,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
65
82
  }
66
83
  return settings;
67
84
  }
68
- if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, or status");
85
+ if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, status, or fix");
69
86
  if (!["darwin", "win32"].includes(platform)) throw new Error("Native prediction setup supports macOS and Windows only; no configuration changed");
70
87
  let paths = predictionPaths({ ...opts, app: settings.app });
71
88
  if (action === "off") {
@@ -238,7 +255,17 @@ export async function startNativePrediction({ env = process.env, platform = proc
238
255
  ...(platform === "win32" ? { profile: paths.profile } : {}),
239
256
  pacUrl: transport.pacUrl,
240
257
  enabled() { return enabled; },
258
+ appCurrent() { return predictionAppMatches(settings.app); },
241
259
  healthy() { return transport.healthy() && (!windowsNetwork || windowsNetwork.healthy()); },
260
+ async inspectRoute() {
261
+ const inspect = options.inspectAppProcesses || (platform === "win32" ? windowsPredictionAppProcesses
262
+ : (await import("./launcher.mjs")).macPredictionAppProcesses);
263
+ const rows = inspect(settings.app.app, opts);
264
+ const route = rows.length === 0 ? "closed" : rows.length !== 1 || !rows[0].readable ? "unverified"
265
+ : rows[0].route === transport.pacUrl ? "verified" : "missing";
266
+ state?.launch(route);
267
+ return route;
268
+ },
242
269
  async prepareRoute() {
243
270
  try {
244
271
  const direct = !windowsNetwork && !networkRoute?.http && !networkRoute?.https && !networkRoute?.bypass?.length;
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import { lookupLatestRelease, githubReleaseVersion } from "./version.mjs";
7
7
  import { terminalCell } from "./terminal-text.mjs";
8
+ import { readBoundedFileSync } from "./bounded-file.mjs";
8
9
 
9
10
  const PACKAGE_NAME = "codex-copilot-dx";
10
11
  const UPDATE_SPECS = {
@@ -84,6 +85,17 @@ function waitForExit(child) {
84
85
  });
85
86
  }
86
87
 
88
+ export function verifyInstalledPackage(target, { expectedVersion } = {}) {
89
+ if (!target) return null;
90
+ let pkg;
91
+ try { pkg = JSON.parse(readBoundedFileSync(path.join(target, "package.json"), { encoding: "utf8" })); } catch {}
92
+ if (pkg?.name !== PACKAGE_NAME || !githubReleaseVersion(pkg.version)
93
+ || (expectedVersion && pkg.version !== expectedVersion)) {
94
+ throw new Error("npm finished, but the target package version could not be verified. Check ccdx doctor; installation was not retried.");
95
+ }
96
+ return pkg.version;
97
+ }
98
+
87
99
  export async function runPackageUpdateCommand({
88
100
  commandName = "ccdx",
89
101
  env = process.env,
@@ -95,6 +107,7 @@ export async function runPackageUpdateCommand({
95
107
  spawnImpl = spawn,
96
108
  fetchImpl = fetch,
97
109
  inspectEnvironmentFn = inspectPackageUpdateEnvironment,
110
+ verifyInstalledFn = verifyInstalledPackage,
98
111
  } = {}) {
99
112
  let selectedSource = normalizeUpdateSource(source);
100
113
  if (source && !selectedSource) throw new Error(`Update source must be npm or github: ${source}`);
@@ -151,6 +164,12 @@ export async function runPackageUpdateCommand({
151
164
  ...launch.options,
152
165
  });
153
166
  await waitForExit(child);
154
- output.write(`Updated ${PACKAGE_NAME} from ${sourceLabel}. Restart the running adapter to use the new version.\n`);
167
+ const installedVersion = verifyInstalledFn(environment?.target, { expectedVersion: release?.version });
168
+ if (installedVersion) {
169
+ output.write(`Updated ${PACKAGE_NAME}: installed v${terminalCell(installedVersion)} at ${terminalCell(environment.target)}.\n`);
170
+ } else {
171
+ output.write("Installer finished; the global target was unavailable, so the installed version was not verified. Run ccdx doctor.\n");
172
+ }
173
+ output.write("Restart the running adapter to use the installed version; an existing service is not replaced automatically.\n");
155
174
  return { cancelled: false, source: selectedSource };
156
175
  }
@@ -122,7 +122,7 @@ export function createProfileModelRuntime({
122
122
  }
123
123
  const gptModelIds = gptModelIdsFromCopilotModels(models);
124
124
  if (gptModelIds.length) {
125
- emit("ok", `Refreshed GPT models from GitHub Copilot: ${gptModelIds.length} available; run ${commandName} models for the list`);
125
+ emit("ok", `Model catalog refreshed: ${gptModelIds.length} GPT models`);
126
126
  } else {
127
127
  emit("warn", "Copilot models response contained no GPT models");
128
128
  }
@@ -69,7 +69,7 @@ function chatCompatibilityError(kind, itemType) {
69
69
  return error;
70
70
  }
71
71
 
72
- export function responsesToChat(body) {
72
+ export function responsesToChat(body, { reasoningEfforts } = {}) {
73
73
  const messages = [];
74
74
  if (body.instructions) messages.push({ role: "system", content: body.instructions });
75
75
 
@@ -165,11 +165,16 @@ export function responsesToChat(body) {
165
165
  const maxTok = body.max_output_tokens ?? body.max_tokens ?? body.max_completion_tokens;
166
166
  if (maxTok !== undefined) chatReq.max_completion_tokens = maxTok;
167
167
 
168
+ if (body.tools !== undefined && !Array.isArray(body.tools)) throw chatCompatibilityError("tools", typeof body.tools);
168
169
  if (body.tools?.length) {
169
- const unsupportedTool = body.tools.find((tool) => tool?.type !== "function");
170
- if (unsupportedTool) throw chatCompatibilityError("tool", unsupportedTool?.type);
170
+ if (body.tools.some(tool => tool?.type !== "function")) {
171
+ throw chatCompatibilityError("tool", body.tools.find(tool => tool?.type !== "function")?.type);
172
+ }
171
173
  chatReq.tools = body.tools
172
174
  .map((tool) => {
175
+ if (typeof (tool.function?.name ?? tool.name) !== "string" || !(tool.function?.name ?? tool.name).trim()) {
176
+ throw chatCompatibilityError("function tool", "missing_name");
177
+ }
173
178
  if (tool.function?.name) return cloneJson(tool);
174
179
  const fn = {
175
180
  name: tool.name,
@@ -179,21 +184,29 @@ export function responsesToChat(body) {
179
184
  };
180
185
  for (const key of Object.keys(fn)) if (fn[key] === undefined) delete fn[key];
181
186
  return { type: "function", function: fn };
182
- })
183
- .filter(Boolean)
184
- .filter((t) => t.function?.name);
185
- if (!chatReq.tools.length) delete chatReq.tools;
187
+ });
186
188
  }
187
189
  if (body.tool_choice !== undefined) {
188
190
  if (typeof body.tool_choice === "string") {
191
+ if (!["auto", "none", "required"].includes(body.tool_choice)) throw chatCompatibilityError("tool choice", body.tool_choice);
189
192
  chatReq.tool_choice = body.tool_choice;
190
193
  } else if (body.tool_choice?.type === "function" && body.tool_choice.name) {
194
+ if (!chatReq.tools?.some(tool => tool.function.name === body.tool_choice.name)) {
195
+ throw chatCompatibilityError("tool choice", "undeclared_function");
196
+ }
191
197
  chatReq.tool_choice = { type: "function", function: { name: body.tool_choice.name } };
192
198
  } else {
193
199
  throw chatCompatibilityError("tool choice", body.tool_choice?.type);
194
200
  }
195
201
  }
196
202
  if (body.parallel_tool_calls !== undefined) chatReq.parallel_tool_calls = body.parallel_tool_calls;
203
+ if (body.reasoning?.effort !== undefined) {
204
+ if (!["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(body.reasoning.effort)
205
+ || (Array.isArray(reasoningEfforts) && !reasoningEfforts.includes(body.reasoning.effort))) {
206
+ throw chatCompatibilityError("reasoning effort", String(body.reasoning.effort));
207
+ }
208
+ chatReq.reasoning_effort = body.reasoning.effort;
209
+ }
197
210
  const textFormat = body.text?.format;
198
211
  if (textFormat?.type === "json_schema") {
199
212
  chatReq.response_format = {
@@ -207,6 +220,8 @@ export function responsesToChat(body) {
207
220
  };
208
221
  } else if (textFormat?.type === "json_object") {
209
222
  chatReq.response_format = { type: "json_object" };
223
+ } else if (textFormat !== undefined && textFormat?.type !== "text") {
224
+ throw chatCompatibilityError("text format", textFormat?.type);
210
225
  }
211
226
  return chatReq;
212
227
  }
@@ -32,8 +32,8 @@ function jsonPayload(value, assertActive) {
32
32
  });
33
33
  }
34
34
 
35
- function chatRequest(responsesBody, stream) {
36
- const chatReq = responsesToChat(responsesBody);
35
+ function chatRequest(responsesBody, stream, reasoningEfforts) {
36
+ const chatReq = responsesToChat(responsesBody, { reasoningEfforts });
37
37
  chatReq.stream = Boolean(stream);
38
38
  delete chatReq.max_tokens;
39
39
  return stream ? withChatStreamUsage(chatReq) : chatReq;
@@ -81,12 +81,13 @@ function checkedChatPayload(chatReq, payload, limit, stage, adapted, assertActiv
81
81
  export async function prepareResponsesChatPayload(reqContext, {
82
82
  assertActive,
83
83
  payloadOptions = {},
84
+ reasoningEfforts,
84
85
  signal,
85
86
  stream = false,
86
87
  } = {}) {
87
88
  assertActive?.();
88
89
  const limit = configuredBodyLimit(payloadOptions);
89
- let finalChatReq = chatRequest(reqContext.body, stream);
90
+ let finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
90
91
  assertActive?.();
91
92
  let finalChat = jsonPayload(finalChatReq, assertActive);
92
93
  const hasInlineImage = bodyHasInlineImage(reqContext.body, assertActive);
@@ -108,7 +109,7 @@ export async function prepareResponsesChatPayload(reqContext, {
108
109
  responsesPayload = { bodyText: prepared.bodyText, bodyBytes: prepared.bodyBytes };
109
110
  adapted = prepared.adapted;
110
111
  stage = prepared.stage;
111
- finalChatReq = chatRequest(reqContext.body, stream);
112
+ finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
112
113
  assertActive?.();
113
114
  finalChat = jsonPayload(finalChatReq, assertActive);
114
115
  }
@@ -132,7 +133,7 @@ export async function prepareResponsesChatPayload(reqContext, {
132
133
  initialBodyBytes: responsesPayload.bodyBytes,
133
134
  });
134
135
  if (!trimmed.adapted) break;
135
- const candidateChatReq = chatRequest(reqContext.body, stream);
136
+ const candidateChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
136
137
  assertActive?.();
137
138
  const candidateChat = jsonPayload(candidateChatReq, assertActive);
138
139
  if (candidateChat.bodyBytes >= finalChat.bodyBytes) {
@@ -335,6 +335,8 @@ export function createResponsesHandler(options) {
335
335
  let { chatReq, bodyText } = await prepareResponsesChatPayload(prepared, {
336
336
  assertActive: assertPrepareActive,
337
337
  payloadOptions: responsesPayloadOptions,
338
+ reasoningEfforts: (Array.isArray(modelRegistry?.models) ? modelRegistry.models : modelRegistry?.models?.data)
339
+ ?.find(model => model?.id === upstreamModel)?.capabilities?.supports?.reasoning_effort,
338
340
  signal: abort.signal,
339
341
  stream: streaming,
340
342
  });
@@ -3,6 +3,8 @@ import { localPackageVersion } from "./version.mjs";
3
3
 
4
4
  export const ADAPTER_HEALTH_PATH = "/_ccdx/health";
5
5
  export const ADAPTER_STATUS_PATH = "/_ccdx/status";
6
+ export const ADAPTER_PREDICTION_FIX_PATH = "/_ccdx/prediction/fix";
7
+ export const PREDICTION_FIX_CAPABILITY = "prediction-fix-v1";
6
8
  export const ADAPTER_PROTOCOL_VERSION = 4;
7
9
  export const ADAPTER_VERSION = localPackageVersion();
8
10
  export const ADAPTER_CAPABILITIES = Object.freeze(["cache-control-v1"]);
package/src/status.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { currentRequestContext } from "./request-context.mjs";
2
+ import { terminalCell } from "./terminal-text.mjs";
2
3
 
3
4
  const LABELS = {
4
5
  info: "[INFO]",
@@ -13,5 +14,5 @@ export function status(kind, message) {
13
14
  const requestContext = currentRequestContext();
14
15
  const requestId = requestContext?.showRequestId ? requestContext.requestId : "";
15
16
  const context = requestId ? ` request_id=${requestId}` : "";
16
- return `${(LABELS[kind] || LABELS.info).padEnd(8)}${context ? `${context.trimStart()} ` : ""}${message}`;
17
+ return `${(LABELS[kind] || LABELS.info).padEnd(8)}${context ? `${terminalCell(context.trimStart())} ` : ""}${terminalCell(message, { fallback: "" })}`;
17
18
  }
@@ -139,6 +139,7 @@ function createRoutePerformance() {
139
139
  success_with_output: 0,
140
140
  errors_with_output: 0,
141
141
  zero_output_errors: 0,
142
+ empty_stream_completions: 0,
142
143
  neutral: 0,
143
144
  terminalTotals: emptyOutcomes(),
144
145
  incompleteReasons: Object.create(null),
@@ -152,6 +153,7 @@ function routeSnapshot(route) {
152
153
  success_with_output: route.success_with_output,
153
154
  errors_with_output: route.errors_with_output,
154
155
  zero_output_errors: route.zero_output_errors,
156
+ empty_stream_completions: route.empty_stream_completions,
155
157
  neutral: route.neutral,
156
158
  terminal_outcomes: {
157
159
  totals: { ...route.terminalTotals },
@@ -274,6 +276,9 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
274
276
  finished = true;
275
277
  failed ||= finishFailed;
276
278
  const outcome = terminalOutcome || (aborted ? "cancelled" : "unknown");
279
+ const emptyStreamCompletion = outcome === "completed" && upstreamStartedAt !== null
280
+ && firstOutputAt === null && outputTokens === 0;
281
+ if (emptyStreamCompletion) route.empty_stream_completions += 1;
277
282
  const origin = terminalOrigin || errorOrigin || (aborted ? "client_disconnect" : "unclassified");
278
283
  route.terminalTotals[outcome] += 1;
279
284
  if (incompleteReason) route.incompleteReasons[incompleteReason] = (route.incompleteReasons[incompleteReason] || 0) + 1;
@@ -288,6 +293,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
288
293
  recentRequests.push({
289
294
  request_id: typeof requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(requestId) ? requestId : null,
290
295
  at, route: routeName, model, outcome, origin, phase,
296
+ empty_stream_completion: emptyStreamCompletion,
291
297
  failed: failed || aborted || (terminalOutcome !== null && terminalOutcome !== "completed"),
292
298
  http_status: Number.isInteger(statusCode) && statusCode >= 100 && statusCode <= 599 ? statusCode : null,
293
299
  upstream_attempts: attempts,