codex-copilot-dx 1.3.18 → 1.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,11 @@
13
13
  image_check: ["Check access", "检查接入"],
14
14
  image_repair: ["Repair access", "修复接入"],
15
15
  image_open: ["Open Codex", "打开 Codex"],
16
+ image_focus: ["Switch to Codex", "切换到 Codex"],
17
+ image_restart: ["Restart Codex to connect", "重启 Codex 以接入"],
18
+ image_inspect: ["Check Codex", "检查 Codex"],
19
+ image_restart_warning: ["Restarting Codex interrupts its running tasks. Finish or save them first.", "重启 Codex 会中断正在执行的任务,请先完成或保存。"],
20
+ image_app_stopped: ["Codex is not running. Image access is checked when it opens.", "Codex 未运行,启动后会检查图片接入。"],
16
21
  image_host_unconfirmed: ["App host connection unconfirmed.", "尚未确认 App 图片宿主连接。"],
17
22
  image_host_connected: ["App host connected; new chat tool registration unconfirmed.", "App 宿主已连接;尚未确认新聊天工具注册。"],
18
23
  image_host_registered: ["Image tool registration observed in a connected host. Other chats may differ.", "已在连接的宿主中观察到图片工具注册,其他聊天可能不同。"],
@@ -24,6 +29,24 @@
24
29
  image_action_opened_new_chat_required: ["Codex launch requested. Use a new chat; registration remains unconfirmed until observed.", "已请求打开 Codex。请使用新聊天;观察到注册前仍显示未确认。"],
25
30
  image_action_open_failed: ["Could not open Codex. Check the App installation.", "未能打开 Codex,请检查 App 安装。"],
26
31
  image_action_unsupported: ["Native image host launch is unavailable on this platform.", "当前平台无法准备原生图片宿主启动。"],
32
+ image_action_focused: ["Requested to switch to Codex.", "已请求切换到 Codex。"],
33
+ image_action_focus_unavailable: ["Could not switch to Codex. Check its current state.", "无法切换到 Codex,请检查当前状态。"],
34
+ image_action_app_not_running: ["Codex is not running. Check its state and open it here.", "Codex 当前未运行,请检查状态后从这里打开。"],
35
+ image_action_already_connected: ["The running Codex App has an image host. A chat may still need a new conversation.", "运行中的 Codex 已连接图片宿主,部分聊天仍需新建对话。"],
36
+ image_action_image_unavailable: ["Image access or the selected model is unavailable. Codex was not restarted.", "图片访问或所选模型不可用,Codex 未重启。"],
37
+ image_action_app_route_conflict: ["The Codex App and suggestion route differ. Codex was not restarted.", "Codex App 与输入建议的接入目标不一致,未重启。"],
38
+ image_action_prediction_unavailable: ["Input suggestions could not be prepared. Codex was not restarted.", "输入建议暂时无法准备,Codex 未重启。"],
39
+ image_action_app_check_failed: ["Could not verify the Codex App state. Codex was not restarted.", "无法确认 Codex App 状态,未重启。"],
40
+ image_action_multiple_apps: ["Multiple Codex App processes were found. Close the extra App, then check again.", "检测到多个 Codex App 进程,请关闭多余的 App 后重新检查。"],
41
+ image_action_quit_refused: ["Codex could not be closed normally. It was not force-quit.", "无法正常退出 Codex,未强制结束。"],
42
+ image_action_quit_timeout: ["Codex did not close in time. Finish its tasks and try again.", "Codex 未在预期时间内退出,请完成任务后重试。"],
43
+ image_action_app_changed: ["The running Codex App changed while restarting. Check it before trying again.", "重启期间 Codex App 状态发生变化,请检查后再试。"],
44
+ codex_action_checked: ["Codex App state checked.", "已检查 Codex App 状态。"],
45
+ codex_action_ready: ["The running Codex App has the selected integrations ready.", "运行中的 Codex 已具备所选接入。"],
46
+ codex_action_opened: ["Codex launch requested. Verify the input suggestions in the App.", "已请求打开 Codex,请在 App 中确认输入建议。"],
47
+ codex_action_prediction_pending: ["Codex opened, but input suggestions still need repair.", "Codex 已打开,但输入建议仍需修复。"],
48
+ codex_action_image_pending: ["Codex opened, but image access still needs repair.", "Codex 已打开,但图片接入仍需修复。"],
49
+ codex_action_both_pending: ["Codex opened, but image access and input suggestions need repair.", "Codex 已打开,但图片接入和输入建议仍需修复。"],
27
50
  image_model: ["Image model", "图片模型"],
28
51
  image_models: ["Image models", "图片模型"],
29
52
  image_needs_github: ["Allow GitHub Copilot access for Codex.", "请允许 Codex 使用 GitHub Copilot。"],
@@ -76,6 +99,7 @@
76
99
  "context_latest_input": ["Latest input", "最近输入"],
77
100
  "context_reuse": ["Cache reuse", "缓存复用"],
78
101
  "context_history": ["Input history", "输入变化"],
102
+ "context_point_usage": ["{time} · input {input} tokens · cache reuse {reuse}", "{time} · 输入 {input} Token · 缓存复用 {reuse}"],
79
103
  "context_compactions": ["Gateway compactions", "网关压缩"],
80
104
  "context_elapsed": ["Elapsed", "耗时"],
81
105
  "context_conversation": ["Conversation {id}", "会话 {id}"],
@@ -93,6 +117,10 @@
93
117
  "issue_brief": ["{cause} · {model} · {time}", "{cause} · {model} · {time}"],
94
118
  "issue_count_unavailable": ["Token counting unavailable", "令牌计数接口不可用"],
95
119
  "issue_source_limit": ["Source usage limit reached", "模型来源用量受限"],
120
+ "issue_source_quota": ["Source credits or quota exhausted", "模型来源余额或配额不足"],
121
+ "issue_source_rate": ["Source request rate limited", "模型来源请求频率受限"],
122
+ "issue_context_limit": ["Source reports context too long", "模型来源报告上下文过长"],
123
+ "issue_content_policy": ["Source content policy rejected the request", "模型来源内容策略拒绝了请求"],
96
124
  "issue_catalog_unavailable": ["Model catalog could not be read", "模型目录读取失败"],
97
125
  "issue_model_not_selected": ["Model not selected for this app", "应用尚未选用此模型"],
98
126
  "issue_access_denied": ["Access was denied", "请求被拒绝访问"],
@@ -539,6 +567,9 @@
539
567
  "tools_access_denied": ["GitHub sign-in is valid. Check your Copilot access or company policy.", "GitHub 登录有效。请检查 Copilot 权限或公司策略。"],
540
568
  "tools_network_hint": ["Connection could not be verified. Check network settings; saved sign-in is kept.", "连接未能验证。请检查网络,原登录已保留。"],
541
569
  "tools_local_scope": ["Local checks only", "仅检查本机"],
570
+ "client_versions_scope": ["Installed versions only; running App adoption and compatibility are separate.", "显示已安装版本;运行中的版本和接入状态需分别确认。"],
571
+ "client_version_observed": ["{version}", "{version}"],
572
+ "client_version_changed": ["{version} · updated, access unverified", "{version} · 已更新,接入待确认"],
542
573
  "tools_check_local": ["Check this computer", "本机检查"],
543
574
  "tools_export_report": ["Export report", "导出报告"],
544
575
  "tools_checks_empty": ["Run a local check to see results.", "运行本机检查后查看结果。"],
@@ -972,7 +1003,7 @@
972
1003
  "entries_entries_trees_trees_misses_misses_evicted_evicted": ["Records: {entries} / groups: {trees}\nNot found: {misses} / removed: {evicted}", "暂存:{entries}条/分组:{trees}\n未找到:{misses}\n清理后未找到:{evicted}"],
973
1004
  "count_succeeded": ["{count} succeeded", "成功:{count}次"],
974
1005
  "not_initialized": ["NOT CONFIRMED", "未确认"],
975
- "active_active_failed_failed_delivery_failures_delivery": ["Running: {active} / generation failed: {failed}\nFile delivery failed: {delivery}", "进行中:{active}/生成失败:{failed}\n文件交付失败:{delivery}"],
1006
+ "active_active_failed_failed_delivery_failures_delivery": ["Running: {active} / generation failed: {failed} / file delivery failed: {delivery}", "进行中:{active}/生成失败:{failed}/文件交付失败:{delivery}"],
976
1007
  "setup_state_unknown_ccdx_image_status": ["Uses the existing GitHub Copilot account.", "使用现有 GitHub Copilot 账号。"],
977
1008
  "snapshot_time": ["Status updated {time}", "状态更新:{time}"],
978
1009
  "status_unavailable_check_ccdx_then_refresh": ["Cannot read status. Check CCDX and refresh.", "无法读取状态。\n请检查 CCDX 后刷新。"],
@@ -989,6 +1020,7 @@
989
1020
  "message": ["Error details", "错误详情"],
990
1021
  "response_id": ["Response ID", "回答编号"],
991
1022
  "upstream_request_id": ["Source request ID", "来源编号"],
1023
+ "upstream_code": ["Source error code", "来源错误码"],
992
1024
  "request_id": ["CCDX request ID", "本机编号"],
993
1025
  "outcome_25a63": ["Result", "处理结果"],
994
1026
  "origin": ["Result source", "结果来源"],
@@ -134,6 +134,10 @@
134
134
  details.open = expanded.has(details.dataset.key);
135
135
  const title = document.createElement("summary");
136
136
  const cause = failure.route === "messages_count_tokens" && [404, 405, 501].includes(failure.http_status) ? "issue_count_unavailable"
137
+ : ["credit_balance_exhausted", "insufficient_quota", "quota_exceeded"].includes(failure.upstream_code) ? "issue_source_quota"
138
+ : ["rate_limit_exceeded", "rate_limit_error"].includes(failure.upstream_code) ? "issue_source_rate"
139
+ : ["context_length_exceeded", "context_window_exceeded"].includes(failure.upstream_code) ? "issue_context_limit"
140
+ : failure.upstream_code === "content_policy_violation" ? "issue_content_policy"
137
141
  : ["rate_limit_error", "rate_limit_exceeded", "insufficient_quota", "http_429"].includes(failure.code) ? "issue_source_limit"
138
142
  : /^m365_catalog_http_/.test(failure.code || "") ? "issue_catalog_unavailable"
139
143
  : failure.reason === "ccdx_model_not_selected" ? "issue_model_not_selected"
@@ -169,7 +173,7 @@
169
173
  request_id: failure.request_id, outcome: timeline?.outcome, origin: failure.origin || timeline?.origin,
170
174
  phase: timeline?.phase, http_status: failure.http_status ?? timeline?.http_status, route: failure.route,
171
175
  upstream_attempts: failure.upstream_attempts ?? timeline?.upstream_attempts,
172
- error_type: failure.error_type, parameter: failure.parameter, error_body: failure.error_body,
176
+ error_type: failure.error_type, upstream_code: failure.upstream_code, parameter: failure.parameter, error_body: failure.error_body,
173
177
  diagnostic_message: failure.diagnostic_message, method: failure.method, target: failure.target,
174
178
  request_options: failure.request_options ? JSON.stringify(failure.request_options) : undefined,
175
179
  transport: failure.transport ? JSON.stringify(failure.transport) : undefined,
@@ -137,6 +137,7 @@
137
137
  el("github-logout").addEventListener("click", () => { if (window.confirm(language.format("tools_logout_confirm"))) void accountAction({ action: "logout", confirmed: true }); });
138
138
  async function loadAccount() { const generation = accountGeneration;try { const data = await api("account");if (generation === accountGeneration && !pending) renderAccount(data); } catch { if (generation === accountGeneration) text("github-account-note", "tools_read_failed"); } }
139
139
  function renderChecks(data) {
140
+ if (Object.hasOwn(data, "client_versions")) globalThis.ccdxClientVersions?.render(data.client_versions);
140
141
  const body = el("checks-body");body.replaceChildren();
141
142
  const groups = new Map();
142
143
  for (const check of data.checks || []) { if (!groups.has(check.id)) groups.set(check.id, []);groups.get(check.id).push(check); }
package/src/doctor.mjs CHANGED
@@ -315,6 +315,14 @@ export async function runDoctor(options = {}) {
315
315
  ].filter(Boolean);
316
316
  if (!options.json) log(`${options.commandName || "ccdx"} doctor${options.configOnly ? " config" : flags.length ? ` ${flags.join(" ")}` : ""}`);
317
317
  let checks = await collectDoctorChecks(options);
318
+ if (!options.configOnly) {
319
+ try {
320
+ const { createClientVersionMonitor, clientVersionChecks } = await import("./client-versions.mjs");
321
+ const monitor = options.clientVersions || createClientVersionMonitor({ home: options.home, env: options.env, platform: options.platform, persist: false });
322
+ try { checks.push(...clientVersionChecks(await monitor.refresh())); }
323
+ finally { if (!options.clientVersions) monitor.close(); }
324
+ } catch { checks.push({ id: "client-versions", kind: "info", message: "App version observations are unavailable" }); }
325
+ }
318
326
  const before = options.fix ? checks : undefined;
319
327
  if (options.fix && !options.configOnly) {
320
328
  const repair = options.repairDoctorFn || (await import("./doctor-repair.mjs")).repairDoctor;
@@ -280,7 +280,7 @@ export function sendJsonError(res, err, fallbackStatus = 400) {
280
280
  export function sendUpstreamError(res, response, text) {
281
281
  const context = currentRequestContext();
282
282
  if (context?.onHttpError) context.onHttpError({
283
- ...upstreamErrorEvidence(text, { includeMessage: context.includeHttpErrorDetails === true }),
283
+ ...upstreamErrorEvidence(text, { includeMessage: context.includeHttpErrorDetails === true, status: response.status }),
284
284
  origin: "upstream_http", headers: response.headers,
285
285
  });
286
286
  if (!res.headersSent) {
@@ -1,10 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { adapterBaseUrl, ADAPTER_PROTOCOL_VERSION } from "./running-adapter.mjs";
4
- import { imageHostLauncherPath, prepareImageHostLaunch } from "./codex-image-host-launch.mjs";
4
+ import { imageHostLauncherPath } from "./codex-image-host-launch.mjs";
5
5
  import { imageSetupSummary } from "./image-setup.mjs";
6
- import { openCodex, macPredictionAppProcesses } from "./launcher.mjs";
7
6
  import { readBoundedResponseText } from "./upstream-body.mjs";
7
+ import { controlCodexLaunch } from "./codex-launch-control.mjs";
8
8
 
9
9
  export async function checkImageConnection({ host = "127.0.0.1", port = 2026, fetchImpl = fetch } = {}) {
10
10
  const nonce = randomUUID();
@@ -17,26 +17,13 @@ export async function checkImageConnection({ host = "127.0.0.1", port = 2026, fe
17
17
  } catch { return { state: "unreachable", scope: "node_loopback", app_path: "unconfirmed" }; }
18
18
  }
19
19
 
20
- export async function controlImage(operation, { integration, state, host, port, models = [], prepare = prepareImageHostLaunch,
21
- launch = openCodex, appProcesses = macPredictionAppProcesses, connection = checkImageConnection, ...options } = {}) {
22
- if (!["check", "repair", "open"].includes(operation)) throw new Error("Unknown image control");
23
- const summary = imageSetupSummary({ ...options, models });
24
- if (operation === "check") return { status: "checked", connection: await connection({ host, port }),
25
- launcher_present: fs.existsSync(imageHostLauncherPath(options)), runtime: state?.snapshot(), ...summary };
26
- if (!summary.enabled) throw new Error("Enable images before repairing image access");
27
- if (!integration) throw new Error("Start CCDX before repairing image access");
28
- const env = { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" };
29
- await integration.configure();
30
- const imageHost = await prepare({ ...options, env, host, port });
31
- if (!imageHost) return { status: "unsupported", prepared: false };
32
- const running = appProcesses(imageHost.app).length > 0;
33
- if (running) return { status: "needs_app_relaunch", prepared: true, runtime: state?.snapshot() };
34
- if (operation === "repair") return { status: "prepared", prepared: true, runtime: state?.snapshot() };
35
- // Share the established prediction launch route; never strip it during repair.
36
- const native = await integration.start();
37
- await native?.prepareRoute?.();
38
- const opened = await launch({ env, imageHost, predictionPacUrl: native?.pacUrl, predictionApp: native?.app,
39
- predictionProfile: native?.profile, preparePredictionRoute: () => native?.prepareRoute?.(),
40
- onPredictionRoute: value => integration.launched?.(value) });
41
- return { status: opened ? "opened_new_chat_required" : "open_failed", prepared: true, runtime: state?.snapshot() };
20
+ export async function controlImage(operation, { connection = checkImageConnection, readSummary = imageSetupSummary, ...options } = {}) {
21
+ if (!["check", "repair", "open", "focus", "restart"].includes(operation)) throw new Error("Unknown image control");
22
+ if (operation === "check") {
23
+ const checked = await controlCodexLaunch("check", { ...options, readSummary, intent: "image" });
24
+ const summary = readSummary({ ...options, models: options.models || [] });
25
+ return { status: "checked", connection: await connection({ host: options.host, port: options.port }),
26
+ launcher_present: fs.existsSync(imageHostLauncherPath(options)), runtime: options.state?.snapshot(), app: checked.app, ...summary };
27
+ }
28
+ return controlCodexLaunch(operation, { ...options, readSummary, intent: "image" });
42
29
  }
@@ -10,7 +10,9 @@ export function createImageHostState({ now = Date.now, alive = pid => { try { pr
10
10
  const previous = hosts.get(value.id);
11
11
  if (previous && previous.pid !== value.pid) throw new Error("Image host identity changed");
12
12
  const host = previous || { id: value.id, pid: value.pid, connected: false, threads: [] };
13
- if (value.event === "connected") host.connected = true;
13
+ // A later tool event also proves this host is live, including when CCDX
14
+ // restarted after the host's initial connection report.
15
+ if (["connected", "registered", "generated", "failed"].includes(value.event)) host.connected = true;
14
16
  if (value.event === "closed") host.connected = false;
15
17
  if (value.event === "registered" && value.thread && !host.threads.includes(value.thread)) host.threads = [...host.threads, value.thread].slice(-32);
16
18
  host.event = value.event;host.updated_at = now();
@@ -12,18 +12,21 @@ import { inspectAdapterCompatibility } from "./doctor-compat.mjs";
12
12
 
13
13
  export function createLocalTools({ home = os.homedir(), env = process.env, host = "127.0.0.1", port = 2026,
14
14
  platform = process.platform, collect = collectDoctorChecks, inspectConfig = inspectCodexConfig, repairConfig = repairCodexConfig,
15
- inspectNetwork = inspectPredictionEnvironment, inspectCompatibility = inspectAdapterCompatibility } = {}) {
15
+ inspectNetwork = inspectPredictionEnvironment, inspectCompatibility = inspectAdapterCompatibility, clientVersions } = {}) {
16
16
  const options = { home, env, host, port, platform };
17
17
  let last = null, flight = null;
18
18
  const safe = text => redactDiagnosticText(String(text || "")).split(home).join("~")
19
19
  .replace(/[\w.+-]+@[\w.-]+/g, "[account]").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 600);
20
20
  const project = checks => checks.slice(0, 80).map(check => ({ id: /^[a-z-]{1,60}$/.test(check.id || "") ? check.id : "local",
21
21
  kind: ["ok", "info", "warn", "err"].includes(check.kind) ? check.kind : "info", message: safe(check.message) }));
22
- function snapshot() { return { source: "local_tools", ...last }; }
22
+ function snapshot() { let versions = null;try { versions = clientVersions?.snapshot?.() || null; } catch {}return { source: "local_tools", ...last, ...(clientVersions ? { client_versions: versions } : {}) }; }
23
23
  async function check() {
24
24
  if (flight) return flight;
25
25
  flight = Promise.resolve().then(async () => {
26
- last = { checked_at: new Date().toISOString(), checks: project(await collect({ ...options, checkAdapter: false })) };
26
+ const versions = clientVersions?.refresh ? Promise.resolve().then(() => clientVersions.refresh()).catch(() => null) : null;
27
+ const checks = await collect({ ...options, checkAdapter: false });
28
+ await versions;
29
+ last = { checked_at: new Date().toISOString(), checks: project(checks) };
27
30
  return snapshot();
28
31
  }).finally(() => { flight = null; });
29
32
  return flight;
@@ -6,6 +6,7 @@ import { readAccessSettings } from "./access-settings.mjs";
6
6
  import { servicePreferences } from "./user-settings.mjs";
7
7
  import { observeRequestedModel, currentRequestContext } from "./request-context.mjs";
8
8
  import { recordResponsesUsage } from "./usage-store.mjs";
9
+ import { readSafeUpstreamReason } from "./safe-upstream-error.mjs";
9
10
 
10
11
  export const NATIVE_IMAGE_MODEL = DEFAULT_IMAGE_MODEL;
11
12
  export const IMAGE_MAX_BYTES = 32 * 1024 * 1024;
@@ -57,11 +58,11 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
57
58
  models = () => [], selection = () => readAccessSettings({ env, home }).clients.codex.image_model,
58
59
  requestBodyTimeoutMs = 120000, timeoutMs = 180000, enabled = () => servicePreferences({ env, home }).image_enabled,
59
60
  allowed = () => nativeImageAccess({ env, home }) } = {}) {
60
- let active = 0;
61
+ let active = 0, processing = 0;
61
62
  const metrics = { total: 0, succeeded: 0, failed: 0, busy: 0, cancelled: 0 };
62
63
  const handler = async (req, res, operation) => {
63
64
  const abort = createRequestAbort(req, res);
64
- let release = () => {}, admitted = false;
65
+ let release = () => {}, admitted = false, processingSlot = false;
65
66
  metrics.total++;
66
67
  try {
67
68
  if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers.host !== undefined && !isLoopbackHostHeader(req.headers.host)
@@ -69,8 +70,8 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
69
70
  if (String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase() !== "application/json") throw httpError("Images require application/json", 415);
70
71
  if (!allowed()) throw httpError("GitHub Copilot access is disabled for Codex", 403);
71
72
  if (!enabled()) throw httpError("Image requests are paused", 503);
72
- if (active >= 2) { metrics.busy++;throw httpError("Two image requests are already active", 503); }
73
- active++;admitted = true;
73
+ if (processing >= 2) { metrics.busy++;throw httpError("Two image requests are already active", 503); }
74
+ active++;processing++;admitted = true;processingSlot = true;
74
75
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
75
76
  release = await acquireRequest(req, { signal: abort.signal });
76
77
  const parsed = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: BODY_MAX_BYTES, maxDecodedBodyBytes: BODY_MAX_BYTES });
@@ -89,11 +90,15 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
89
90
  const response = await call({ input: body.prompt }, { signal: abort.signal });
90
91
  if (!response.ok) {
91
92
  metrics.failed++;
92
- await response.body?.cancel().catch(() => {});
93
+ // The upstream request has finished. Do not hold image concurrency or
94
+ // body admission while an optional error reason is read.
95
+ release();release = () => {};processing--;processingSlot = false;
96
+ const reason = await readSafeUpstreamReason(response, { signal: abort.signal });
93
97
  abort.signal.throwIfAborted();
94
98
  const code = `ccdx_images_http_${response.status}`, headers = new Headers(response.headers);
95
99
  headers.set("Content-Type", "application/json");
96
- sendUpstreamError(res, { status: response.status, headers }, JSON.stringify({ error: { type: "upstream_error", code, message: code } }));
100
+ sendUpstreamError(res, { status: response.status, headers }, JSON.stringify({ error: { type: "upstream_error", code,
101
+ message: reason?.message || code, ...(reason ? { upstream_code: reason.code } : {}) } }));
97
102
  return;
98
103
  }
99
104
  const text = await readBoundedResponseText(response, { maxBytes: RESPONSE_MAX_BYTES, signal: abort.signal, label: "Copilot image response" });
@@ -112,7 +117,7 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
112
117
  if (abort.reason === "client_closed" || abort.reason === "client_aborted") metrics.cancelled++;
113
118
  logRequestFailure("images", error, abort);
114
119
  sendJsonError(res, error, error.statusCode || 502);
115
- } finally { release();if (admitted) active--;abort.cleanup(); }
120
+ } finally { release();if (admitted) active--;if (processingSlot) processing--;abort.cleanup(); }
116
121
  };
117
122
  handler.stats = () => ({ ...metrics, active, native: true, model: imageModelSelection(models(), selection()).selected_model });
118
123
  return handler;
@@ -57,6 +57,14 @@ const WINDOWS_APP_SCRIPT = `$p=@(Get-AppxPackage -Name OpenAI.Codex | Where-Obje
57
57
  if($a.Count -ne 1){throw 'Unknown Windows App executable'};
58
58
  @{root=$p[0].InstallLocation;executable=$a[0].Executable;family=$p[0].PackageFamilyName} | ConvertTo-Json -Compress`;
59
59
 
60
+ export async function inspectWindowsCodexVersion({ env = process.env, exec = execFileAsync } = {}) {
61
+ const script = `$p=@(Get-AppxPackage -Name OpenAI.Codex | Where-Object { [int]$_.Status -eq 0 -and [int]$_.SignatureKind -eq 3 -and $_.Publisher -eq '${WINDOWS_PUBLISHER}' -and $_.PackageFamilyName -eq '${WINDOWS_PACKAGE_FAMILY}' });if($p.Count -ne 1){throw 'Unknown App registration'};[string]$p[0].Version`;
62
+ const [command, args] = powershellCommand(script, env);
63
+ const result = await exec(command, args, { encoding: "utf8", timeout: 2500, maxBuffer: 4096, env: windowsPowerShellEnvironment(env), windowsHide: true });
64
+ const version = String(result?.stdout ?? result).trim();
65
+ return /^\d+(?:\.\d+){1,3}$/.test(version) ? version : null;
66
+ }
67
+
60
68
  function registeredApp(raw) {
61
69
  let metadata;
62
70
  try { metadata = JSON.parse(raw); } catch { throw new Error("Could not read the registered Windows Codex App"); }
@@ -185,8 +185,9 @@ export function runtimeStatusPayload({
185
185
  last_request: observed ? {
186
186
  client_version: version(observed.client_version),
187
187
  application: ["ChatGPT.app", "Codex.app", "custom binary"].includes(observed.application) ? observed.application : null,
188
- source: observed.source === "bundled" ? "bundled" : "unavailable",
188
+ source: ["bundled", "cached_bundled"].includes(observed.source) ? observed.source : "unavailable",
189
189
  matched: observed.matched === true,
190
+ match_precision: ["exact", "core_only"].includes(observed.match_precision) ? observed.match_precision : null,
190
191
  observed_at: typeof observed.observed_at === "string" && /^\d{4}-\d{2}-\d{2}T[0-9:.]+Z$/.test(observed.observed_at) ? observed.observed_at : null,
191
192
  } : null,
192
193
  observed_versions: (Array.isArray(snapshot?.observed_versions) ? snapshot.observed_versions : []).filter(version).slice(0, 8),
@@ -114,12 +114,12 @@ function fragments(session, json, onRetained) {
114
114
 
115
115
  function rewrite(wire, event, named = false) {
116
116
  let written = false;
117
- const output = wire.split(/(?<=\n)/).map(line => {
117
+ const output = wire.split(/(?<=\n)|(?<=\r)(?!\n)/).map(line => {
118
118
  if (!line.startsWith("data:")) return line;
119
119
  if (written) return "";written = true;
120
- return "data: " + JSON.stringify(event) + (line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : "");
120
+ return "data: " + JSON.stringify(event) + (line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : line.endsWith("\r") ? "\r" : "");
121
121
  }).join("");
122
- return named && !/^event:/m.test(output) ? "event: " + event.type + "\n" + output : output;
122
+ return named && !/^event:/m.test(output) ? "event: " + event.type + (wire.match(/\r\n|\r|\n/)?.[0] || "\n") + output : output;
123
123
  }
124
124
 
125
125
  export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 1024, maxChannels = 1024 } = {}) {
@@ -184,7 +184,7 @@ export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 10
184
184
  forget(id);return output;
185
185
  }
186
186
  function transform(wire) {
187
- const lines = wire.split(/\r?\n/), data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
187
+ const lines = wire.split(/\r\n|\r|\n/), data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
188
188
  if (!data || data === "[DONE]") return wire;
189
189
  let event;
190
190
  try { event = JSON.parse(data); } catch { throw fail("stream_invalid"); }
@@ -269,8 +269,10 @@ export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 10
269
269
  pending += decoder.write(chunk);pendingBytes += chunk.length;
270
270
  if (pendingBytes > 8 * 1024 * 1024) throw fail("stream_limit");
271
271
  let output = "", match;
272
- while ((match = /\r?\n\r?\n/.exec(pending))) {
273
- const end = match.index + match[0].length, wire = pending.slice(0, end);pending = pending.slice(end);
272
+ while ((match = /(?:\r\n|\r(?!\n)|(?<!\r)\n){2}/.exec(pending))) {
273
+ const end = match.index + match[0].length;
274
+ if (end === pending.length && match[0].endsWith("\r") && match[0].includes("\n")) break;
275
+ const wire = pending.slice(0, end);pending = pending.slice(end);
274
276
  pendingBytes = Buffer.byteLength(pending);output += transform(wire);
275
277
  }
276
278
  return output;
@@ -278,7 +280,8 @@ export function createPrivacyStream(session, { maxBufferedBytes = 32 * 1024 * 10
278
280
  },
279
281
  finish() {
280
282
  try {
281
- pending += decoder.end();const output = pending ? transform(pending + "\n\n") : "";pending = "";
283
+ pending += decoder.end();const complete = /(?:\r\n|\r(?!\n)|(?<!\r)\n){2}$/.test(pending);
284
+ const output = pending ? transform(pending + (complete ? "" : "\n\n")) : "";pending = "";
282
285
  if (channels.size) throw fail("stream_incomplete");return output;
283
286
  } catch (error) { completed = false;throw error; }
284
287
  finally { clear();pending = "";pendingBytes = 0; }
@@ -19,7 +19,8 @@ export function createApiTokenCounter({ request, now = Date.now }) {
19
19
  const serialized = JSON.stringify(body), size = Buffer.byteLength(serialized), hash = size <= 1024 * 1024 ? createHash("sha256").update(scope).update(serialized).digest("hex") : null;
20
20
  const identity = hash || {};
21
21
  async function run(probe) {
22
- const key = probe ? "probe:" + scope : "body:" + hash, waiter = { start: options.onUpstreamStart, observe: options.onCountObservation, signal: options.signal, identity };
22
+ const key = probe ? "probe:" + scope : "body:" + hash, waiter = { start: options.onUpstreamStart, observe: options.onCountObservation,
23
+ errorHeaders: options.onUpstreamErrorHeaders, signal: options.signal, identity };
23
24
  let flight = flights.get(key);
24
25
  if (flight && [...flight.waiters].every(item => item.signal?.aborted)) { flights.delete(key);bytes -= flight.bytes;flight = null; }
25
26
  const joinable = (probe || hash !== null) && (Boolean(flight) || flights.size < 16 && (probe || bytes + size <= 4 * 1024 * 1024));
@@ -33,11 +34,20 @@ export function createApiTokenCounter({ request, now = Date.now }) {
33
34
  item.observe?.(item.identity === flight.identity ? { upstream: true, shared: flight.shared } : { waited: true });
34
35
  };
35
36
  if (flight.started) start(waiter);
37
+ if (flight.errorStatus && (flight.errorStatus === 404 || waiter.identity === flight.identity)) {
38
+ try { waiter.errorHeaders?.(flight.errorStatus); } catch {}
39
+ }
36
40
  const task = async signal => {
37
41
  try {
38
42
  if (signal?.aborted) throw signal.reason;
39
43
  const response = await request(body, { ...options, bodyText: serialized, signal, observeUpstream: false,
40
- onUpstreamStart() { flight.started = true;for (const item of flight.waiters) if (!item.signal?.aborted) start(item); } });
44
+ onUpstreamStart() { flight.started = true;for (const item of flight.waiters) if (!item.signal?.aborted) start(item); },
45
+ onUpstreamErrorHeaders(status) {
46
+ flight.errorStatus = status;
47
+ for (const item of flight.waiters) if (!item.signal?.aborted && (status === 404 || item.identity === flight.identity)) {
48
+ try { item.errorHeaders?.(status); } catch {}
49
+ }
50
+ } });
41
51
  if (signal?.aborted) { await response.body?.cancel();throw signal.reason; }
42
52
  if (response.status === 404) {
43
53
  await response.body?.cancel();observe(scope, 404);const result = missed();
@@ -10,6 +10,7 @@ import { markUpstreamHeaders } from "../stream-performance.mjs";
10
10
  import { createApiNetwork } from "./api-network.mjs";
11
11
  import { checkedApiKey } from "../api-secrets.mjs";
12
12
  import { transportErrorDetails } from "../operation-error.mjs";
13
+ import { readSafeUpstreamReason } from "../safe-upstream-error.mjs";
13
14
  import { resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
14
15
  import { apiModelMetadata } from "./api-model-metadata.mjs";
15
16
  import { markRequestObservation, markUpstreamStarted } from "../stream-performance.mjs";
@@ -85,11 +86,13 @@ export function createApiProvider({ config, secrets, env = process.env, platform
85
86
  const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
86
87
  if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
87
88
  if (!result.ok) {
88
- await result.body?.cancel();const code = `ccdx_api_http_${result.status}`;
89
+ try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Optional admission release cannot hide the upstream response. */ }
90
+ const reason = await readSafeUpstreamReason(result, { signal: options.signal });const code = `ccdx_api_http_${result.status}`;
89
91
  const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
90
92
  if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
91
93
  else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
92
- return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: code } }), { status: result.status, headers: safeHeaders });
94
+ return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: reason?.message || code,
95
+ ...(reason ? { upstream_code: reason.code } : {}) } }), { status: result.status, headers: safeHeaders });
93
96
  }
94
97
  return result;
95
98
  } catch (error) {
@@ -160,8 +163,10 @@ export function createApiProvider({ config, secrets, env = process.env, platform
160
163
  applyRequestPolicies() {},
161
164
  compatibility: { hasRetry: () => false, selectRetry: async () => null,
162
165
  async openResponse(context, upstream, options) {
163
- const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart });
164
- markUpstreamHeaders(resp.status);
166
+ let headersObserved = false;
167
+ const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart,
168
+ onUpstreamErrorHeaders(status) { headersObserved = true;markUpstreamHeaders(status);options.releaseRequest?.(context); } });
169
+ if (!headersObserved) markUpstreamHeaders(resp.status);
165
170
  // request() already discarded the vendor body and projected a safe error.
166
171
  if (!resp.ok) {
167
172
  const errorText = await readBoundedResponseText(resp, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, signal: options.signal, label: "API error response" });
@@ -2,6 +2,7 @@ import { boundedDiagnosticText, redactDiagnosticText } from "./diagnostic-text.m
2
2
  import { currentRequestContext } from "./request-context.mjs";
3
3
  import { isProviderId } from "./provider-metadata.mjs";
4
4
  import { transportErrorDetails } from "./operation-error.mjs";
5
+ import { safeUpstreamReason } from "./safe-upstream-error.mjs";
5
6
 
6
7
  const DEFAULT_RECENT_FAILURES = 10;
7
8
 
@@ -104,7 +105,7 @@ export function createResponseFailureDiagnostics({
104
105
  };
105
106
  }
106
107
 
107
- export function upstreamErrorEvidence(text, { includeMessage = false } = {}) {
108
+ export function upstreamErrorEvidence(text, { includeMessage = false, status = null } = {}) {
108
109
  const errorBody = !String(text || "").trim() ? "empty" : "unstructured";
109
110
  let error;
110
111
  try { const parsed = JSON.parse(text); error = parsed?.error; } catch {}
@@ -115,7 +116,10 @@ export function upstreamErrorEvidence(text, { includeMessage = false } = {}) {
115
116
  const param = typeof error.param === "string" && error.param.length <= 160
116
117
  && /^(?: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
118
  ? error.param : undefined;
119
+ const upstreamCode = (safeUpstreamReason(error.upstream_code, status) || safeUpstreamReason(error.code, status)
120
+ || safeUpstreamReason(error.type, status))?.code;
118
121
  return { error_body: "structured", code: technical(error.code), error_type: technical(error.type),
122
+ ...(upstreamCode ? { upstream_code: upstreamCode } : {}),
119
123
  parameter: param, ...(includeMessage && typeof error.message === "string" ? { diagnostic_message: safeFailureMessage(error.message) } : {}) };
120
124
  }
121
125
 
@@ -179,7 +183,7 @@ export function isDiscoveryRequest(method, pathname) {
179
183
  }
180
184
 
181
185
  export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers, model_error,
182
- error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
186
+ error_body, error_type, upstream_code, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
183
187
  application, reason, capability_cached, shared_upstream, transport }) {
184
188
  if (!reason && code === "ccdx_client_source_disabled" && upstream_attempts === 0 && origin !== "upstream_http") {
185
189
  reason = code;origin = "client_validation";
@@ -204,7 +208,8 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
204
208
  message: model_error ? "The model source reported an error; the original HTTP response was preserved." : message } }, model_error ? "model.error" : "http.error", { headers, provider });
205
209
  return { ...details, request_id: requestId, http_status: statusCode, route,
206
210
  origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
207
- ...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}), ...(parameter ? { parameter } : {}),
211
+ ...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}),
212
+ ...(safeUpstreamReason(upstream_code, statusCode) ? { upstream_code } : {}), ...(parameter ? { parameter } : {}),
208
213
  ...(diagnostic_message ? { diagnostic_message } : {}),
209
214
  ...(method ? { method } : {}), ...(target ? { target } : {}),
210
215
  ...(request_options ? { request_options } : {}),