codex-copilot-dx 0.9.40 → 0.9.41

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
@@ -21,7 +21,7 @@ is needed. On Windows, open the App manually unless native prediction setup is
21
21
  enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. No install script, alias or policy change is added; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
22
22
 
23
23
  Open [the local dashboard](http://127.0.0.1:2026/) for status, model discovery,
24
- usage, cache/limits, recent failures, request context and animation settings.
24
+ usage, cache/limits, recent failures, request context and animation settings. First output uses **ms**; estimated output speed uses **token/s**. Inference HTTP failures are retained separately from route and MCP-method errors.
25
25
  Auto refresh runs every 30 minutes while visible and can be switched off. Hidden pages pause; opening sections and manual refresh still work. The atom rotates once on page load and manual refresh, respecting reduced motion. Startup uses a compact six-line atom and aligned checks; `Ready` refers to the core service. Narrow/non-color terminals use a plain title.
26
26
 
27
27
  ## Commands
@@ -88,7 +88,7 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
88
88
  Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`.
89
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. For npm `EALLOWREMOTE`, only if policy permits and the update is trusted, use `ccdx update github --allow-remote`: explicit URL-download permission for that installation's whole dependency tree, not a hostname allowlist. Persistent npm settings stay unchanged.
90
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.
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
+ Recent errors separate HTTP and model failures. By default HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged. Explicit, bounded error-excerpt collection is described in the [reference](docs/REFERENCE.md#http-error-diagnostics).
92
92
 
93
93
  The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown. See [architecture boundaries](docs/ARCHITECTURE.md) for separate inference, integration, image and management ownership.
94
94
 
@@ -17,6 +17,15 @@ 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
+ `management-routes.mjs` owns status, health, cache control and prediction repair
21
+ HTTP checks. It receives a snapshot callback and the existing explicit repair
22
+ action, not a model client or a second recovery lifecycle.
23
+ `optional-routes.mjs` owns lazy WebUI/API and image-MCP dispatch and image stats.
24
+ The adapter remains the HTTP composition root; neither extracted route module
25
+ imports it. Native prediction belongs to client integration, WebUI to management,
26
+ and terminal animation to presentation. Input-image optimization remains core
27
+ multimodal inference, distinct from optional image generation. This is a module
28
+ boundary, not a plugin framework, daemon, IPC protocol or package split.
20
29
  The HTTP dispatch boundary rejects browser Origin-bearing inference requests
21
30
  before body admission, credential use or provider dispatch; native LAN opt-in is unchanged.
22
31
 
@@ -226,11 +235,19 @@ Prediction preference, bridge readiness and observed configuration responses are
226
235
  different states. None proves that a candidate appeared in the App. The dashboard
227
236
  keeps that result unknown. Integration diagnostics retain bounded, redacted
228
237
  metadata, not conversation or image contents.
229
- HTTP failures have a separate 20-entry metadata ring (`http_errors`): status,
230
- safe technical code, model when observed, route, source and request IDs. Original
231
- HTTP error bodies are returned unchanged but not saved in that ring. Model
232
- terminal diagnostics and their counters retain their existing meaning. The
233
- dashboard merges recent HTTP, model and request-timeline failures for display.
238
+ HTTP failures retain the original 20-entry metadata ring (`http_errors.recent`)
239
+ plus independent 20-entry inference/other and eight-entry image-MCP method rings.
240
+ Fixed categories distinguish inference, image-MCP HTTP 405, unmatched routes and
241
+ other failures without treating every 404/405 as harmless. Status, safe technical
242
+ code/type/parameter, method, allowlisted target, request IDs and numeric/enum
243
+ request options survive; body/query/prompt/tool/schema values do not. Optional
244
+ error prose requires `CCDX_HTTP_ERROR_DETAILS=1` at service creation, is redacted
245
+ and capped at 500 characters, and still needs review before sharing.
246
+ Original error responses are preserved. Per-request attempt timings retain only
247
+ the first and last two provider calls, not unbounded stream events. All data is
248
+ process-local and cleared on restart. The dashboard uses the independently
249
+ retained actionable HTTP errors rather than letting route noise erase them.
250
+ Model terminal diagnostics and HTTP counters retain their original meanings.
234
251
 
235
252
  Tests cover module dependency direction, default-off behavior, concurrent writers,
236
253
  proxy handshakes, TLS validation, streaming, history isolation and release lookup.
package/docs/REFERENCE.md CHANGED
@@ -793,8 +793,16 @@ output is observed at the gateway from generated deltas, hidden-reasoning/tool
793
793
  announcements or content snapshots; a runtime-only result is marked separately.
794
794
  Empty message/envelope frames, client tool results and compaction are excluded.
795
795
  `first_output_sources` and each recent request's `first_output_source` describe
796
- that evidence, not internal model decode or prefill timing. Per-token time is a
797
- gateway estimate and can include hosted-tool and downstream delays. The new
796
+ that evidence, not internal model decode or prefill timing. First output is
797
+ displayed in ms, and output speed in token/s. The additive
798
+ `output_tokens_per_second` metric divides the sum of reported output-token
799
+ intervals (`output_tokens - 1`) by their summed first-output-to-finish durations.
800
+ It is a time-weighted per-request estimate, not the inverse of average TPOT, an
801
+ unweighted average of request speeds, or concurrent system throughput. At least
802
+ two integral output tokens and a positive duration are required; missing usage
803
+ is unknown, not zero speed. The existing TPOT histogram remains unchanged for
804
+ API consumers, including its partial-failure samples. Both estimates can
805
+ include hosted-tool and downstream delays. The new
798
806
  timing classifier does not change stream forwarding or the existing output
799
807
  commitment that gates compatibility retries.
800
808
 
@@ -892,7 +900,7 @@ For the complete machine-readable status payload:
892
900
  curl -s http://127.0.0.1:2026/_ccdx/status | jq
893
901
  ```
894
902
 
895
- 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.
903
+ 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. Whole request/response bodies, credential fields, and account profiles are not archived in status. Explicit HTTP diagnostic mode can retain a bounded error excerpt; see HTTP error diagnostics below. Arbitrary upstream prose cannot be guaranteed free of sensitive content; review diagnostics before sharing them.
896
904
 
897
905
  `stream_performance.by_route.*.empty_stream_completions` counts completed streams
898
906
  with no observed output and an explicit zero output-token count. The recent request's
@@ -960,14 +968,42 @@ selection. Isolated/custom credential clients retain their own recovery contract
960
968
 
961
969
  After an account is selected, automatic `401`/`403` recovery and in-process token rotation accept only that same GitHub account. Concurrent callers share token refresh work without sharing cancellation, and a still-valid Copilot token may be used briefly after a transient refresh failure. Explicit token variables remain the intentional way to select another account.
962
970
 
963
- If refresh still fails with `401` or `403`, the saved GitHub OAuth credential may be expired, revoked, or missing Copilot access. After stopping the adapter, remove that exact saved token and start again to rerun authentication recovery:
964
-
965
- ```bash
966
- rm ~/.local/share/copilot-api/github_token
967
- ccdx
968
- ```
969
-
970
- Recovery first tries compatible local credentials and starts Device Flow only when none can be imported. Set `CCDX_DISABLE_TOKEN_DISCOVERY=1` for that launch if a fresh Device Flow is intended after removing the saved token.
971
+ If refresh still fails with Copilot `401` or `403`, preserve the saved credential.
972
+ Run `ccdx auth status --online` only when you explicitly want an online diagnosis;
973
+ check account entitlement and company routing policy separately. Reauthorization
974
+ is appropriate only after independent GitHub identity rejection or an explicit
975
+ account-change decision, not merely a Copilot denial, package update, or failed
976
+ network probe. Existing same-account recovery and explicit source selection are
977
+ unchanged.
978
+
979
+ ## HTTP error diagnostics
980
+
981
+ `http_errors.recent` keeps its 20-record rolling view. Independent
982
+ `actionable_recent` (20 inference/other failures) and `protocol_recent` (eight
983
+ image-MCP HTTP 405 records) prevent route/method noise from erasing inference
984
+ evidence. `by_category` counts inference, protocol, route and other HTTP failures;
985
+ classification does not discard errors, grant access or retry requests.
986
+ The WebUI prioritizes actionable records; raw HTTP counters remain visible.
987
+
988
+ New records retain safe error code/type/parameter paths, method, an allowlisted
989
+ endpoint without a query, and upstream attempt count. Requested/served model
990
+ IDs are distinct; only the explicit Auto-review alias identifies that request
991
+ purpose. Other purposes remain unknown, not guessed from a model name.
992
+ Known enum/numeric options
993
+ include reasoning effort, service tier, output format, max output tokens and
994
+ input/tool counts; no prompt, schema or tool values are kept. `error_body` says
995
+ whether the upstream provided empty, structured or unstructured error details.
996
+ Recent request `attempts` and HTTP `attempt_timings` retain the first and last two
997
+ provider dispatch/header offsets and statuses; these are not TCP-retry counts.
998
+
999
+ By default arbitrary upstream error prose is not copied into HTTP diagnostics.
1000
+ For a specific investigation, start a **new** service with
1001
+ `CCDX_HTTP_ERROR_DETAILS=1` to retain a redacted error-message excerpt, capped at
1002
+ 500 characters, in those bounded in-memory records. In Windows PowerShell set
1003
+ `$env:CCDX_HTTP_ERROR_DETAILS='1'` before `ccdx.cmd`. This does not reconfigure an
1004
+ already-running service, enable file logging, retain whole requests, or guarantee
1005
+ that arbitrary upstream prose contains no private context. Review before sharing;
1006
+ unset the variable after the investigation. Records disappear on service exit.
971
1007
 
972
1008
  ## Security
973
1009
 
@@ -976,7 +1012,7 @@ Recovery first tries compatible local credentials and starts Device Flow only wh
976
1012
  - 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.
977
1013
  - 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.
978
1014
  - 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.
979
- - 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.
1015
+ - Runtime status and usage records retain metadata by default; explicitly enabled HTTP error excerpts can contain private context. Diagnostic logging records status and error messages; it is not a general redaction layer for arbitrary error text. See Debug logging before sharing logs.
980
1016
  - Request/response bodies, request-admission queues, retained history, image work, SSE buffers, log queues, retries, and shutdown have explicit limits. These component limits are not a single process-wide memory ceiling; completed image files are persistent user artifacts, not an automatically evicted cache.
981
1017
 
982
1018
  ## Configuration
@@ -1004,6 +1040,7 @@ Recovery first tries compatible local credentials and starts Device Flow only wh
1004
1040
  | `CCDX_AUTO_REVIEW_MODEL` | saved selection or `gpt-6.1-sol` | Copilot Responses model used for Codex Auto-review; overrides the interactive selection |
1005
1041
  | `CCDX_LOG_PATH` | unset | Mirror terminal logs to a file; set to `1` for `~/.local/share/codex-copilot-dx/debug.log` |
1006
1042
  | `CCDX_LOG_LEVEL` | `info` | Set to `debug` for upstream attempts, status codes, retry causes, and timings |
1043
+ | `CCDX_HTTP_ERROR_DETAILS` | unset | Set to `1` on a new service to retain redacted HTTP error excerpts (500 characters) in bounded memory; review before sharing, no file logging is enabled |
1007
1044
  | `CCDX_LOG_MAX_BYTES` | `16777216` | Rotate the debug log at this size and retain one `.1` backup; set to `0` to disable rotation |
1008
1045
  | `CCDX_TERMINAL_ANIMATION` | auto | Show the selected transient animation while an interactive terminal has active requests and no output for 800 ms; set to `0`, `false`, `no`, or `off` to disable |
1009
1046
  | `CCDX_IMG_MAX_DIM` | `2048` | Maximum long edge in pixels for image downscaling |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "0.9.40",
3
+ "version": "0.9.41",
4
4
  "description": "Use Codex App with GitHub Copilot",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -12,26 +12,21 @@ 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, ADAPTER_PREDICTION_FIX_PATH, PREDICTION_FIX_CAPABILITY, adapterHealthPayload } from "./running-adapter.mjs";
15
+ import { ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH } from "./running-adapter.mjs";
16
+ import { createManagementHandler, isManagementRoute } from "./management-routes.mjs";
17
+ import { createOptionalRoutes, isOptionalRoute, DASHBOARD_PATHS, DASHBOARD_API_PATHS } from "./optional-routes.mjs";
16
18
  import { createResponsesCompactHandler, createResponsesHandler } from "./responses-handler.mjs";
17
19
  import { createResponsesImagePressureController } from "./responses-image-pressure.mjs";
18
- import { createResponseFailureDiagnostics, buildHttpFailureDetails } from "./response-failures.mjs";
19
- import {
20
- ADAPTER_CACHE_PATH,
21
- cacheRuntimeSnapshot,
22
- cleanRuntimeCaches,
23
- setHistoryCacheLimit,
24
- } from "./cache-control.mjs";
20
+ import { createResponseFailureDiagnostics, createHttpFailureDiagnostics, buildHttpFailureDetails } from "./response-failures.mjs";
21
+ import { ADAPTER_CACHE_PATH } from "./cache-control.mjs";
25
22
  import { loadRuntimeConfig, parsePositiveInteger } from "./runtime-config.mjs";
26
23
  import {
27
24
  createRequestAbort,
28
25
  logRequestFailure,
29
- readJsonBody,
30
26
  sendJsonError,
31
27
  } from "./http-transport.mjs";
32
28
  import { httpError } from "./http-errors.mjs";
33
29
  import { createRequestAdmission } from "./request-admission.mjs";
34
- import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
35
30
 
36
31
  export {
37
32
  abortErrorStatusCode,
@@ -63,8 +58,6 @@ export {
63
58
  } from "./responses-request.mjs";
64
59
 
65
60
  const ADAPTER_RUNTIME_CONFIG = loadRuntimeConfig();
66
- const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js"]);
67
- const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth"]);
68
61
 
69
62
  export function requestPath(reqUrl) {
70
63
  return new URL(reqUrl || "/", "http://localhost").pathname;
@@ -170,8 +163,17 @@ export function createAdapterHandler(options = {}) {
170
163
  const streamPerformanceMetrics = options.streamPerformanceMetrics || createStreamPerformanceMetrics();
171
164
  const imagePressure = options.imagePressure || createResponsesImagePressureController();
172
165
  const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
173
- const httpErrors = createResponseFailureDiagnostics({ maxEntries: 20 });
174
- let imageMcpHandler = options.imageMcpHandler || null;
166
+ const httpErrors = createHttpFailureDiagnostics();
167
+ const optionalRoutes = createOptionalRoutes(options);
168
+ const managementHandler = createManagementHandler({
169
+ nativePredictionPac: options.nativePredictionPac, fixPrediction: options.fixPrediction, requestBodyTimeoutMs,
170
+ statusSnapshot: () => ({ ...runtimeStatusPayload({
171
+ metrics: requestMetrics, streamPerformance: streamPerformanceMetrics, admission: acquireRequest,
172
+ imagePressure, responseFailures, imageGeneration: optionalRoutes.imageStats(),
173
+ modelRegistry: codexModelRegistry, codexClient, codexModelRegistry, codexModelCatalog,
174
+ clientIntegrations: options.clientIntegrationSnapshot?.(),
175
+ }), http_errors: httpErrors.snapshot() }),
176
+ });
175
177
  const responsesHandler = createResponsesHandler({
176
178
  acquireRequest,
177
179
  autoReviewModelResolver: options.autoReviewModelResolver,
@@ -211,132 +213,8 @@ export function createAdapterHandler(options = {}) {
211
213
  sendJsonError(res, error, 403);
212
214
  return;
213
215
  }
214
- if (DASHBOARD_API_PATHS.has(pathname)) {
215
- const { handleDashboardApi } = await import("./dashboard-api.mjs");
216
- return handleDashboardApi(req, res, pathname, options.dashboardOptions);
217
- }
218
- if ((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname)) {
219
- const { serveDashboard } = await import("./dashboard.mjs");
220
- return serveDashboard(req, res, pathname);
221
- }
222
- if (pathname === "/mcp/image") {
223
- if (imageMcpHandler) return imageMcpHandler(req, res);
224
- return import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
225
- imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
226
- return imageMcpHandler(req, res);
227
- });
228
- }
229
- if (req.method === "GET" && pathname === ADAPTER_STATUS_PATH) {
230
- if (!isLoopbackAddress(req.socket?.remoteAddress) || !isLoopbackHostHeader(req.headers?.host)) {
231
- res.writeHead(403, { "Content-Type": "application/json" });
232
- res.end(JSON.stringify({ error: "Runtime status is available only from loopback" }));
233
- return;
234
- }
235
- res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
236
- res.end(JSON.stringify({ ...runtimeStatusPayload({
237
- metrics: requestMetrics,
238
- streamPerformance: streamPerformanceMetrics,
239
- admission: acquireRequest,
240
- imagePressure,
241
- responseFailures,
242
- imageGeneration: imageMcpHandler?.stats?.(),
243
- modelRegistry: codexModelRegistry,
244
- codexClient,
245
- codexModelRegistry,
246
- codexModelCatalog,
247
- clientIntegrations: options.clientIntegrationSnapshot?.(),
248
- }), http_errors: httpErrors.snapshot() }));
249
- return;
250
- }
251
-
252
- if (req.method === "GET" && pathname === ADAPTER_HEALTH_PATH) {
253
- res.writeHead(200, { "Content-Type": "application/json" });
254
- const predictionPac = isLoopbackAddress(req.socket?.remoteAddress) && isLoopbackHostHeader(req.headers?.host)
255
- ? options.nativePredictionPac?.() : null;
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(); }
288
- return;
289
- }
290
-
291
- if (pathname === ADAPTER_CACHE_PATH) {
292
- if (!isLoopbackAddress(req.socket?.remoteAddress) || !isLoopbackHostHeader(req.headers?.host)) {
293
- res.writeHead(403, { "Content-Type": "application/json" });
294
- res.end(JSON.stringify({ error: "Cache control is available only from loopback" }));
295
- return;
296
- }
297
- if (req.method === "GET") {
298
- res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
299
- res.end(JSON.stringify(cacheRuntimeSnapshot()));
300
- return;
301
- }
302
- if (req.method !== "POST") {
303
- res.writeHead(405, { "Content-Type": "application/json", Allow: "GET, POST" });
304
- res.end(JSON.stringify({ error: "Only GET and POST are supported" }));
305
- return;
306
- }
307
- if (Object.hasOwn(req.headers || {}, "origin")) {
308
- res.writeHead(403, { "Content-Type": "application/json" });
309
- res.end(JSON.stringify({ error: "Browser origins are not allowed for cache control" }));
310
- return;
311
- }
312
- const mediaType = String(req.headers?.["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
313
- if (mediaType !== "application/json") {
314
- res.writeHead(415, { "Content-Type": "application/json" });
315
- res.end(JSON.stringify({ error: "Cache control requires application/json" }));
316
- return;
317
- }
318
- const abort = createRequestAbort(req, res);
319
- abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
320
- try {
321
- const body = await readJsonBody(req, {
322
- maxBodyBytes: 8 * 1024,
323
- maxDecodedBodyBytes: 8 * 1024,
324
- signal: abort.signal,
325
- });
326
- let result;
327
- if (body?.action === "set_limit") result = setHistoryCacheLimit(body.max_bytes);
328
- else if (body?.action === "clean") result = cleanRuntimeCaches({ history: body.history === true });
329
- else throw httpError("Unknown cache action", 400);
330
- res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
331
- res.end(JSON.stringify(result));
332
- } catch (error) {
333
- if (["ccdx_cache_busy", "ccdx_cache_limit_below_usage"].includes(error?.code)) error.statusCode = 409;
334
- sendJsonError(res, error, 400);
335
- } finally {
336
- abort.cleanup();
337
- }
338
- return;
339
- }
216
+ if (isOptionalRoute(req.method, pathname)) return optionalRoutes.handle(req, res, pathname);
217
+ if (isManagementRoute(req.method, pathname)) return managementHandler(req, res, pathname);
340
218
 
341
219
  if (req.method === "POST" && pathname === "/v1/responses") {
342
220
  return responsesHandler(req, res);
@@ -447,7 +325,13 @@ export function createAdapterHandler(options = {}) {
447
325
  if (requestFinished) return;
448
326
  requestFinished = true;
449
327
  if (trackRequest && statusCode >= 400) {
450
- try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model })); } catch {}
328
+ try { httpErrors.record(buildHttpFailureDetails({ ...httpEvidence, statusCode, route: routeName, requestId, model: context?.model,
329
+ method: ["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"].includes(req.method) ? req.method : "OTHER",
330
+ target: ["/v1/responses", "/v1/responses/compact", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
331
+ request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.(),
332
+ attempt_timings: streamPerformance?.attemptTimings?.(),
333
+ requested_model: context?.requestedModel,
334
+ })); } catch {}
451
335
  }
452
336
  try { complete({ statusCode, aborted }); } catch {}
453
337
  try { streamPerformance?.finish({ failed: aborted || statusCode >= 400, aborted, statusCode }); } catch {}
@@ -484,6 +368,7 @@ export function createAdapterHandler(options = {}) {
484
368
  requestId,
485
369
  pathname,
486
370
  showRequestId: options.showRequestId === true,
371
+ includeHttpErrorDetails: options.includeHttpErrorDetails === true || process.env.CCDX_HTTP_ERROR_DETAILS === "1",
487
372
  streamPerformance,
488
373
  onHttpError: evidence => { httpEvidence = evidence; },
489
374
  };
@@ -39,11 +39,14 @@ function mebibytes(value) {
39
39
  return bytes === null ? "n/a" : `${(bytes / (1024 * 1024)).toFixed(1)}MiB`;
40
40
  }
41
41
 
42
- function tpot(metric) {
43
- const average = finiteNumber(metric?.avg);
44
- if (average === null) return "n/a";
45
- const milliseconds = metric?.unit === "us" ? average / 1000 : average;
46
- return `${milliseconds.toFixed(2)}ms/token`;
42
+ function outputRate(metric) {
43
+ const average = metric?.avg === null ? null : finiteNumber(metric?.avg);
44
+ return metric?.samples > 0 && average !== null ? `${average.toFixed(1)}token/s` : "n/a";
45
+ }
46
+
47
+ function firstOutputLatency(metric) {
48
+ const average = metric?.avg === null ? null : finiteNumber(metric?.avg);
49
+ return metric?.samples > 0 && average !== null ? `${average.toFixed(1)}ms` : "n/a";
47
50
  }
48
51
 
49
52
  function cacheHitRate(cache = {}) {
@@ -151,7 +154,7 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
151
154
  `${commandName} status`,
152
155
  adapterLine,
153
156
  status("info", `Requests: ${count(requests.completed)}/${count(requests.total)} completed, ${count(requests.active)} active, ${count(requests.status_4xx)} 4xx, ${count(requests.status_5xx)} 5xx, ${count(requests.aborted)} aborted`),
154
- status("info", `Responses stream: TTFT avg ${latency(performance.ttft_ms?.avg)} (${count(performance.ttft_ms?.samples)} samples), TPOT avg ${tpot(performance.tpot_us)} (${count(performance.tpot_us?.samples)} samples; gateway estimate)`),
157
+ status("info", `Responses stream: TTFT avg ${firstOutputLatency(performance.ttft_ms)} (${count(performance.ttft_ms?.samples)} samples), output avg ${outputRate(performance.output_tokens_per_second)} (${count(performance.output_tokens_per_second?.samples)} samples; gateway estimate)`),
155
158
  ...(terminalOutcomes ? [status("info", `Model outcomes: ${count(terminalOutcomes.completed)} completed, ${count(terminalOutcomes.incomplete)} incomplete, ${count(terminalOutcomes.failed)} failed, ${count(terminalOutcomes.cancelled)} cancelled, ${count(terminalOutcomes.unknown)} without terminal`)] : []),
156
159
  status("info", `Admission: ${count(admission.activeRequests)} active, ${count(admission.queued)} queued, ${count(admission.rejected)} rejected, ${count(admission.timedOut)} timed out, wait avg ${latency(admission.waitMsAvg)}`),
157
160
  status("info", `Memory: RSS ${mebibytes(processStats.rss_bytes)}, heap ${mebibytes(processStats.heap_used_bytes)}`),
@@ -188,7 +191,14 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
188
191
  lines.push(status("warn", ` ${model} ${code}: ${message}${failure.retried ? ` [retried:${retryPolicy}]` : ""}`));
189
192
  }
190
193
  }
191
- if (data.http_errors) lines.push(status("info", `HTTP failures: ${count(data.http_errors.total)} observed (separate from model terminal events)`));
194
+ if (data.http_errors) {
195
+ lines.push(status("info", `HTTP failures: ${count(data.http_errors.total)} observed (separate from model terminal events)`));
196
+ const categories = data.http_errors.by_category;
197
+ if (categories) lines.push(status("info", `HTTP categories: ${count(categories.inference)} inference, ${count(categories.protocol)} unsupported MCP methods, ${count(categories.route)} unmatched routes, ${count(categories.other)} other`));
198
+ for (const failure of (data.http_errors.actionable_recent || []).slice(-3).reverse()) {
199
+ lines.push(status("warn", `HTTP ${count(failure.http_status)} ${terminalCell(failure.model)} ${terminalCell(failure.code)}${failure.parameter ? ` param=${terminalCell(failure.parameter)}` : ""}; ${terminalCell(failure.origin)}; ${count(failure.upstream_attempts)} attempts`));
200
+ }
201
+ }
192
202
  lines.push(status("info", `Models: ${count(models.models)} total; Copilot token ${copilot.token_cached ? `cached (${duration(copilot.token_expires_in_ms)} remaining)` : "not cached"}`));
193
203
  const prediction = data.client_integrations?.prediction;
194
204
  if (prediction) {
@@ -6,6 +6,8 @@ import { enforceResponsesPayloadByteBudget } from "./responses-byte-budget.mjs";
6
6
  import { status } from "./status.mjs";
7
7
  import { withChatStreamUsage } from "./stream-contract.mjs";
8
8
  import { markRequestObservation, markUpstreamStarted } from "./stream-performance.mjs";
9
+ import { currentRequestContext } from "./request-context.mjs";
10
+ import { requestOptionsEvidence } from "./response-failures.mjs";
9
11
 
10
12
  function abortError(signal) {
11
13
  if (signal?.reason instanceof Error) return signal.reason;
@@ -185,6 +187,8 @@ export function createCopilotClientRuntime({
185
187
  headers["Content-Length"] = String(bodyBytes);
186
188
  headers.Accept = reqBody.stream ? "text/event-stream" : "application/json";
187
189
  try {
190
+ const context = currentRequestContext();
191
+ if (context) context.requestOptions = requestOptionsEvidence(reqBody);
188
192
  onUpstreamStart?.();
189
193
  markUpstreamStarted(reqBody.stream === true);
190
194
  return await fetchCopilotUpstream(`${tokenSession.getApiBase()}${responsesEndpointPath()}`, {
@@ -110,7 +110,7 @@ export async function openCopilotResponse(reqContext, upstream = copilotResponse
110
110
  payloadPrepared,
111
111
  });
112
112
  } finally { releaseRecovery?.();releaseRecovery = null; }
113
- markUpstreamHeaders();
113
+ markUpstreamHeaders(resp.status);
114
114
  options.assertPrepareActive?.();
115
115
  payloadPrepared = true;
116
116
  if (resp.ok) {
@@ -4,6 +4,15 @@ function cloneJson(value) {
4
4
  return value === undefined ? undefined : structuredClone(value);
5
5
  }
6
6
 
7
+ export function stripUnsupportedGpt6ServiceTier(body, requestedModel, upstreamModel, priorityTierModel) {
8
+ if (requestedModel.startsWith("gpt-6-")
9
+ && upstreamModel === requestedModel
10
+ && !priorityTierModel
11
+ && body.service_tier === "priority") {
12
+ delete body.service_tier;
13
+ }
14
+ }
15
+
7
16
  export function isConnectionOwnedInputError(statusCode, text) {
8
17
  if (statusCode !== 400 || !text) return false;
9
18
  try {
@@ -31,7 +31,7 @@
31
31
  <article class="card"><h2 data-i18n>ADAPTER</h2><strong id="version">—</strong><p id="uptime">—</p></article>
32
32
  <article class="card"><h2>Copilot</h2><strong id="copilot">—</strong><p id="token">—</p></article>
33
33
  <article class="card"><h2 data-i18n>KNOWN MODELS</h2><strong id="models">—</strong><p id="model-source">—</p></article>
34
- <article class="card"><h2 data-i18n>REQUESTS</h2><strong id="requests">—</strong><p id="request-errors">—</p><p><span data-i18n>Per-request limits (active)</span><br><span id="body-limits">—</span></p></article>
34
+ <article class="card"><h2 data-i18n>REQUESTS</h2><strong id="requests">—</strong><p id="request-errors">—</p><p id="http-error-breakdown">—</p><p><span data-i18n>Per-request limits (active)</span><br><span id="body-limits">—</span></p></article>
35
35
  </section>
36
36
 
37
37
  <section class="details" aria-label="Runtime details" data-i18n-label>
@@ -39,8 +39,8 @@
39
39
  <div class="panel-heading"><h2 data-i18n>MODEL OUTCOMES</h2><span>RESPONSES</span></div>
40
40
  <dl class="stats"><div><dt data-i18n>Completed</dt><dd id="completed">—</dd></div><div><dt data-i18n>Incomplete</dt><dd id="incomplete">—</dd></div><div><dt data-i18n>Failed</dt><dd id="failed">—</dd></div><div><dt data-i18n>Cancelled</dt><dd id="cancelled">—</dd></div></dl>
41
41
  <p class="hint" data-i18n>HTTP 2xx != model completed.</p>
42
- <dl class="stats timing-stats"><div><dt data-i18n>First output</dt><dd id="ttft">—</dd></div><div><dt data-i18n>Token time</dt><dd id="tpot">—</dd></div></dl>
43
- <p class="hint" data-i18n>Gateway timing. Token time is estimated.</p>
42
+ <dl class="stats timing-stats"><div><dt data-i18n>First output</dt><dd id="ttft">—</dd></div><div><dt data-i18n>Output speed</dt><dd id="tpot">—</dd></div></dl>
43
+ <p class="hint" data-i18n>Gateway timing. Output speed is estimated.</p>
44
44
  </article>
45
45
  <article class="panel">
46
46
  <div class="panel-heading"><h2 data-i18n>LOCAL HISTORY</h2><span data-i18n>ACTIVE LIMIT</span></div>
@@ -15,8 +15,20 @@
15
15
  "Unavailable": ["Unavailable", "不可用"],
16
16
  "Observed": ["Observed", "已收到配置请求"],
17
17
  "First output": ["First output", "首次输出"],
18
- "Token time": ["Token time", "输出耗时"],
19
- "Gateway timing. Token time is estimated.": ["Observed at the gateway. Token time is an estimate.", "网关观测时间。\n每Token耗时为估算值。"],
18
+ "Output speed": ["Output speed", "输出速度"],
19
+ "Inference {inference} / method {protocol} / route {route} / other {other}": ["Inference {inference} / method {protocol} / route {route} / other {other}", "推理{inference}·方法{protocol}·路由{route}·其他{other}"],
20
+ "Upstream returned no error details.": ["The upstream returned no error details.", "上游未返回错误详情。"],
21
+ "error_type": ["Error type", "错误类型"],
22
+ "parameter": ["Parameter", "请求参数"],
23
+ "error_body": ["Error details", "错误详情"],
24
+ "diagnostic_message": ["Opt-in error detail", "诊断详情"],
25
+ "method": ["Method", "请求方法"],
26
+ "target": ["Endpoint", "请求入口"],
27
+ "request_options": ["Request options", "请求选项"],
28
+ "requested_model": ["Requested model", "指定模型"],
29
+ "request_kind": ["Request purpose", "请求用途"],
30
+ "attempt_timings": ["Upstream attempts", "上游尝试"],
31
+ "Gateway timing. Output speed is estimated.": ["Gateway estimates, not internal model timing or total throughput.", "网关估算值。\n非模型内部耗时或总吞吐量。"],
20
32
  "{value} / {samples} samples": ["{value} / {samples} samples", "{value} / {samples}次样本"],
21
33
  "CCDX · Local dashboard": ["CCDX · Dashboard", "CCDX · 运行看板"],
22
34
  "/ LOCAL STATUS": ["/ DASHBOARD", "/ 运行看板"],
@@ -74,7 +74,12 @@
74
74
  recovery: failure.recovery ? JSON.stringify(failure.recovery) : undefined,
75
75
  request_id: failure.request_id, outcome: timeline?.outcome, origin: failure.origin || timeline?.origin,
76
76
  phase: timeline?.phase, http_status: failure.http_status ?? timeline?.http_status, route: failure.route,
77
- upstream_attempts: timeline?.upstream_attempts,
77
+ upstream_attempts: failure.upstream_attempts ?? timeline?.upstream_attempts,
78
+ error_type: failure.error_type, parameter: failure.parameter, error_body: failure.error_body,
79
+ diagnostic_message: failure.diagnostic_message, method: failure.method, target: failure.target,
80
+ request_options: failure.request_options ? JSON.stringify(failure.request_options) : undefined,
81
+ requested_model: failure.requested_model, request_kind: failure.request_kind,
82
+ attempt_timings: failure.attempt_timings || timeline?.attempts ? JSON.stringify(failure.attempt_timings || timeline.attempts) : undefined,
78
83
  timings_ms: timingText };
79
84
  const diagnostic = document.createElement("dl");
80
85
  diagnostic.className = "failure-detail";
@@ -120,12 +125,15 @@
120
125
  const requests = data.requests || {};
121
126
  text("requests", number(requests.total));
122
127
  text("request-errors", "4xx {client} / 5xx {server} / active {active}", { client: number(requests.status_4xx), server: number(requests.status_5xx), active: number(requests.active) });
128
+ const categories = data.http_errors?.by_category;
129
+ text("http-error-breakdown", categories ? "Inference {inference} / method {protocol} / route {route} / other {other}" : "—",
130
+ categories ? Object.fromEntries(Object.entries(categories).map(([key, value]) => [key, number(value)])) : {});
123
131
  text("body-limits", "raw {raw} / decoded {decoded}", { raw: mib(data.limits?.max_body_bytes), decoded: mib(data.limits?.max_decoded_body_bytes) });
124
132
 
125
133
  const outcomes = data.stream_performance?.by_route?.responses?.terminal_outcomes?.totals || {};
126
134
  for (const key of ["completed", "incomplete", "failed", "cancelled"]) text(key, number(outcomes[key]));
127
135
  const timing = data.stream_performance?.by_route?.responses || {};
128
- for (const [id, metric, scale, unit] of [["ttft", timing.ttft_ms, 1, "ms"], ["tpot", timing.tpot_us, timing.tpot_us?.unit === "us" ? 1000 : 1, "ms/token"]]) {
136
+ for (const [id, metric, scale, unit] of [["ttft", timing.ttft_ms, 1, "ms"], ["tpot", timing.output_tokens_per_second, 1, "token/s"]]) {
129
137
  const value = metric?.samples > 0 && finite(metric.avg) ? `${(Number(metric.avg) / scale).toFixed(1)} ${unit}` : "—";
130
138
  text(id, "{value} / {samples} samples", { value, samples: number(metric?.samples) });
131
139
  }
@@ -143,7 +151,7 @@
143
151
  ? "active {active} / failed {failed} / delivery failures {delivery}"
144
152
  : "Setup state unknown / ccdx image-status", { active: number(image?.active), failed: number(image?.failed), delivery: number(image?.delivery_failures) });
145
153
 
146
- renderFailures([...(data.response_failures?.recent || []), ...(data.http_errors?.recent || [])]
154
+ renderFailures([...(data.response_failures?.recent || []), ...(data.http_errors?.actionable_recent || data.http_errors?.recent || [])]
147
155
  .sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0)), data.stream_performance?.recent_requests);
148
156
  renderContext(data.stream_performance);
149
157
  if (element("prediction-preference")) {
@@ -8,6 +8,7 @@ import { redactDiagnosticText } from "./diagnostic-text.mjs";
8
8
  import { httpError } from "./http-errors.mjs";
9
9
  import { admissionAbortError, contentEncodings, requestContentLength } from "./request-admission.mjs";
10
10
  import { currentRequestContext } from "./request-context.mjs";
11
+ import { upstreamErrorEvidence } from "./response-failures.mjs";
11
12
 
12
13
  export { httpError } from "./http-errors.mjs";
13
14
  export { createRequestAdmission } from "./request-admission.mjs";
@@ -275,9 +276,11 @@ export function sendJsonError(res, err, fallbackStatus = 400) {
275
276
  }
276
277
 
277
278
  export function sendUpstreamError(res, response, text) {
278
- let code;
279
- try { code = JSON.parse(text)?.error?.code; } catch {}
280
- currentRequestContext()?.onHttpError?.({ code, origin: "upstream_http", headers: response.headers });
279
+ const context = currentRequestContext();
280
+ if (context?.onHttpError) context.onHttpError({
281
+ ...upstreamErrorEvidence(text, { includeMessage: context.includeHttpErrorDetails === true }),
282
+ origin: "upstream_http", headers: response.headers,
283
+ });
281
284
  if (!res.headersSent) {
282
285
  res.writeHead(response.status || 502, safeUpstreamResponseHeaders(response.headers, {
283
286
  defaultContentType: "application/json",
@@ -0,0 +1,118 @@
1
+ import { ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH, PREDICTION_FIX_CAPABILITY, adapterHealthPayload } from "./running-adapter.mjs";
2
+ import { ADAPTER_CACHE_PATH, cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
3
+ import { createRequestAbort, readJsonBody, sendJsonError } from "./http-transport.mjs";
4
+ import { httpError } from "./http-errors.mjs";
5
+ import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
6
+
7
+ export function isManagementRoute(method, pathname) {
8
+ return (method === "GET" && [ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH].includes(pathname))
9
+ || pathname === ADAPTER_PREDICTION_FIX_PATH || pathname === ADAPTER_CACHE_PATH;
10
+ }
11
+
12
+ // Management retains its own access checks; it receives snapshots and explicit
13
+ // actions, never an inference client or a second integration lifecycle.
14
+ export function createManagementHandler({ statusSnapshot, nativePredictionPac, fixPrediction, requestBodyTimeoutMs } = {}) {
15
+ const options = { nativePredictionPac, fixPrediction };
16
+ return async (req, res, pathname) => {
17
+ if (req.method === "GET" && pathname === ADAPTER_STATUS_PATH) {
18
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || !isLoopbackHostHeader(req.headers?.host)) {
19
+ res.writeHead(403, { "Content-Type": "application/json" });
20
+ res.end(JSON.stringify({ error: "Runtime status is available only from loopback" }));
21
+ return;
22
+ }
23
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
24
+ res.end(JSON.stringify(statusSnapshot()));
25
+ return;
26
+ }
27
+
28
+ if (req.method === "GET" && pathname === ADAPTER_HEALTH_PATH) {
29
+ res.writeHead(200, { "Content-Type": "application/json" });
30
+ const predictionPac = isLoopbackAddress(req.socket?.remoteAddress) && isLoopbackHostHeader(req.headers?.host)
31
+ ? options.nativePredictionPac?.() : null;
32
+ const health = adapterHealthPayload();
33
+ res.end(JSON.stringify({ ...health,
34
+ capabilities: [...health.capabilities, ...(typeof options.fixPrediction === "function" ? [PREDICTION_FIX_CAPABILITY] : [])],
35
+ ...(predictionPac ? { native_prediction_pac: predictionPac } : {}) }));
36
+ return;
37
+ }
38
+
39
+ if (pathname === ADAPTER_PREDICTION_FIX_PATH) {
40
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers?.host === undefined
41
+ || !isLoopbackHostHeader(req.headers.host) || Object.hasOwn(req.headers, "origin")) {
42
+ sendJsonError(res, httpError("Prediction repair is available only to native loopback clients", 403));return;
43
+ }
44
+ if (req.method !== "POST") {
45
+ res.setHeader?.("Allow", "POST");sendJsonError(res, httpError("Prediction repair requires POST", 405));return;
46
+ }
47
+ if (String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase() !== "application/json") {
48
+ sendJsonError(res, httpError("Prediction repair requires application/json", 415));return;
49
+ }
50
+ if (typeof options.fixPrediction !== "function") {
51
+ sendJsonError(res, httpError("This adapter does not support prediction repair; upgrade and restart CCDX once", 503));return;
52
+ }
53
+ const abort = createRequestAbort(req, res);abort.setTimeout(2000);
54
+ try {
55
+ const body = await readJsonBody(req, { maxBodyBytes: 1024, maxDecodedBodyBytes: 1024, signal: abort.signal });
56
+ if (!body || Object.keys(body).length !== 1 || body.action !== "fix") throw httpError("Expected prediction repair action: fix", 400);
57
+ abort.clearTimeout();
58
+ const result = await options.fixPrediction();
59
+ if (!res.destroyed && !res.writableEnded) {
60
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(result));
61
+ }
62
+ } catch (error) { sendJsonError(res, error, 503); }
63
+ finally { abort.cleanup(); }
64
+ return;
65
+ }
66
+
67
+ if (pathname === ADAPTER_CACHE_PATH) {
68
+ if (!isLoopbackAddress(req.socket?.remoteAddress) || !isLoopbackHostHeader(req.headers?.host)) {
69
+ res.writeHead(403, { "Content-Type": "application/json" });
70
+ res.end(JSON.stringify({ error: "Cache control is available only from loopback" }));
71
+ return;
72
+ }
73
+ if (req.method === "GET") {
74
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
75
+ res.end(JSON.stringify(cacheRuntimeSnapshot()));
76
+ return;
77
+ }
78
+ if (req.method !== "POST") {
79
+ res.writeHead(405, { "Content-Type": "application/json", Allow: "GET, POST" });
80
+ res.end(JSON.stringify({ error: "Only GET and POST are supported" }));
81
+ return;
82
+ }
83
+ if (Object.hasOwn(req.headers || {}, "origin")) {
84
+ res.writeHead(403, { "Content-Type": "application/json" });
85
+ res.end(JSON.stringify({ error: "Browser origins are not allowed for cache control" }));
86
+ return;
87
+ }
88
+ const mediaType = String(req.headers?.["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
89
+ if (mediaType !== "application/json") {
90
+ res.writeHead(415, { "Content-Type": "application/json" });
91
+ res.end(JSON.stringify({ error: "Cache control requires application/json" }));
92
+ return;
93
+ }
94
+ const abort = createRequestAbort(req, res);
95
+ abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
96
+ try {
97
+ const body = await readJsonBody(req, {
98
+ maxBodyBytes: 8 * 1024,
99
+ maxDecodedBodyBytes: 8 * 1024,
100
+ signal: abort.signal,
101
+ });
102
+ let result;
103
+ if (body?.action === "set_limit") result = setHistoryCacheLimit(body.max_bytes);
104
+ else if (body?.action === "clean") result = cleanRuntimeCaches({ history: body.history === true });
105
+ else throw httpError("Unknown cache action", 400);
106
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
107
+ res.end(JSON.stringify(result));
108
+ } catch (error) {
109
+ if (["ccdx_cache_busy", "ccdx_cache_limit_below_usage"].includes(error?.code)) error.statusCode = 409;
110
+ sendJsonError(res, error, 400);
111
+ } finally {
112
+ abort.cleanup();
113
+ }
114
+ return;
115
+ }
116
+
117
+ };
118
+ }
@@ -0,0 +1,33 @@
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js"]);
2
+ export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth"]);
3
+
4
+ export function isOptionalRoute(method, pathname) {
5
+ return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
6
+ || ((method === "GET" || method === "HEAD") && DASHBOARD_PATHS.has(pathname));
7
+ }
8
+
9
+ // Optional handlers load only on their own routes. Failure is contained by the
10
+ // shared HTTP dispatcher and cannot initialize or change core inference.
11
+ export function createOptionalRoutes(options = {}) {
12
+ let imageMcpHandler = options.imageMcpHandler || null;
13
+ return {
14
+ imageStats() { return imageMcpHandler?.stats?.(); },
15
+ async handle(req, res, pathname) {
16
+ if (DASHBOARD_API_PATHS.has(pathname)) {
17
+ const { handleDashboardApi } = await import("./dashboard-api.mjs");
18
+ return handleDashboardApi(req, res, pathname, options.dashboardOptions);
19
+ }
20
+ if ((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname)) {
21
+ const { serveDashboard } = await import("./dashboard.mjs");
22
+ return serveDashboard(req, res, pathname);
23
+ }
24
+ if (pathname === "/mcp/image") {
25
+ if (imageMcpHandler) return imageMcpHandler(req, res);
26
+ return import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
27
+ imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
28
+ return imageMcpHandler(req, res);
29
+ });
30
+ }
31
+ },
32
+ };
33
+ }
@@ -83,26 +83,85 @@ export function createResponseFailureDiagnostics({
83
83
  const recent = [];
84
84
  let total = 0;
85
85
  let retried = 0;
86
+ const copy = entry => ({ ...entry,
87
+ ...(entry.request_options ? { request_options: { ...entry.request_options } } : {}),
88
+ ...(entry.attempt_timings ? { attempt_timings: entry.attempt_timings.map(attempt => ({ ...attempt })) } : {}),
89
+ });
86
90
  return {
87
91
  record(details) {
88
92
  total += 1;
89
93
  if (details.retried) retried += 1;
90
- recent.push({ ...details, at: now() });
94
+ recent.push(copy({ ...details, at: now() }));
91
95
  if (recent.length > maxEntries) recent.splice(0, recent.length - maxEntries);
92
96
  },
93
97
  snapshot() {
94
98
  return {
95
99
  total,
96
100
  retried,
97
- recent: recent.map((entry) => ({ ...entry })),
101
+ recent: recent.map(copy),
98
102
  };
99
103
  },
100
104
  };
101
105
  }
102
106
 
103
- export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers }) {
107
+ export function upstreamErrorEvidence(text, { includeMessage = false } = {}) {
108
+ const errorBody = !String(text || "").trim() ? "empty" : "unstructured";
109
+ let error;
110
+ try { const parsed = JSON.parse(text); error = parsed?.error; } catch {}
111
+ if (!error || typeof error !== "object" || Array.isArray(error)) return { error_body: errorBody,
112
+ ...(includeMessage && errorBody !== "empty" ? { diagnostic_message: safeFailureMessage(typeof error === "string" ? error : text) } : {}) };
113
+ const technical = value => typeof value === "string" && /^[a-z\d_.:-]{1,80}$/i.test(value)
114
+ && redactDiagnosticText(value) === value ? value : undefined;
115
+ const param = typeof error.param === "string" && error.param.length <= 160
116
+ && /^(?:model|input|tools|tool_choice|reasoning|text|temperature|top_p|max_output_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
117
+ ? error.param : undefined;
118
+ return { error_body: "structured", code: technical(error.code), error_type: technical(error.type),
119
+ parameter: param, ...(includeMessage && typeof error.message === "string" ? { diagnostic_message: safeFailureMessage(error.message) } : {}) };
120
+ }
121
+
122
+ export function requestOptionsEvidence(body) {
123
+ const result = {};
124
+ if (!body || typeof body !== "object") return result;
125
+ if (["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"].includes(body.reasoning?.effort)) result.reasoning_effort = body.reasoning.effort;
126
+ if (["auto", "default", "flex", "priority", "scale"].includes(body.service_tier)) result.service_tier = body.service_tier;
127
+ if (["text", "json_object", "json_schema"].includes(body.text?.format?.type)) result.output_format = body.text.format.type;
128
+ if (Number.isSafeInteger(body.max_output_tokens) && body.max_output_tokens >= 0) result.max_output_tokens = body.max_output_tokens;
129
+ if (Array.isArray(body.tools)) result.tools = body.tools.length;
130
+ if (Array.isArray(body.input)) result.input_items = body.input.length;
131
+ return result;
132
+ }
133
+
134
+ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
135
+ const all = createResponseFailureDiagnostics({ maxEntries, now });
136
+ const actionable = createResponseFailureDiagnostics({ maxEntries, now });
137
+ const protocol = createResponseFailureDiagnostics({ maxEntries: 8, now });
138
+ const counts = { inference: 0, protocol: 0, route: 0, other: 0 };
139
+ return {
140
+ record(details) {
141
+ all.record(details);
142
+ const category = ["responses", "responses_compact"].includes(details.route) ? "inference"
143
+ : details.route === "image_mcp" && details.http_status === 405 ? "protocol"
144
+ : details.route === "not_found" ? "route" : "other";
145
+ counts[category]++;
146
+ if (category === "inference" || category === "other") actionable.record(details);
147
+ if (category === "protocol") protocol.record(details);
148
+ },
149
+ snapshot() { return { ...all.snapshot(), by_category: { ...counts },
150
+ actionable_recent: actionable.snapshot().recent, protocol_recent: protocol.snapshot().recent }; },
151
+ };
152
+ }
153
+
154
+ export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers,
155
+ error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model }) {
104
156
  const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
105
- message: "HTTP request failed; original response was preserved." } }, "http.error", { headers });
157
+ message: error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved." } }, "http.error", { headers });
106
158
  return { ...details, request_id: requestId, http_status: statusCode, route,
107
- origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true };
159
+ origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
160
+ ...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}), ...(parameter ? { parameter } : {}),
161
+ ...(diagnostic_message ? { diagnostic_message } : {}),
162
+ ...(method ? { method } : {}), ...(target ? { target } : {}),
163
+ ...(request_options ? { request_options } : {}),
164
+ ...(attempt_timings ? { attempt_timings } : {}),
165
+ ...(requested_model ? { requested_model, request_kind: requested_model === "codex-auto-review" ? "auto_review" : "unknown" } : {}),
166
+ ...(Number.isSafeInteger(upstream_attempts) ? { upstream_attempts } : {}) };
108
167
  }
@@ -273,7 +273,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
273
273
  bodyText,
274
274
  onUpstreamStart,
275
275
  });
276
- markUpstreamHeaders();
276
+ markUpstreamHeaders(resp.status);
277
277
  } finally {
278
278
  bodyText = undefined;
279
279
  chatReq = undefined;
@@ -1,5 +1,5 @@
1
1
  import { getCachedModelEndpoints } from "./copilot.mjs";
2
- import { applyCopilotResponsesRequestPolicies } from "./copilot-responses-policy.mjs";
2
+ import { applyCopilotResponsesRequestPolicies, stripUnsupportedGpt6ServiceTier } from "./copilot-responses-policy.mjs";
3
3
  import {
4
4
  createRequestAbort,
5
5
  logRequestFailure,
@@ -103,15 +103,6 @@ function resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver) {
103
103
  ? preference.reasoningEffort : undefined };
104
104
  }
105
105
 
106
- function stripUnsupportedGpt6ServiceTier(body, requestedModel, upstreamModel, priorityTierModel) {
107
- if (requestedModel.startsWith("gpt-6-")
108
- && upstreamModel === requestedModel
109
- && !priorityTierModel
110
- && body.service_tier === "priority") {
111
- delete body.service_tier;
112
- }
113
- }
114
-
115
106
  export function createResponsesHandler(options) {
116
107
  const {
117
108
  acquireRequest,
@@ -287,7 +278,7 @@ export function createResponsesHandler(options) {
287
278
  }
288
279
  }
289
280
  if (upstreamModel !== requestedModel) prepared.body.model = upstreamModel;
290
- markResponseModel(upstreamModel);
281
+ markResponseModel(upstreamModel, { requestedModel });
291
282
  markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
292
283
  const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
293
284
  console.log(status("info", `responses model=${requestedModel}${upstreamLog} stream=${streaming}`));
@@ -400,7 +391,7 @@ export function createResponsesHandler(options) {
400
391
  bodyText,
401
392
  onUpstreamStart: startUpstreamTimeout,
402
393
  });
403
- markUpstreamHeaders();
394
+ markUpstreamHeaders(upstream.status);
404
395
  releaseChatPayload();
405
396
  const data = upstream.ok
406
397
  ? await readBoundedResponseText(upstream, {
@@ -575,6 +566,7 @@ export function createResponsesCompactHandler(options) {
575
566
  markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
576
567
  const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
577
568
  console.log(status("info", `responses compact model=${requestedModel}${upstreamLog} stream=false`));
569
+ markResponseModel(upstreamModel, { requestedModel });
578
570
  prepared = applyResponseHistoryRoutePlan(prepared, createRoutePlan({
579
571
  disposition: "relay",
580
572
  origin: "ccdx",
@@ -133,6 +133,7 @@ function createRoutePerformance() {
133
133
  return {
134
134
  ttft: createHistogram(TTFT_EDGES_MS),
135
135
  tpot: createHistogram(TPOT_EDGES_US),
136
+ outputRate: { intervals: 0, milliseconds: 0, samples: 0 },
136
137
  requestTtft: createHistogram(TTFT_EDGES_MS),
137
138
  outputSources: { delta: 0, announcement: 0, snapshot: 0, runtime: 0 },
138
139
  preparation: Object.fromEntries(PREPARATION_STAGES.map((stage) => [stage, createHistogram(PREPARATION_EDGES_MS)])),
@@ -163,6 +164,14 @@ function routeSnapshot(route) {
163
164
  },
164
165
  ttft_ms: histogramSnapshot(route.ttft, "ms"),
165
166
  tpot_us: histogramSnapshot(route.tpot, "us"),
167
+ output_tokens_per_second: {
168
+ avg: route.outputRate.milliseconds > 0
169
+ ? Number((route.outputRate.intervals * 1000 / route.outputRate.milliseconds).toFixed(1)) : null,
170
+ samples: route.outputRate.samples,
171
+ unit: "token/s",
172
+ aggregation: "time_weighted_per_request",
173
+ estimated: true,
174
+ },
166
175
  request_ttft_ms: histogramSnapshot(route.requestTtft, "ms"),
167
176
  first_output_sources: { ...route.outputSources },
168
177
  timing_boundary: "gateway_observed",
@@ -195,6 +204,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
195
204
  const preparationMs = Object.fromEntries(PREPARATION_STAGES.map((stage) => [stage, 0]));
196
205
  let phase = "received";
197
206
  let attempts = 0;
207
+ const attemptTimings = [];
198
208
  let firstAttemptAt = null;
199
209
  let headersAt = null;
200
210
  let lastActivityAt = null;
@@ -221,15 +231,22 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
221
231
  if (finished) return;
222
232
  const time = now();
223
233
  attempts += 1;
234
+ if (attemptTimings.length === 3) attemptTimings.splice(1, 1);
235
+ attemptTimings.push({ attempt: attempts, started_ms: elapsed(time), headers_ms: null, http_status: null });
224
236
  firstAttemptAt ??= time;
225
237
  phase = "upstream_connection";
226
238
  if (streaming && upstreamStartedAt === null) upstreamStartedAt = time;
227
239
  },
228
- upstreamHeaders() {
240
+ upstreamHeaders(statusCode) {
229
241
  if (finished) return;
230
242
  headersAt = now();
231
243
  lastActivityAt = headersAt;
232
244
  phase = "upstream_response";
245
+ const attempt = attemptTimings.at(-1);
246
+ if (attempt) {
247
+ attempt.headers_ms = elapsed(headersAt);
248
+ attempt.http_status = Number.isInteger(statusCode) && statusCode >= 100 && statusCode <= 599 ? statusCode : null;
249
+ }
233
250
  },
234
251
  upstreamActivity() {
235
252
  if (finished) return;
@@ -249,6 +266,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
249
266
  setModel(value) {
250
267
  model = modelLabel(value);
251
268
  },
269
+ attemptCount() { return attempts; },
270
+ attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
252
271
  observeContext(values) {
253
272
  if (finished || !values || typeof values !== "object") return;
254
273
  for (const key of Object.keys(context)) {
@@ -297,6 +316,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
297
316
  failed: failed || aborted || (terminalOutcome !== null && terminalOutcome !== "completed"),
298
317
  http_status: Number.isInteger(statusCode) && statusCode >= 100 && statusCode <= 599 ? statusCode : null,
299
318
  upstream_attempts: attempts,
319
+ attempts: attemptTimings.map(attempt => ({ ...attempt })),
300
320
  first_output_source: firstOutputSource,
301
321
  context: { ...context },
302
322
  timings_ms: {
@@ -321,6 +341,12 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
321
341
  observe(route.ttft, Math.max(0, firstOutputAt - upstreamStartedAt));
322
342
  if (outputTokens !== null && outputTokens >= 2) {
323
343
  observe(route.tpot, Math.max(0, ((finishedAt - firstOutputAt) * 1_000) / (outputTokens - 1)));
344
+ const milliseconds = finishedAt - firstOutputAt;
345
+ if (Number.isSafeInteger(outputTokens) && milliseconds > 0) {
346
+ route.outputRate.intervals += outputTokens - 1;
347
+ route.outputRate.milliseconds += milliseconds;
348
+ route.outputRate.samples += 1;
349
+ }
324
350
  }
325
351
  if (failed) route.errors_with_output += 1;
326
352
  else route.success_with_output += 1;
@@ -330,7 +356,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
330
356
  snapshot() {
331
357
  return {
332
358
  by_route: Object.fromEntries(PERFORMANCE_ROUTES.map((name) => [name, routeSnapshot(routes[name])])),
333
- recent_requests: recentRequests.map((entry) => ({ ...entry, context: { ...entry.context }, timings_ms: { ...entry.timings_ms } })),
359
+ recent_requests: recentRequests.map((entry) => ({ ...entry, attempts: entry.attempts.map(attempt => ({ ...attempt })), context: { ...entry.context }, timings_ms: { ...entry.timings_ms } })),
334
360
  };
335
361
  },
336
362
  };
@@ -362,8 +388,8 @@ export function markUpstreamStarted(streaming = true) {
362
388
  tracker()?.upstreamStarted(streaming);
363
389
  }
364
390
 
365
- export function markUpstreamHeaders() {
366
- tracker()?.upstreamHeaders?.();
391
+ export function markUpstreamHeaders(statusCode) {
392
+ tracker()?.upstreamHeaders?.(statusCode);
367
393
  }
368
394
 
369
395
  export function markUpstreamActivity() {
@@ -386,9 +412,12 @@ export function markStreamFailure() {
386
412
  tracker()?.fail();
387
413
  }
388
414
 
389
- export function markResponseModel(model) {
415
+ export function markResponseModel(model, { requestedModel } = {}) {
390
416
  const context = currentRequestContext();
391
- if (context) context.model = model;
417
+ if (context) {
418
+ context.model = model;
419
+ if (requestedModel !== undefined) context.requestedModel = modelLabel(requestedModel);
420
+ }
392
421
  tracker()?.setModel?.(model);
393
422
  }
394
423