codex-copilot-dx 1.3.16 → 1.3.18

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.
@@ -68,7 +68,7 @@
68
68
  async function api(body) {
69
69
  const response = await fetch("/_ccdx/ui/settings", { method: body ? "POST" : "GET", cache: "no-store",
70
70
  headers: { "X-CCDX-Dashboard": "1", ...(body ? { "Content-Type": "application/json" } : {}) },
71
- ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(body?.action === "prediction" ? 210000 : body?.action === "image" || body?.operation === "account" ? 65000 : 15000) });
71
+ ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout((body?.action === "prediction" || body?.action === "image" && body?.operation === "open") ? 210000 : body?.action === "image" || body?.operation === "account" ? 65000 : 15000) });
72
72
  const data = await response.json();if (!response.ok) throw Object.assign(new Error(data.error || `HTTP ${response.status}`), { code: data.code });return data;
73
73
  }
74
74
  const preferences = globalThis.ccdxDashboardPreferences?.create({ element: el, api, applied: applySettings, time,
@@ -198,7 +198,7 @@
198
198
  if (settingsPending) return;
199
199
  settingsPending = true;
200
200
  syncAccountControls();
201
- const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-enabled, #prediction-continue, #prediction-open, #prediction-setup, #prediction-remove, #image-models input, #decoded-limit, #decoded-limit-save, #decoded-limit-default, #install-update")];
201
+ const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-enabled, #prediction-continue, #prediction-open, #prediction-setup, #prediction-remove, #image-models input, #image-check, #image-repair, #image-open, #decoded-limit, #decoded-limit-save, #decoded-limit-default, #install-update")];
202
202
  controls.forEach(input => { input.disabled = true; });
203
203
  const note = el(body.action === "prediction" ? "prediction-action-note" : body.action === "image" ? "effect-image_enabled" : body.action === "update" ? "manual-update-note" : body.action === "decoded_limit" ? "decoded-limit-note" : body.action === "nightly_update" ? "nightly-state" : body.key ? `effect-${body.key}` : body.action === "color_theme" ? "terminal-color-note"
204
204
  : body.action.startsWith("history_") ? "effect-history" : body.action === "prediction_fix" ? "prediction-note"
@@ -1,6 +1,15 @@
1
1
  (() => {
2
2
  function create({ element: el, change, localize }) {
3
3
  let saved = null, limitDirty = false, imageSignature = "";
4
+ for (const operation of ["check", "repair", "open"]) el("image-" + operation).addEventListener("click", async () => {
5
+ const data = await change({ action: "image", operation }, el("image-" + operation));
6
+ const result = data?.last_operation?.feature === "image" ? data.last_operation.result : null;
7
+ if (result) {
8
+ el("image-action-note").dataset.operation = operation;
9
+ el("image-action-note").hidden = false;
10
+ localize(el("image-action-note"), operation === "check" ? "image_connection_" + result.connection?.state : "image_action_" + result.status);
11
+ }
12
+ });
4
13
  const prediction = operation => change({ action: "prediction", operation }, el("prediction-continue"));
5
14
  el("setting-prediction_enabled").addEventListener("change", () => void prediction(el("setting-prediction_enabled").checked ? "enable" : "disable"));
6
15
  el("prediction-continue").addEventListener("click", () => void prediction(saved?.features?.prediction?.enabled ? "enable" : "disable"));
@@ -31,7 +40,9 @@
31
40
  if (notes) localize(el("prediction-action-note"), !value ? "feature_unavailable" : value.status === "unavailable" ? "feature_read_failed" : pending ? "prediction_quit_continue" : value.enabled && value.bridge !== "running" ? "prediction_bridge_missing" : value.enabled ? "prediction_ready" : "prediction_disabled");
32
41
  el("effect-prediction_enabled").hidden = !pending;
33
42
  if (pending) localize(el("effect-prediction_enabled"), "feature_pending");
34
- const image = data.features?.image, signature = JSON.stringify(image || null);
43
+ const runtime = data.features?.image?.runtime;
44
+ localize(el("image-host-note"), runtime?.tool_registration === "observed" ? "image_host_registered" : runtime?.connected ? "image_host_connected" : "image_host_unconfirmed");
45
+ const image = data.features?.image, signature = JSON.stringify(image ? { ...image, runtime: undefined } : null);
35
46
  if (signature !== imageSignature) {
36
47
  imageSignature = signature;
37
48
  const list = el("image-models"), focus = list.contains(document.activeElement) ? document.activeElement.value : null;
@@ -92,6 +92,8 @@
92
92
  let tr = detailRows.get(id);
93
93
  if (!tr) { tr = entry("tr");for (let i = 0; i < 6; i++) tr.append(entry("td"));detailRows.set(id, tr); }
94
94
  const values = [appName(row.application), sourceName(row.provider), modelName(row.model), format(fresh ? status(row) : "flow_last_observed"), `${((row.elapsed_ms + Math.max(0, Date.now() - sampledAt)) / 1000).toFixed(1)} s`, row.upstream_attempts.toLocaleString()];
95
+ if (row.previous_request) values[3] += " · " + format("flow_previous_result", { reason: row.previous_request.stop_reason || row.previous_request.outcome || "—", seconds: (row.previous_request.elapsed_ms / 1000).toFixed(1) });
96
+ tr.title = row.session_id ? format("flow_session_previous", { session: row.session_id, reason: row.previous_request?.stop_reason || row.previous_request?.outcome || "—", seconds: row.previous_request ? (row.previous_request.elapsed_ms / 1000).toFixed(1) : "—" }) : format("flow_session_unknown");
95
97
  values.forEach((value, i) => { if (tr.children[i].textContent !== value) tr.children[i].textContent = value; });
96
98
  if (body.children[index] !== tr) body.insertBefore(tr, body.children[index] || null);
97
99
  }
@@ -189,6 +191,8 @@
189
191
  if (!parts.length || parts.some(part => !integer(part.active_total) || !Array.isArray(part.active_requests))) { unavailable();return; }
190
192
  const values = parts.flatMap(part => part.active_requests).slice(0, 128);
191
193
  rows = values.filter(row => row && typeof row.model === "string" && integer(row.upstream_attempts) && Number.isFinite(row.elapsed_ms) && row.elapsed_ms >= 0).map(row => ({
194
+ session_id: typeof row.session_id === "string" && /^[a-f0-9]{16}$/.test(row.session_id) ? row.session_id : null,
195
+ previous_request: row.previous_request && Number.isFinite(row.previous_request.elapsed_ms) ? { elapsed_ms: row.previous_request.elapsed_ms, stop_reason: row.previous_request.stop_reason, outcome: row.previous_request.outcome } : null,
192
196
  request_id: typeof row.request_id === "string" ? row.request_id.slice(0, 80) : null,
193
197
  application: clients.has(row.application) ? row.application : "api", provider: typeof row.provider === "string" && /^[a-z][a-z0-9_-]{0,63}$/.test(row.provider) ? row.provider : "unknown",
194
198
  model: row.model.slice(0, 160), phase: String(row.phase || "").slice(0, 40), elapsed_ms: row.elapsed_ms,
@@ -134,6 +134,9 @@
134
134
  <summary class="panel-heading"><h2 data-i18n="codex_image_generation">IMAGE GENERATION</h2></summary>
135
135
  <div class="setting-row"><label for="setting-image_enabled" data-i18n="allow_new_image_calls">Allow image requests</label><input id="setting-image_enabled" type="checkbox" role="switch" disabled><span id="effect-image_enabled" class="hint" role="status"></span></div>
136
136
  <div id="image-models" class="image-models" role="group" aria-label="Image model" data-i18n-label="image_model"></div>
137
+ <div class="section-actions"><button id="image-check" type="button" data-i18n="image_check">Check access</button><button id="image-repair" type="button" data-i18n="image_repair">Repair access</button><button id="image-open" type="button" data-i18n="image_open">Open Codex</button></div>
138
+ <p id="image-host-note" class="hint" role="status"></p>
139
+ <p id="image-action-note" class="hint" role="status" hidden></p>
137
140
  <p id="image-model-note" class="hint" role="status" hidden></p>
138
141
  <div class="image-metrics hint"><strong id="image">—</strong><span id="image-detail">—</span></div>
139
142
  </details>
@@ -7,6 +7,23 @@
7
7
  feature_continue: ["Continue setup", "继续配置"],
8
8
  prediction_open: ["Open Codex", "打开 Codex"],
9
9
  feature_remove: ["Remove setup", "移除接入"],
10
+ flow_previous_result: ["Previous: {reason}, {seconds} s", "上次:{reason},{seconds} 秒"],
11
+ flow_session_previous: ["Session {session} · previous: {reason}, {seconds} s", "会话 {session} · 上次请求:{reason},{seconds} 秒"],
12
+ flow_session_unknown: ["Session correlation unavailable", "无法关联会话"],
13
+ image_check: ["Check access", "检查接入"],
14
+ image_repair: ["Repair access", "修复接入"],
15
+ image_open: ["Open Codex", "打开 Codex"],
16
+ image_host_unconfirmed: ["App host connection unconfirmed.", "尚未确认 App 图片宿主连接。"],
17
+ image_host_connected: ["App host connected; new chat tool registration unconfirmed.", "App 宿主已连接;尚未确认新聊天工具注册。"],
18
+ image_host_registered: ["Image tool registration observed in a connected host. Other chats may differ.", "已在连接的宿主中观察到图片工具注册,其他聊天可能不同。"],
19
+ image_connection_verified: ["Local Node route verified. Codex network path unconfirmed.", "本机 Node 连接与服务身份已验证;Codex 网络路径尚未确认。"],
20
+ image_connection_unreachable: ["Local check could not reach CCDX.", "本机检查未能连接 CCDX。"],
21
+ image_connection_identity_mismatch: ["Local response did not match this CCDX check.", "本机响应身份不符合本次 CCDX 检查。"],
22
+ image_action_prepared: ["Launch configuration repaired. Open Codex, then use a new chat.", "启动配置已修复。请打开 Codex,再使用新聊天。"],
23
+ image_action_needs_app_relaunch: ["Launch configuration prepared. Quit Codex when your tasks finish, then open it here and use a new chat.", "启动配置已准备。请在任务完成后退出 Codex,再从这里打开并使用新聊天。"],
24
+ image_action_opened_new_chat_required: ["Codex launch requested. Use a new chat; registration remains unconfirmed until observed.", "已请求打开 Codex。请使用新聊天;观察到注册前仍显示未确认。"],
25
+ image_action_open_failed: ["Could not open Codex. Check the App installation.", "未能打开 Codex,请检查 App 安装。"],
26
+ image_action_unsupported: ["Native image host launch is unavailable on this platform.", "当前平台无法准备原生图片宿主启动。"],
10
27
  image_model: ["Image model", "图片模型"],
11
28
  image_models: ["Image models", "图片模型"],
12
29
  image_needs_github: ["Allow GitHub Copilot access for Codex.", "请允许 Codex 使用 GitHub Copilot。"],
@@ -0,0 +1,42 @@
1
+ import fs from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { adapterBaseUrl, ADAPTER_PROTOCOL_VERSION } from "./running-adapter.mjs";
4
+ import { imageHostLauncherPath, prepareImageHostLaunch } from "./codex-image-host-launch.mjs";
5
+ import { imageSetupSummary } from "./image-setup.mjs";
6
+ import { openCodex, macPredictionAppProcesses } from "./launcher.mjs";
7
+ import { readBoundedResponseText } from "./upstream-body.mjs";
8
+
9
+ export async function checkImageConnection({ host = "127.0.0.1", port = 2026, fetchImpl = fetch } = {}) {
10
+ const nonce = randomUUID();
11
+ try {
12
+ const response = await fetchImpl(adapterBaseUrl(host, port) + "/_ccdx/health?nonce=" + nonce,
13
+ { redirect: "error", headers: { Accept: "application/json" }, signal: AbortSignal.timeout(2000) });
14
+ const value = JSON.parse(await readBoundedResponseText(response, { maxBytes: 8192, label: "Local image check" }));
15
+ return { state: response.ok && value.name === "codex-copilot-dx" && value.ok === true && value.nonce === nonce
16
+ && value.protocol_version === ADAPTER_PROTOCOL_VERSION ? "verified" : "identity_mismatch", scope: "node_loopback", app_path: "unconfirmed" };
17
+ } catch { return { state: "unreachable", scope: "node_loopback", app_path: "unconfirmed" }; }
18
+ }
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() };
42
+ }
@@ -0,0 +1,26 @@
1
+ // Runtime evidence only. No prompts, image paths, credentials or raw chat IDs.
2
+ export function createImageHostState({ now = Date.now, alive = pid => { try { process.kill(pid, 0);return true; } catch { return false; } } } = {}) {
3
+ const hosts = new Map();
4
+ return {
5
+ report(value) {
6
+ if (!value || Object.keys(value).some(key => !["id", "pid", "event", "thread"].includes(key))
7
+ || !/^[a-f0-9-]{36}$/.test(value.id || "") || !Number.isSafeInteger(value.pid) || value.pid < 1
8
+ || !["connected", "registered", "generated", "failed", "closed"].includes(value.event)
9
+ || value.thread !== undefined && !/^[a-f0-9]{32}$/.test(value.thread)) throw new Error("Invalid image host evidence");
10
+ const previous = hosts.get(value.id);
11
+ if (previous && previous.pid !== value.pid) throw new Error("Image host identity changed");
12
+ const host = previous || { id: value.id, pid: value.pid, connected: false, threads: [] };
13
+ if (value.event === "connected") host.connected = true;
14
+ if (value.event === "closed") host.connected = false;
15
+ if (value.event === "registered" && value.thread && !host.threads.includes(value.thread)) host.threads = [...host.threads, value.thread].slice(-32);
16
+ host.event = value.event;host.updated_at = now();
17
+ hosts.delete(value.id);hosts.set(value.id, host);
18
+ if (hosts.size > 16) hosts.delete(hosts.keys().next().value);
19
+ },
20
+ snapshot() {
21
+ const values = [...hosts.values()].map(host => ({ ...host, threads: [...host.threads], connected: host.connected && alive(host.pid) }));
22
+ const connected = values.filter(host => host.connected);
23
+ return { connected: connected.length > 0, tool_registration: connected.some(host => host.threads.length) ? "observed" : "unconfirmed", hosts: values };
24
+ },
25
+ };
26
+ }
package/src/lock.mjs CHANGED
@@ -1,10 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
-
5
- function sleep(ms) {
6
- return new Promise((resolve) => setTimeout(resolve, ms));
7
- }
4
+ import { setTimeout as delay } from "node:timers/promises";
8
5
 
9
6
  // Synchronous configuration writers share the same cross-process lock format.
10
7
  // Readers never take the lock. A live lock is never stolen on timeout.
@@ -269,6 +266,7 @@ export async function withFileLock(lockPath, fn, {
269
266
  now = Date.now,
270
267
  fsImpl = fs,
271
268
  processAlive = processIsAlive,
269
+ signal,
272
270
  } = {}) {
273
271
  fs.mkdirSync(path.dirname(lockPath), { recursive: true });
274
272
  const started = now();
@@ -277,12 +275,13 @@ export async function withFileLock(lockPath, fn, {
277
275
  const guardPath = reclaimGuardPath(lockPath);
278
276
 
279
277
  while (fd === null) {
278
+ signal?.throwIfAborted();
280
279
  const beforeAcquire = now();
281
280
  if (lockPathExists(guardPath, fsImpl)) {
282
281
  maybeRemoveAbandonedGuard(guardPath, staleMs, beforeAcquire, fsImpl, processAlive);
283
282
  if (lockPathExists(guardPath, fsImpl)) {
284
283
  if (beforeAcquire - started >= timeoutMs) throw new Error(`Timed out waiting for lock: ${lockPath}`);
285
- await sleep(Math.min(pollMs, Math.max(1, timeoutMs - (beforeAcquire - started))));
284
+ await delay(Math.min(pollMs, Math.max(1, timeoutMs - (beforeAcquire - started))), undefined, { signal });
286
285
  continue;
287
286
  }
288
287
  }
@@ -306,11 +305,12 @@ export async function withFileLock(lockPath, fn, {
306
305
  if (nowMs - started >= timeoutMs) {
307
306
  throw new Error(`Timed out waiting for lock: ${lockPath}`);
308
307
  }
309
- await sleep(Math.min(pollMs, Math.max(1, timeoutMs - (nowMs - started))));
308
+ await delay(Math.min(pollMs, Math.max(1, timeoutMs - (nowMs - started))), undefined, { signal });
310
309
  }
311
310
  }
312
311
 
313
312
  try {
313
+ signal?.throwIfAborted();
314
314
  return await fn();
315
315
  } finally {
316
316
  try {
@@ -42,7 +42,9 @@ export function createManagementHandler({ statusSnapshot, activityEvents, native
42
42
  const predictionPac = isLoopbackAddress(req.socket?.remoteAddress) && isLoopbackHostHeader(req.headers?.host)
43
43
  ? options.nativePredictionPac?.() : null;
44
44
  const health = adapterHealthPayload();
45
+ const nonce = new URL(req.url, "http://localhost").searchParams.get("nonce");
45
46
  res.end(JSON.stringify({ ...health,
47
+ ...(/^[a-f0-9-]{36}$/.test(nonce || "") ? { nonce } : {}),
46
48
  capabilities: [...health.capabilities, ...(typeof options.fixPrediction === "function" ? [PREDICTION_FIX_CAPABILITY] : [])],
47
49
  ...(predictionPac ? { native_prediction_pac: predictionPac } : {}) }));
48
50
  return;
@@ -1,10 +1,10 @@
1
- import fs from "node:fs";
1
+ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { accessSettingsPath } from "./access-settings.mjs";
5
- import { readBoundedFileSync } from "./bounded-file.mjs";
6
- import { atomicWriteFilePairSync } from "./atomic-file.mjs";
7
- import { withFileLockSync } from "./lock.mjs";
5
+ import { readBoundedFile } from "./bounded-file.mjs";
6
+ import { atomicWriteFilePair } from "./atomic-file.mjs";
7
+ import { withFileLock } from "./lock.mjs";
8
8
 
9
9
  const grants = new WeakMap(), HASH = /^[a-f0-9]{64}$/, LIMIT = 1024;
10
10
  const digest = value => createHash("sha256").update(JSON.stringify(value, (key, entry) => key === "cache_control" ? undefined : entry)).digest("hex");
@@ -141,29 +141,29 @@ function project(body, count) {
141
141
  // fingerprints; it neither changes routing nor stores conversation contents.
142
142
  export function createMessagesHistoryTransfer(options = {}) {
143
143
  const file = messagesTransferPath(options), canonicalFile = path.join(path.dirname(file), "conversation-prefixes.json"), active = new Map();let records;
144
- function readFile(target, canonical = false) {
145
- try { return checkedRecords(JSON.parse(readBoundedFileSync(target, { encoding: "utf8", maxBytes: 512 * 1024 })), canonical); }
144
+ async function readFile(target, canonical = false) {
145
+ try { return checkedRecords(JSON.parse(await readBoundedFile(target, { encoding: "utf8", maxBytes: 512 * 1024 })), canonical); }
146
146
  catch (error) { if (error.code === "ENOENT") return {};invalidState(); }
147
147
  }
148
- function read() {
149
- const raw = readFile(file), canonical = readFile(canonicalFile, true);
148
+ async function read() {
149
+ const raw = await readFile(file), canonical = await readFile(canonicalFile, true);
150
150
  return Object.fromEntries(Object.entries(raw).map(([key, record]) => [key, { ...record,
151
151
  ...(canonical[key]?.owner === record.owner && canonical[key].raw_count === record.count && canonical[key].raw_prefix === record.prefix ? { canonical: canonical[key] } : {}) }]));
152
152
  }
153
- function save(key, record) {
154
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
155
- withFileLockSync(`${file}.lock`, () => {
156
- const next = read();delete next[key];next[key] = { ...record.raw, canonical: record.canonical };
153
+ async function save(key, record, signal) {
154
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
155
+ await withFileLock(`${file}.lock`, async () => {
156
+ const next = await read();delete next[key];next[key] = { ...record.raw, canonical: record.canonical };
157
157
  while (Object.keys(next).length > LIMIT) delete next[Object.keys(next)[0]];
158
158
  const raw = Object.fromEntries(Object.entries(next).map(([key, { canonical, ...value }]) => [key, value]));
159
159
  const canonical = Object.fromEntries(Object.entries(next).filter(([, value]) => value.canonical).map(([key, value]) => [key, value.canonical]));
160
160
  checkedRecords({ version: 1, records: raw });checkedRecords({ version: 1, records: canonical }, true);
161
- atomicWriteFilePairSync(file, JSON.stringify({ version: 1, records: raw }) + "\n", canonicalFile, JSON.stringify({ version: 1, records: canonical }) + "\n");records = next;
162
- });
161
+ await atomicWriteFilePair(file, JSON.stringify({ version: 1, records: raw }) + "\n", canonicalFile, JSON.stringify({ version: 1, records: canonical }) + "\n");records = next;
162
+ }, { timeoutMs: 1000, staleMs: 60_000, pollMs: 10, signal });
163
163
  }
164
- return { prepare({ key, owner, previousOwner, profile, body, countTokens = false, knownOwners = [] }) {
164
+ return { async prepare({ key, owner, previousOwner, profile, body, countTokens = false, knownOwners = [], signal }) {
165
165
  if (!Array.isArray(body?.messages) || body.input !== undefined) return null;
166
- records ||= read();const entry = records[key], changed = entry ? entry.owner !== owner : Boolean(previousOwner && previousOwner !== owner);
166
+ if (!records) records = await read();const entry = records[key], changed = entry ? entry.owner !== owner : Boolean(previousOwner && previousOwner !== owner);
167
167
  const initial = knownOwners.includes(entry?.owner || previousOwner);
168
168
  const hasHistory = history(body), noncommitting = countTokens || Boolean(changed || entry) && !hasHistory;
169
169
  const items = changed || entry ? canonicalItems(body.messages) : null;
@@ -175,17 +175,19 @@ export function createMessagesHistoryTransfer(options = {}) {
175
175
  }
176
176
  const grant = { profile, noncommitting: true, initial, active: true };grants.set(body, grant);
177
177
  const nextCheckpoint = countTokens ? null : checkpoint(owner, body.messages);
178
- let toolLease, committed = false;
179
- return { handled: true, commit(state) {
178
+ let toolLease, committed = false, released = false, committing;
179
+ return { handled: true, async commit(state) {
180
180
  // A no-history model probe must not pin the conversation. An actual
181
181
  // tool call must: its following results continue this very same turn.
182
- if (countTokens || !state?.tool || committed) return;
182
+ if (committing) return committing;
183
+ if (countTokens || !state?.tool || committed || released) return committed;
183
184
  const lease = active.get(key);
184
185
  if (lease && lease.owner !== owner) fail("ccdx_history_transfer_busy", "Wait for the current response to finish before switching sources.");
185
- save(key, nextCheckpoint);committed = true;
186
186
  toolLease = lease || { owner, count: 0 };toolLease.count++;active.set(key, toolLease);
187
+ committing = save(key, nextCheckpoint, signal).then(() => { committed = true;return true; });
188
+ return committing;
187
189
  }, release() {
188
- grant.active = false;if (toolLease && --toolLease.count === 0) active.delete(key);toolLease = null;
190
+ released = true;grant.active = false;if (toolLease && --toolLease.count === 0) active.delete(key);toolLease = null;
189
191
  } };
190
192
  }
191
193
  const lease = active.get(key);
@@ -205,12 +207,17 @@ export function createMessagesHistoryTransfer(options = {}) {
205
207
  removed = project(body, count);grant = { profile, noncommitting: false, initial, active: true };grants.set(body, grant);
206
208
  }
207
209
  const current = lease || { owner, count: 0 };current.count++;active.set(key, current);
208
- let released = false, committed = false;
209
- return { handled: Boolean(changed || entry), commit() {
210
- if (committed || released) return;
211
- if (candidate) save(key, candidate);
212
- committed = true;
213
- if (candidate && changed) options.onTransfer?.({ removed_thinking: removed });
210
+ let released = false, committed = false, committing;
211
+ return { handled: Boolean(changed || entry), async commit() {
212
+ if (committing) return committing;
213
+ if (committed || released) return committed;
214
+ committing = (async () => {
215
+ if (candidate) await save(key, candidate, signal);
216
+ committed = true;
217
+ if (candidate && changed) options.onTransfer?.({ removed_thinking: removed });
218
+ return true;
219
+ })();
220
+ return committing;
214
221
  }, release() {
215
222
  if (released) return;released = true;if (grant) grant.active = false;
216
223
  if (--current.count === 0) active.delete(key);
package/src/models.mjs CHANGED
@@ -14,7 +14,7 @@ export function autoReviewReasoningEfforts(model) {
14
14
 
15
15
  function hasOpenAIEndpoint(model) {
16
16
  const endpoints = Array.isArray(model?.supported_endpoints) ? model.supported_endpoints : [];
17
- return endpoints.includes("/responses") || endpoints.includes("/v1/responses") || endpoints.includes("/chat/completions");
17
+ return endpoints.includes("/responses") || endpoints.includes("/v1/responses") || (endpoints.includes("/chat/completions") || endpoints.includes("/v1/chat/completions"));
18
18
  }
19
19
 
20
20
  // Endpoint-based routing helpers. A model is "responses-only" when it exposes a
@@ -25,13 +25,13 @@ export function modelEndpoints(model) {
25
25
  }
26
26
 
27
27
  export function modelSupportsChatCompletions(model) {
28
- return modelEndpoints(model).includes("/chat/completions");
28
+ return modelEndpoints(model).some(path => ["/chat/completions", "/v1/chat/completions"].includes(path));
29
29
  }
30
30
 
31
31
  export function modelIsResponsesOnly(model) {
32
32
  const endpoints = modelEndpoints(model);
33
33
  const hasResponses = endpoints.includes("/responses") || endpoints.includes("/v1/responses");
34
- return hasResponses && !endpoints.includes("/chat/completions");
34
+ return hasResponses && !(endpoints.includes("/chat/completions") || endpoints.includes("/v1/chat/completions"));
35
35
  }
36
36
 
37
37
  export function resolveCopilotPriorityTierModel(model, serviceTier, models) {
@@ -87,7 +87,15 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
87
87
  const forward = input => client.images(operation, { ...body, prompt: input.input }, { signal: abort.signal });
88
88
  const call = privacy?.wrap ? privacy.wrap(forward, { res, protocol: "responses", client: "codex" }) : forward;
89
89
  const response = await call({ input: body.prompt }, { signal: abort.signal });
90
- if (!response.ok) { metrics.failed++;await sendUpstreamError(res, response, "images", { signal: abort.signal });return; }
90
+ if (!response.ok) {
91
+ metrics.failed++;
92
+ await response.body?.cancel().catch(() => {});
93
+ abort.signal.throwIfAborted();
94
+ const code = `ccdx_images_http_${response.status}`, headers = new Headers(response.headers);
95
+ headers.set("Content-Type", "application/json");
96
+ sendUpstreamError(res, { status: response.status, headers }, JSON.stringify({ error: { type: "upstream_error", code, message: code } }));
97
+ return;
98
+ }
91
99
  const text = await readBoundedResponseText(response, { maxBytes: RESPONSE_MAX_BYTES, signal: abort.signal, label: "Copilot image response" });
92
100
  let result;
93
101
  try { result = JSON.parse(text); } catch { throw httpError("Copilot returned invalid image JSON", 502); }
@@ -5,7 +5,7 @@ import { publicModelCatalog } from "../provider-metadata.mjs";
5
5
  import { resolveClaudeModel } from "../claude-models.mjs";
6
6
  import { prepareResponsesPayload } from "../image-optimization.mjs";
7
7
  import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
8
- import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
8
+ import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, MAX_UPSTREAM_ERROR_BODY_BYTES, readBoundedResponseText } from "../http-transport.mjs";
9
9
  import { markUpstreamHeaders } from "../stream-performance.mjs";
10
10
  import { createApiNetwork } from "./api-network.mjs";
11
11
  import { checkedApiKey } from "../api-secrets.mjs";
@@ -162,8 +162,11 @@ export function createApiProvider({ config, secrets, env = process.env, platform
162
162
  async openResponse(context, upstream, options) {
163
163
  const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart });
164
164
  markUpstreamHeaders(resp.status);
165
- // Upstream errors may echo its key; never forward its error body.
166
- if (!resp.ok) { await resp.body?.cancel();const code = `ccdx_api_http_${resp.status}`;return { resp: new Response(JSON.stringify({ error: { code, message: code } }), { status: resp.status, headers: { "Content-Type": "application/json" } }), reqContext: context, errorText: code, usedRetryPolicies: new Set() }; }
165
+ // request() already discarded the vendor body and projected a safe error.
166
+ if (!resp.ok) {
167
+ const errorText = await readBoundedResponseText(resp, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, signal: options.signal, label: "API error response" });
168
+ return { resp, reqContext: context, errorText, usedRetryPolicies: new Set() };
169
+ }
167
170
  return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
168
171
  } },
169
172
  close() { closed = true;lifetime.abort();network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
@@ -1,7 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
- import { m365Paths, readM365Json, writeM365Json, m365AccountKey } from "../m365-settings.mjs";
3
- import { withFileLockSync } from "../lock.mjs";
4
- import fs from "node:fs";
2
+ import { m365Paths, m365AccountKey } from "../m365-settings.mjs";
3
+ import { withFileLock } from "../lock.mjs";
4
+ import fs from "node:fs/promises";
5
+ import { readBoundedFile } from "../bounded-file.mjs";
6
+ import { atomicWriteFile } from "../atomic-file.mjs";
5
7
  import { messagesHistoryTransferGrant } from "../messages-history-transfer.mjs";
6
8
 
7
9
  const changed = () => Object.assign(new Error("This conversation belongs to another company account. Start a new conversation."),
@@ -12,6 +14,7 @@ export function createM365ConversationGuard({ home } = {}) {
12
14
  const { directory, conversations: file } = m365Paths({ home });
13
15
  let cached;
14
16
  return (account, body, headers = {}, options = {}) => {
17
+ options.signal?.throwIfAborted();
15
18
  const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
16
19
  let session = headers["session_id"] || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
17
20
  if (!session && typeof body.metadata?.user_id === "string") {
@@ -30,18 +33,28 @@ export function createM365ConversationGuard({ home } = {}) {
30
33
  if (noncommitting && !hasHistory) return;
31
34
  if (cached?.[key] === owner) return;
32
35
  if (cached?.[key] && cached[key] !== owner) throw changed();
33
- fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
34
- withFileLockSync(`${file}.lock`, () => {
35
- const saved = readM365Json(file, { owners: {} });
36
- if (!saved.owners || typeof saved.owners !== "object" || Array.isArray(saved.owners)
37
- || Object.keys(saved.owners).length > 1024 || Object.entries(saved.owners).some(([id, value]) => !/^[a-f0-9]{64}$/.test(id) || !/^[a-f0-9]{64}$/.test(value))) throw changed();
38
- const owners = saved.owners;
39
- if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory && !(authorized && grant.initial)) throw changed();
40
- if (noncommitting) return;
41
- if (owners[key]) { cached = owners;return; }
42
- owners[key] = owner;
43
- while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
44
- writeM365Json(file, { owners });cached = owners;
45
- });
36
+ return (async () => {
37
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
38
+ await withFileLock(`${file}.lock`, async () => {
39
+ let saved;
40
+ try {
41
+ if (!(await fs.lstat(file)).isFile()) throw Error("Expected a regular file");
42
+ saved = JSON.parse(await readBoundedFile(file, { encoding: "utf8", maxBytes: 4 * 1024 * 1024 }));
43
+ if (!saved || typeof saved !== "object" || Array.isArray(saved)) throw Error("Expected an object");
44
+ } catch (error) {
45
+ if (error.code === "ENOENT") saved = { owners: {} };
46
+ else throw Object.assign(new Error("M365 local configuration could not be read; existing files were preserved"), { code: "m365_config_invalid" });
47
+ }
48
+ if (!saved.owners || typeof saved.owners !== "object" || Array.isArray(saved.owners)
49
+ || Object.keys(saved.owners).length > 1024 || Object.entries(saved.owners).some(([id, value]) => !/^[a-f0-9]{64}$/.test(id) || !/^[a-f0-9]{64}$/.test(value))) throw changed();
50
+ const owners = saved.owners;
51
+ if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory && !(authorized && grant.initial)) throw changed();
52
+ if (noncommitting) return;
53
+ if (owners[key]) { cached = owners;return; }
54
+ owners[key] = owner;
55
+ while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
56
+ await atomicWriteFile(file, `${JSON.stringify({ owners }, null, 2)}\n`, { mode: 0o600, preserveMode: false });cached = owners;
57
+ }, { timeoutMs: 1000, staleMs: 60_000, pollMs: 10, signal: options.signal });
58
+ })();
46
59
  };
47
60
  }
@@ -207,7 +207,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
207
207
  cacheModelEndpoints() {},
208
208
  async responses(body, options = {}) {
209
209
  const model = selectedModel(body.model, "gpt");
210
- if (account) guardConversation(account, body, currentRequestContext()?.clientHeaders || options.headers);
210
+ if (account) { const admission = guardConversation(account, body, currentRequestContext()?.clientHeaders || options.headers, { signal: options.signal });if (admission?.then) await admission; }
211
211
  const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
212
212
  currentInputStart: options.currentInputStart || 0, signal: options.signal,
213
213
  profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
@@ -225,7 +225,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
225
225
  async messages(body, options = {}) {
226
226
  if (catalog && now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
227
227
  const model = selectedModel(body.model, "claude");
228
- if (account) guardConversation(account, body, options.headers, { profile: profile(), countTokens: options.countTokens === true });
228
+ if (account) { const admission = guardConversation(account, body, options.headers, { profile: profile(), countTokens: options.countTokens === true, signal: options.signal });if (admission?.then) await admission; }
229
229
  const efforts = modelReasoningEfforts(model);
230
230
  if (body.output_config?.effort !== undefined && efforts && !efforts.includes(body.output_config.effort)) {
231
231
  throw protocolError("m365_effort_unavailable", "The selected effort is not advertised by this model. Refresh its model list and select an available effort.");
@@ -45,6 +45,7 @@ function collectResponseImages(inputItems, currentInputStart, assertActive) {
45
45
  originalOutput: options.originalOutput,
46
46
  usesAnthropicParts: false,
47
47
  };
48
+ const before = refs.length;
48
49
  for (let partIndex = 0; partIndex < parts.length; partIndex += 1) {
49
50
  if ((partIndex & 63) === 0) assertActive?.();
50
51
  const identity = inlineImageIdentity(parts[partIndex]);
@@ -57,7 +58,7 @@ function collectResponseImages(inputItems, currentInputStart, assertActive) {
57
58
  identity,
58
59
  });
59
60
  }
60
- if (refs.some((ref) => ref.record === record)) records.push(record);
61
+ if (refs.length > before) records.push(record);
61
62
  };
62
63
 
63
64
  const historyBoundary = Math.min(Math.max(0, currentInputStart), inputItems.length);
@@ -218,7 +218,8 @@ export function createResponsesHandler(options) {
218
218
  autoReviewModelResolver = () => options.providerPreference?.(provider.id);
219
219
  if (provider.id !== "github") openAIModelEnv = { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" };
220
220
  }
221
- options.validateConversation?.(parsed, req.headers, provider);
221
+ const validation = options.validateConversation?.(parsed, req.headers, provider, abort.signal);
222
+ if (validation?.then) await validation;
222
223
  observeContextSession(parsed, req.headers, provider);
223
224
  activeDeadline = now() + upstreamTimeoutMs;
224
225
  activeTimeoutReason = "responses_prepare_timeout";
@@ -509,7 +510,8 @@ export function createResponsesCompactHandler(options) {
509
510
  autoReviewModelResolver = () => options.providerPreference?.(provider.id);
510
511
  if (provider.id !== "github") openAIModelEnv = { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" };
511
512
  }
512
- options.validateConversation?.(parsed, req.headers, provider);
513
+ const validation = options.validateConversation?.(parsed, req.headers, provider, abort.signal);
514
+ if (validation?.then) await validation;
513
515
  observeContextSession(parsed, req.headers, provider);
514
516
  activeDeadline = now() + upstreamTimeoutMs;
515
517
  activeTimeoutReason = "responses_prepare_timeout";
@@ -1,3 +1,5 @@
1
+ import { createImageHostState } from "./image-host-state.mjs";
2
+ import { controlImage } from "./image-control.mjs";
1
3
  import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
2
4
  writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
3
5
  nightlyUpdatePreference, writeNightlyUpdatePreference, decodedBodyLimitPreference, writeDecodedBodyLimitMib } from "./user-settings.mjs";
@@ -10,10 +12,11 @@ import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
10
12
 
11
13
  export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
12
14
  nightlyStatus = () => null, nightlyChanged = () => {},
13
- manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup,
15
+ manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage,
14
16
  adapterPort = 2026, adapterHost = "127.0.0.1",
15
17
  readImages = () => imageSetupSummary({ env, home }).configured, readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
16
18
  const options = { env, home };
19
+ const imageHostState = createImageHostState();
17
20
  let serial = Promise.resolve(), lastOperation = null, pending = 0;
18
21
  const featureSnapshot = read => { try { return read(options); } catch { return { status: "unavailable" }; } };
19
22
  function snapshot() {
@@ -25,7 +28,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
25
28
  const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
26
29
  const localPrivacy = providerRuntime?.privacy?.snapshot();
27
30
  return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
28
- features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image },
31
+ features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: { ...image, runtime: imageHostState.snapshot() } },
29
32
  decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
30
33
  nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
31
34
  effective: {
@@ -43,7 +46,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
43
46
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
44
47
  const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
45
48
  history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
46
- prediction: ["action", "operation"], image: ["action", "operation", "model"],
49
+ prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence"],
47
50
  update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
48
51
  preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
49
52
  provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
@@ -52,7 +55,9 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
52
55
  if (input.action === "prediction") {
53
56
  lastOperation = { feature: "prediction", result: await predictionControl(input.operation, { ...options, integration: clientIntegration }) };
54
57
  } else if (input.action === "image") {
55
- if (["pause", "resume"].includes(input.operation)) writeServicePreference("image_enabled", input.operation === "resume", options);
58
+ if (input.operation === "report") { imageHostState.report(input.evidence);terminal?.image?.(imageHostState.snapshot()); }
59
+ else if (["check", "repair", "open"].includes(input.operation)) lastOperation = { feature: "image", result: await imageHostControl(input.operation, { ...options, host: adapterHost, port: adapterPort, integration: clientIntegration, state: imageHostState, models: providerRuntime?.imageModels?.().models || [] }) };
60
+ else if (["pause", "resume"].includes(input.operation)) writeServicePreference("image_enabled", input.operation === "resume", options);
56
61
  else lastOperation = { feature: "image", result: await imageControl(input, { ...options, providerRuntime, adapterPort, adapterHost }) };
57
62
  } else if (input.action === "update") {
58
63
  if (input.confirmed !== true) throw new Error("Confirm installation and the idle service switch");