codex-copilot-dx 0.9.39 → 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.
@@ -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 {
@@ -15,6 +15,7 @@ import {
15
15
  normalizeGithubIdentity,
16
16
  } from "./github-identity.mjs";
17
17
  import { status } from "./status.mjs";
18
+ import { cancelResponseBody } from "./auth-device-flow.mjs";
18
19
 
19
20
  const GITHUB_API = "https://api.github.com";
20
21
 
@@ -251,6 +252,7 @@ export function createCopilotTokenSession({
251
252
  throw error;
252
253
  }
253
254
  if (!response.ok) {
255
+ cancelResponseBody(response);
254
256
  if ((response.status === 401 || response.status === 403) && allowTokenDiscovery) {
255
257
  const imported = await importDiscoveredGithubToken({
256
258
  home: resolvedHome,
@@ -272,9 +274,23 @@ export function createCopilotTokenSession({
272
274
  }
273
275
  if (response.status === 401 || response.status === 403) {
274
276
  const prefix = profile === "codex" ? "Failed to get Copilot token" : `Failed to get Copilot token for ${profile} profile`;
275
- throw refreshError(formatReauth(`${prefix}: ${response.status}. The saved GitHub token may be expired, revoked, or missing Copilot access.`, resolvedHome), {
276
- statusCode: response.status,
277
- });
277
+ const reason = `${prefix}: ${response.status}.`;
278
+ if (!usesDefaultTokenStore || typeof reauthMessage === "function") {
279
+ throw refreshError(formatReauth(`${reason} The saved GitHub token may be expired, revoked, or missing Copilot access.`, resolvedHome), {
280
+ statusCode: response.status,
281
+ });
282
+ }
283
+ // A Copilot denial is not proof that the underlying GitHub credential
284
+ // expired. Only GitHub's own 401 can justify reauthorization guidance.
285
+ const identity = response.status === 401
286
+ ? await fetchGithubIdentity(credentials.token, { fetchImpl, signal, timeoutMs: 4000 }) : null;
287
+ if (signal?.aborted) throw abortError(signal);
288
+ const message = identity?.status === 401
289
+ ? formatReauth(`${reason} GitHub also rejected the saved credential.`, resolvedHome)
290
+ : `${reason} The saved GitHub credential was preserved. ${response.status === 403 || identity?.ok
291
+ ? "Check Copilot account access and network policy; this response does not establish that a new login is needed."
292
+ : "GitHub credential validity could not be confirmed; check network access before changing authentication."}`;
293
+ throw refreshError(message, { statusCode: response.status });
278
294
  }
279
295
  const prefix = profile === "codex" ? "Failed to get Copilot token" : `Failed to get Copilot token for ${profile} profile`;
280
296
  throw refreshError(`${prefix}: ${response.status}`, {
@@ -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",
package/src/launcher.mjs CHANGED
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { installedWindowsPredictionApp, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
5
5
  import { status } from "./status.mjs";
6
+ import { isPredictionPacUrl } from "./prediction-pac.mjs";
6
7
 
7
8
  export { ensureAuth } from "./auth.mjs";
8
9
 
@@ -50,7 +51,7 @@ export function macPredictionAppProcesses(app, { exec = execFileSync } = {}) {
50
51
  const pid = Number(match[1]);
51
52
  try {
52
53
  const args = exec("/bin/ps", ["-p", String(pid), "-o", "args="], options);
53
- const route = args.match(/(?:^|\s)--proxy-pac-url=(?:"(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac)"|(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac)(?=\s|$))/);
54
+ const route = args.match(/(?:^|\s)--proxy-pac-url=(?:"(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?)"|(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?)(?=\s|$))/);
54
55
  const readable = args.trim() === match[2] || args.trimStart().startsWith(`${match[2]} `);
55
56
  const uniqueRoute = (args.match(/(?:^|\s)--proxy-pac-url=/g) || []).length === 1;
56
57
  rows.push({ pid, readable, route: readable && uniqueRoute ? route?.[1] || route?.[2] || null : null });
@@ -64,8 +65,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
64
65
  preparePredictionRoute, persistedPredictionRoute = false, onPredictionRoute = () => {}, log = console.log,
65
66
  resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses,
66
67
  macAppProcesses = macPredictionAppProcesses } = {}) {
67
- if (platform === "win32" && autoLaunchEnabled(env) && typeof predictionPacUrl === "string"
68
- && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(predictionPacUrl)
68
+ if (platform === "win32" && autoLaunchEnabled(env) && isPredictionPacUrl(predictionPacUrl)
69
69
  && typeof predictionApp === "string" && path.win32.isAbsolute(predictionApp)) {
70
70
  try {
71
71
  if (typeof predictionProfile !== "string" || !path.win32.isAbsolute(predictionProfile)
@@ -124,7 +124,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
124
124
  return false;
125
125
  }
126
126
 
127
- const extraArgs = typeof predictionPacUrl === "string" && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(predictionPacUrl)
127
+ const extraArgs = isPredictionPacUrl(predictionPacUrl)
128
128
  && APP_PATH_CANDIDATES.includes(predictionApp)
129
129
  ? ["--args", `--proxy-pac-url=${predictionPacUrl}`] : [];
130
130
  if (extraArgs.length) {
@@ -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
+ }
@@ -4,9 +4,9 @@ import { isDeepStrictEqual } from "node:util";
4
4
  import { readBoundedFileSync } from "./bounded-file.mjs";
5
5
  import { atomicWriteFileSync } from "./atomic-file.mjs";
6
6
  import { withFileLock } from "./lock.mjs";
7
+ import { isPredictionPacUrl } from "./prediction-pac.mjs";
7
8
 
8
- const validPac = value => typeof value === "string" && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(value)
9
- && Number(new URL(value).port) >= 1024 && Number(new URL(value).port) <= 65535;
9
+ const validPac = isPredictionPacUrl;
10
10
  const object = value => value && typeof value === "object" && !Array.isArray(value);
11
11
 
12
12
  function regularFile(file) {
@@ -4,6 +4,7 @@ import { promisify } from "node:util";
4
4
  import { gunzip, inflate, brotliDecompress } from "node:zlib";
5
5
  import { networkPredictionPac } from "./network-route.mjs";
6
6
  import { operationErrorDetails } from "./operation-error.mjs";
7
+ import { PREDICTION_PAC_PATH, predictionProxyExpression } from "./prediction-pac.mjs";
7
8
 
8
9
  export const PREDICTION_HOSTS = Object.freeze(["chatgpt.com", "ab.chatgpt.com"]);
9
10
  const CONFIG_LIMIT = 16 * 1024 * 1024;
@@ -20,7 +21,7 @@ export function predictionRoute(host, pathname) {
20
21
  export function predictionPac(port, networkRoute) {
21
22
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid prediction proxy port");
22
23
  if (networkRoute) return networkPredictionPac(port, networkRoute);
23
- return `function FindProxyForURL(url, host) { if (url.indexOf('https:') === 0 && (host === 'chatgpt.com' || host === 'ab.chatgpt.com')) return 'PROXY 127.0.0.1:${port}; DIRECT'; return 'DIRECT'; }\n`;
24
+ return `function FindProxyForURL(url, host) { if (url.indexOf('https:') === 0 && (host === 'chatgpt.com' || host === 'ab.chatgpt.com')) return ${predictionProxyExpression(port)}+'; DIRECT'; return 'DIRECT'; }\n`;
24
25
  }
25
26
 
26
27
  function cleanHeaders(headers) {
@@ -220,7 +221,7 @@ export async function startPredictionTransport({
220
221
  gateway.on("tlsClientError", (error, socket) => { onEvent({ type: "tls_error", error: operationErrorDetails(error) }); socket.destroy(); });
221
222
  gateway.on("clientError", (_error, socket) => socket.destroy());
222
223
  const proxy = http.createServer((req, res) => {
223
- if (req.method === "GET" && req.url === "/proxy.pac" && !req.headers.origin
224
+ if (req.method === "GET" && ["/proxy.pac", PREDICTION_PAC_PATH].includes(req.url) && !req.headers.origin
224
225
  && ["127.0.0.1", "localhost"].includes(String(req.headers.host || "").split(":")[0])) {
225
226
  res.writeHead(200, { "Content-Type": "application/x-ns-proxy-autoconfig", "Cache-Control": "no-store" });
226
227
  res.end(pacImpl ? pacImpl(proxy.address().port) : predictionPac(proxy.address().port, networkRoute)); return;
@@ -249,7 +250,7 @@ export async function startPredictionTransport({
249
250
  try { port = await listen(proxy, listenPort); }
250
251
  catch (error) { agent?.destroy();gateway.close();throw error; }
251
252
  return {
252
- port, pacUrl: `http://127.0.0.1:${port}/proxy.pac`,
253
+ port, pacUrl: `http://127.0.0.1:${port}${PREDICTION_PAC_PATH}`,
253
254
  healthy() { return !closing && !listenerError && proxy.listening; },
254
255
  async close() {
255
256
  closing = true;
@@ -35,7 +35,7 @@ export function windowsPredictionAppProcesses(app, { env = process.env, ...optio
35
35
  $_.ExecutablePath -eq $env:CCDX_PREDICTION_APP_PATH -and ($_.CommandLine -notmatch '--type(?:=|\\s)')
36
36
  } | ForEach-Object {
37
37
  $route=$null;
38
- if($_.CommandLine -match '--proxy-pac-url=(?:"(http://127\\.0\\.0\\.1:\\d{1,5}/proxy\\.pac)"|(http://127\\.0\\.0\\.1:\\d{1,5}/proxy\\.pac))'){
38
+ if($_.CommandLine -match '--proxy-pac-url=(?:"(http://127\\.0\\.0\\.1:\\d{1,5}/proxy\\.pac(?:\\?v=2)?)"|(http://127\\.0\\.0\\.1:\\d{1,5}/proxy\\.pac(?:\\?v=2)?)(?=\\s|$))'){
39
39
  $route=if($Matches[1]){$Matches[1]}else{$Matches[2]}
40
40
  };
41
41
  @{pid=[int]$_.ProcessId;route=$route;readable=![string]::IsNullOrWhiteSpace($_.CommandLine)}
@@ -43,7 +43,7 @@ export function windowsPredictionAppProcesses(app, { env = process.env, ...optio
43
43
  let rows;
44
44
  try { rows = JSON.parse(raw); } catch { throw new Error("Could not verify the running Windows App route; launch was skipped"); }
45
45
  if (!Array.isArray(rows) || rows.length > 8 || rows.some(row => !Number.isInteger(row?.pid) || typeof row.readable !== "boolean"
46
- || (row.route !== null && (typeof row.route !== "string" || !/^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(row.route))))) {
46
+ || (row.route !== null && (typeof row.route !== "string" || !/^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?$/.test(row.route))))) {
47
47
  throw new Error("Unknown running Windows App route; launch was skipped");
48
48
  }
49
49
  return rows;
@@ -1,5 +1,6 @@
1
1
  import net from "node:net";
2
2
  import { compileBypassRules, matchesBypass, bypassPacSource } from "./network-bypass.mjs";
3
+ import { predictionProxyExpression } from "./prediction-pac.mjs";
3
4
 
4
5
  const OFFICIAL_API = "https://chatgpt.com/backend-api";
5
6
  const routeError = (code, message) => Object.assign(new Error(message), { code });
@@ -80,7 +81,7 @@ function FindProxyForURL(url,host) {
80
81
  var authority=url.split('/')[2]||'', explicit=/:([0-9]+)$/.exec(authority);if(explicit)p=Number(explicit[1]);
81
82
  var skip=matchesBypass(host,p,ccdxRoute.rules,ccdxRoute.excludeSimple);
82
83
  var original=skip?'DIRECT':secure?ccdxRoute.https:ccdxRoute.http;
83
- if(secure&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return 'PROXY 127.0.0.1:${port}; '+original;
84
+ if(secure&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return ${predictionProxyExpression(port)}+'; '+original;
84
85
  return original;
85
86
  }\n`;
86
87
  }
@@ -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
+ }
@@ -0,0 +1,17 @@
1
+ // A stable format revision, not the CCDX package version. Existing Apps must
2
+ // load it once; later adapter upgrades keep the same URL, port and trust.
3
+ export const PREDICTION_PAC_PATH = "/proxy.pac?v=2";
4
+
5
+ export function isPredictionPacUrl(value) {
6
+ const match = typeof value === "string" && /^http:\/\/127\.0\.0\.1:(\d{1,5})\/proxy\.pac(?:\?v=2)?$/.exec(value);
7
+ return Boolean(match && Number(match[1]) >= 1024 && Number(match[1]) <= 65535);
8
+ }
9
+
10
+ // Chromium caches failed proxy endpoints separately from the PAC URL. A fresh
11
+ // loopback-only name lets its next resolution retry a restored listener without
12
+ // waiting for that failed endpoint's retry cache. No timer, DNS lookup in Node,
13
+ // new port, process, or system proxy mutation is involved.
14
+ export function predictionProxyExpression(port) {
15
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid prediction proxy port");
16
+ return `'PROXY 127.0.0.1:${port}; PROXY ccdx-'+Math.floor(Date.now()/10000)+'.localhost:${port}'`;
17
+ }
@@ -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",