codex-copilot-dx 1.3.17 → 1.3.19

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.
@@ -0,0 +1,132 @@
1
+ import { prepareImageHostLaunch } from "./codex-image-host-launch.mjs";
2
+ import { imageSetupSummary } from "./image-setup.mjs";
3
+ import { openCodex } from "./launcher.mjs";
4
+ import { installedPredictionApp } from "./native-prediction-app.mjs";
5
+ import { inspectCodexApp, controlCodexApp } from "./codex-app-control.mjs";
6
+ import { predictionControlSnapshot } from "./prediction-control.mjs";
7
+ import { predictionPaths, readPredictionSettings, writePredictionSettings } from "./native-prediction-profile.mjs";
8
+ import { servicePreferences } from "./user-settings.mjs";
9
+ import { runPredictionOperation } from "./prediction-operations.mjs";
10
+ import { withFileLock } from "./lock.mjs";
11
+
12
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
13
+ const publicAppState = value => ({ status: value.status, ...(value.host ? { host: value.host } : {}),
14
+ ...(value.tool_registration ? { tool_registration: value.tool_registration } : {}),
15
+ ...(value.prediction_route ? { prediction_route: value.prediction_route } : {}),
16
+ ...(typeof value.needs_restart === "boolean" ? { needs_restart: value.needs_restart } : {}) });
17
+
18
+ async function applyPendingPrediction(options, nativeOperation) {
19
+ try {
20
+ if (!readPredictionSettings(options).displayPending) return true;
21
+ const enabled = servicePreferences(options).prediction_enabled;
22
+ const result = await nativeOperation("display", { ...options, enabled, requireClosed: true });
23
+ if (result?.pending !== false) return false;
24
+ return await withFileLock(`${predictionPaths(options).settings}.lock`, () => {
25
+ const current = readPredictionSettings(options);
26
+ if (!current.displayPending) return true;
27
+ if (servicePreferences(options).prediction_enabled !== enabled) return false;
28
+ writePredictionSettings({ ...current, displayPending: false }, options);return true;
29
+ });
30
+ } catch { return false; }
31
+ }
32
+
33
+ export async function controlCodexLaunch(operation, { intent = "image", integration, state, host, port, models = [],
34
+ prepare = prepareImageHostLaunch, launch = openCodex, readSummary = imageSetupSummary,
35
+ readPrediction = predictionControlSnapshot, nativeOperation = runPredictionOperation,
36
+ discover = installedPredictionApp, inspect = inspectCodexApp, appControl = controlCodexApp,
37
+ confirmed = false, wait = sleep, now = Date.now, quitTimeoutMs = 10000, ...options } = {}) {
38
+ if (!["check", "repair", "open", "focus", "restart"].includes(operation) || !["image", "prediction"].includes(intent)) throw new Error("Unknown Codex App control");
39
+ if (operation === "restart" && confirmed !== true) throw new Error("Confirm that restarting Codex can interrupt its running tasks");
40
+ const platform = options.platform || process.platform;
41
+ let image, prediction;
42
+ try { image = readSummary({ ...options, models }); }
43
+ catch { image = { enabled: servicePreferences(options).image_enabled, configured: false, selected_available: false, availability: "unavailable" }; }
44
+ try { prediction = readPrediction(options); }
45
+ catch { prediction = { enabled: false, configured: false, status: "unavailable" }; }
46
+ const runtime = () => state?.snapshot();
47
+ const inspectApp = async app => {
48
+ const current = await inspect(app, runtime()?.hosts || [], { ...options, predictionPacUrl: integration?.pacUrl?.() });
49
+ if (current.status === "running") {
50
+ const imagePending = image.enabled && image.configured && image.selected_available && current.host !== "connected";
51
+ const predictionPending = prediction.display_pending || prediction.configured && prediction.enabled && current.prediction_route !== "verified";
52
+ current.needs_restart = Boolean(imagePending || predictionPending);
53
+ }
54
+ return current;
55
+ };
56
+ if (operation === "check") {
57
+ let app = { status: platform === "darwin" ? "unknown" : "unsupported" };
58
+ if (platform === "darwin") try { app = await inspectApp((await discover(options)).app); } catch { /* Unknown is not stopped. */ }
59
+ return { status: "checked", app: publicAppState(app), prediction, image: { enabled: image.enabled, availability: image.availability } };
60
+ }
61
+ if (operation === "focus") {
62
+ if (platform !== "darwin") return { status: "unsupported", app: { status: "unsupported" } };
63
+ let app, current;
64
+ try { app = (await discover(options)).app;current = await inspectApp(app); }
65
+ catch { return { status: "app_check_failed", app: { status: "unknown" } }; }
66
+ if (current.status !== "running") return { status: "app_not_running", app: publicAppState(current) };
67
+ let result;
68
+ try { result = await appControl(app, current.pid, "activate", options); }
69
+ catch { return { status: "focus_unavailable", app: { status: "unknown" } }; }
70
+ return { status: result === "sent" ? "focused" : "focus_unavailable", app: result === "sent" ? publicAppState(current) : { status: "unknown" } };
71
+ }
72
+ if (!integration) throw new Error("Start CCDX before opening Codex from this control");
73
+ if (intent === "image" && !image.enabled) throw new Error("Enable images before repairing image access");
74
+ if (intent === "prediction" && !prediction.configured && !prediction.display_pending) throw new Error("Enable predictions before opening Codex");
75
+ const env = { ...(options.env || process.env), CCDX_AUTO_LAUNCH: "1" };
76
+ await integration.configure();
77
+ let imageHost = null, imagePrepFailed = false, imageWarning = intent === "prediction" && image.enabled && (!image.configured || !image.selected_available);
78
+ if (image.enabled) {
79
+ try { imageHost = await prepare({ ...options, env, host, port }); }
80
+ catch (error) { if (intent === "image") throw error;imageWarning = true;imagePrepFailed = true; }
81
+ if (!imageHost) { if (intent === "image") return { status: "unsupported", prepared: false };imageWarning = true;imagePrepFailed = true; }
82
+ }
83
+ let app = imageHost?.app;
84
+ if (!app) { try { app = (await discover(options)).app; } catch { return { status: "app_check_failed", prepared: false }; } }
85
+ let current;
86
+ try { current = await inspectApp(app); } catch { return { status: "app_check_failed", prepared: true }; }
87
+ if (current.status === "unsupported") return { status: "unsupported", prepared: true };
88
+ if (current.status === "multiple") return { status: "multiple_apps", prepared: true, app: publicAppState(current) };
89
+ if (!["running", "stopped"].includes(current.status)) return { status: "app_check_failed", prepared: true };
90
+ if (operation !== "restart" && current.status === "running") return { status: current.needs_restart ? "needs_app_relaunch" : "already_connected",
91
+ prepared: true, runtime: runtime(), app: publicAppState(current) };
92
+ if (operation === "repair") return { status: "prepared", prepared: true, runtime: runtime(), app: publicAppState(current) };
93
+ if (operation === "restart" && intent === "image" && (!image.configured || !image.selected_available)) return { status: "image_unavailable", prepared: true, app: publicAppState(current) };
94
+ if (operation === "restart" && current.status === "running" && !current.needs_restart) return { status: "already_connected", prepared: true, app: publicAppState(current) };
95
+ // Never lose a currently connected image host due to a failed preparation.
96
+ if (imagePrepFailed && current.status === "running" && current.host === "connected") return { status: "image_unavailable", prepared: true, app: publicAppState(current) };
97
+ const native = await integration.start();
98
+ if (prediction.status === "unavailable") return { status: "prediction_unavailable", prepared: true, app: publicAppState(current) };
99
+ if (!native && prediction.configured && prediction.enabled) return { status: "prediction_unavailable", prepared: true, app: publicAppState(current) };
100
+ await native?.prepareRoute?.();
101
+ if (native?.pacUrl && native.app && native.app !== app) return { status: "app_route_conflict", prepared: true };
102
+ if (operation === "restart") {
103
+ const previous = current;
104
+ try { current = await inspectApp(app); } catch { return { status: "app_check_failed", prepared: true }; }
105
+ if (current.status === "running" && !current.needs_restart) return { status: "already_connected", prepared: true, app: publicAppState(current) };
106
+ if (!["running", "stopped"].includes(current.status) || current.status === "running" && (previous.status !== "running" || current.pid !== previous.pid)) {
107
+ return { status: "app_changed", prepared: true, app: publicAppState(current) };
108
+ }
109
+ if (current.status === "running") {
110
+ const originalPid = current.pid;
111
+ let requested;
112
+ try { requested = await appControl(app, originalPid, "quit", options); }
113
+ catch { return { status: "quit_refused", prepared: true, app: publicAppState(current) }; }
114
+ if (!["sent", "absent"].includes(requested)) return { status: "quit_refused", prepared: true, app: publicAppState(current) };
115
+ const deadline = now() + quitTimeoutMs;
116
+ do {
117
+ try { current = await inspectApp(app); } catch { return { status: "app_check_failed", prepared: true }; }
118
+ if (current.status === "stopped") break;
119
+ if (current.status !== "running" || current.pid !== originalPid) return { status: "app_changed", prepared: true, app: publicAppState(current) };
120
+ if (now() >= deadline) return { status: "quit_timeout", prepared: true, app: publicAppState(current) };
121
+ await wait(Math.min(250, Math.max(1, deadline - now())));
122
+ } while (true);
123
+ }
124
+ }
125
+ const predictionReady = await applyPendingPrediction(options, nativeOperation);
126
+ const opened = await launch({ env, imageHost, predictionPacUrl: native?.pacUrl, predictionApp: native?.app,
127
+ predictionProfile: native?.profile, preparePredictionRoute: () => native?.prepareRoute?.(),
128
+ onPredictionRoute: value => integration.launched?.(value) });
129
+ return { status: opened ? !predictionReady || imageWarning ? "opened_with_pending" : "opened_new_chat_required" : "open_failed",
130
+ prepared: true, runtime: runtime(), app: { status: "unknown" }, ...(opened && !predictionReady ? { prediction_pending: true } : {}),
131
+ ...(opened && imageWarning ? { image_pending: true } : {}) };
132
+ }
@@ -658,7 +658,7 @@ export function createConnectionRuntime({
658
658
  if (!source) throw accessError("ccdx_api_not_ready", 503);
659
659
  return source;
660
660
  }
661
- function validateConversation(body, headers, source, client = "codex") {
661
+ function validateConversation(body, headers, source, signal, client = "codex") {
662
662
  if (!body || typeof body !== "object" || Array.isArray(body)) return;
663
663
  if (
664
664
  managed &&
@@ -683,7 +683,8 @@ export function createConnectionRuntime({
683
683
  body,
684
684
  headers,
685
685
  identities()[client],
686
- transfer
686
+ transfer,
687
+ signal
687
688
  );
688
689
  }
689
690
  }
@@ -1412,7 +1413,7 @@ export function createConnectionRuntime({
1412
1413
  }),
1413
1414
  }),
1414
1415
  },
1415
- codexCatalog: codexClientCatalog(compiled),
1416
+ codexCatalog: codexClientCatalog(compiled, () => getSource("github")?.registry?.models),
1416
1417
  };
1417
1418
  }
1418
1419
  if (Array.isArray(c.deployments) && compiled.defaultUnavailable) {
@@ -1509,7 +1510,7 @@ export function createConnectionRuntime({
1509
1510
  finish,
1510
1511
  };
1511
1512
  },
1512
- validateConversation: (body, headers, source) => validateConversation(body, headers, source, id),
1513
+ validateConversation: (body, headers, source, signal) => validateConversation(body, headers, source, signal, id),
1513
1514
  onRequest() {
1514
1515
  lastClients[id] = new Date().toISOString();
1515
1516
  },
@@ -1,15 +1,16 @@
1
- import fs from "node:fs";
1
+ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { createHmac } from "node:crypto";
4
4
  import { accessSettingsPath, accessError } from "./access-settings.mjs";
5
- import { readBoundedFileSync } from "./bounded-file.mjs";
6
- import { atomicWriteFileSync } from "./atomic-file.mjs";
7
- import { withFileLockSync } from "./lock.mjs";
5
+ import { readBoundedFile } from "./bounded-file.mjs";
6
+ import { atomicWriteFile } from "./atomic-file.mjs";
7
+ import { withFileLock } from "./lock.mjs";
8
8
 
9
9
  // Correlation only: retain hashes, never prompts, session IDs or credentials.
10
10
  export function createConversationSourceGuard(options = {}) {
11
11
  const file = path.join(path.dirname(accessSettingsPath(options)), "conversation-sources.json");let cache;
12
- return (client, profile, body, headers = {}, salt, transfer) => {
12
+ return (client, profile, body, headers = {}, salt, transfer, signal) => {
13
+ signal?.throwIfAborted();
13
14
  const hash = value => createHmac("sha256", salt).update(value).digest("hex");
14
15
  const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
15
16
  const hasHistory = Boolean(body.previous_response_id) || items.filter(item => item?.role === "user").length > 1
@@ -25,30 +26,33 @@ export function createConversationSourceGuard(options = {}) {
25
26
  const agent = headers["x-claude-code-agent-id"];
26
27
  const child = identified && ["claude_app", "claude_code"].includes(client) && typeof agent === "string" && /^[\w-]{1,128}$/.test(agent) ? `\0agent\0${agent}` : "";
27
28
  const key = hash(client + "\0" + input + child), owner = hash(profile);
28
- const prepare = previousOwner => transfer?.prepare({ key, owner, previousOwner, profile, body,
29
+ const prepare = previousOwner => transfer?.prepare({ key, owner, previousOwner, profile, body, signal,
29
30
  knownOwners: transfer.profiles?.map(hash) || [] });
30
- let prepared;
31
- if (cache?.[key]) {
32
- prepared = prepare(cache[key]);
33
- if (prepared?.handled || cache[key] === owner) return prepared;
34
- prepared?.release();
35
- if (identified || hasHistory) throw accessError("ccdx_conversation_source_changed", 409);
36
- }
37
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
38
- try { return withFileLockSync(`${file}.lock`, () => {
39
- let owners = {};
40
- try { owners = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 256 * 1024 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_conversation_state_invalid", 409); }
41
- if (!owners || typeof owners !== "object" || Array.isArray(owners) || Object.keys(owners).length > 1024
42
- || Object.entries(owners).some(([key, owner]) => !/^[a-f0-9]{64}$/.test(key) || !/^[a-f0-9]{64}$/.test(owner))) throw accessError("ccdx_conversation_state_invalid", 409);
43
- prepared = prepare(owners[key]);
44
- if (prepared?.handled) { cache = owners;return prepared; }
45
- if (owners[key] && owners[key] !== owner && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
46
- if (owners[key] !== owner) {
47
- owners[key] = owner;while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
48
- atomicWriteFileSync(file, JSON.stringify(owners) + "\n", { mode: 0o600 });
31
+ if (!transfer && cache?.[key] === owner) return;
32
+ return (async () => {
33
+ let prepared;
34
+ if (cache?.[key]) {
35
+ prepared = await prepare(cache[key]);
36
+ if (prepared?.handled || cache[key] === owner) return prepared;
37
+ prepared?.release();
38
+ if (identified || hasHistory) throw accessError("ccdx_conversation_source_changed", 409);
49
39
  }
50
- cache = owners;
51
- return prepared;
52
- }); } catch (error) { prepared?.release();throw error; }
40
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
41
+ try { return await withFileLock(`${file}.lock`, async () => {
42
+ let owners = {};
43
+ try { owners = JSON.parse(await readBoundedFile(file, { encoding: "utf8", maxBytes: 256 * 1024 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_conversation_state_invalid", 409); }
44
+ if (!owners || typeof owners !== "object" || Array.isArray(owners) || Object.keys(owners).length > 1024
45
+ || Object.entries(owners).some(([key, owner]) => !/^[a-f0-9]{64}$/.test(key) || !/^[a-f0-9]{64}$/.test(owner))) throw accessError("ccdx_conversation_state_invalid", 409);
46
+ prepared = await prepare(owners[key]);
47
+ if (prepared?.handled) { cache = owners;return prepared; }
48
+ if (owners[key] && owners[key] !== owner && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
49
+ if (owners[key] !== owner) {
50
+ owners[key] = owner;while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
51
+ await atomicWriteFile(file, JSON.stringify(owners) + "\n", { mode: 0o600 });
52
+ }
53
+ cache = owners;
54
+ return prepared;
55
+ }, { timeoutMs: 1000, staleMs: 60_000, pollMs: 10, signal }); } catch (error) { prepared?.release();throw error; }
56
+ })();
53
57
  };
54
58
  }
@@ -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" || body?.action === "image" && body?.operation === "open") ? 210000 : body?.action === "image" || body?.operation === "account" ? 65000 : 15000) });
71
+ ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout((body?.action === "prediction" || ["image", "codex_app"].includes(body?.action) && ["open", "restart"].includes(body?.operation)) ? 210000 : ["image", "codex_app"].includes(body?.action) || 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,
@@ -200,7 +200,7 @@
200
200
  syncAccountControls();
201
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
- 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"
203
+ const note = el(body.action === "codex_app" ? body.intent === "prediction" ? "prediction-action-note" : "image-action-note" : 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"
205
205
  : body.operation === "switch" ? "source-control-note" : body.operation === "auto-review" ? "review-control-note"
206
206
  : body.operation === "account" ? "m365-account-note" : "m365-control-note");
@@ -1,20 +1,63 @@
1
1
  (() => {
2
2
  function create({ element: el, change, localize }) {
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));
3
+ let saved = null, limitDirty = false, imageSignature = "", imageApp = { status: "unknown" }, appInspectionStarted = false;
4
+ function renderImageApp() {
5
+ const connected = imageApp.status === "running" && imageApp.host === "connected";
6
+ const restart = imageApp.status === "running" && (imageApp.needs_restart === true || saved?.features?.prediction?.display_pending === true);
7
+ const action = restart ? "image_restart" : imageApp.status === "running" ? "image_focus" : imageApp.status === "stopped" ? "image_open" : "image_inspect";
8
+ localize(el("image-open"), action);
9
+ localize(el("prediction-open"), imageApp.status === "unsupported" ? "prediction_open" : action);
10
+ el("image-restart-warning").hidden = !restart;
11
+ el("prediction-restart-warning").hidden = !restart;
12
+ localize(el("image-host-note"), imageApp.status === "stopped" ? "image_app_stopped" : imageApp.status === "multiple" ? "image_action_multiple_apps"
13
+ : connected ? imageApp.tool_registration === "observed" ? "image_host_registered" : "image_host_connected" : "image_host_unconfirmed");
14
+ }
15
+ async function codexAction(operation, intent, button, { quiet = false } = {}) {
16
+ const data = await change({ action: "codex_app", operation, intent, ...(operation === "restart" ? { confirmed: true } : {}) }, button);
17
+ const result = data?.last_operation?.feature === "codex_app" ? data.last_operation.result : null;
18
+ if (!result) return;
19
+ if (result.app) imageApp = result.app;
20
+ if (!quiet) {
21
+ const note = el(intent === "prediction" ? "prediction-action-note" : "image-action-note");
22
+ note.dataset.operation = operation;note.hidden = false;
23
+ const key = operation === "check" ? "codex_action_checked" : result.status === "opened_with_pending"
24
+ ? result.prediction_pending && result.image_pending ? "codex_action_both_pending" : result.prediction_pending ? "codex_action_prediction_pending" : "codex_action_image_pending"
25
+ : result.status === "already_connected" ? "codex_action_ready"
26
+ : result.status === "opened_new_chat_required" && intent === "prediction" ? "codex_action_opened" : "image_action_" + result.status;
27
+ localize(note, key);
28
+ }
29
+ renderImageApp();
30
+ }
31
+ async function imageAction(operation, button, { quiet = false } = {}) {
32
+ const data = await change({ action: "image", operation, ...(operation === "restart" ? { confirmed: true } : {}) }, button);
6
33
  const result = data?.last_operation?.feature === "image" ? data.last_operation.result : null;
7
34
  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);
35
+ if (result.app) imageApp = result.app;
36
+ if (!quiet) {
37
+ el("image-action-note").dataset.operation = operation;
38
+ el("image-action-note").hidden = false;
39
+ localize(el("image-action-note"), operation === "check" ? "image_connection_" + result.connection?.state : "image_action_" + result.status);
40
+ }
41
+ renderImageApp();
11
42
  }
43
+ }
44
+ el("image-check").addEventListener("click", () => void imageAction("check", el("image-check")));
45
+ el("image-repair").addEventListener("click", () => void imageAction("repair", el("image-repair")));
46
+ const appButton = (intent, button) => {
47
+ if (imageApp.status === "unsupported" && intent === "prediction") { void prediction("open");return; }
48
+ const operation = imageApp.status === "running" ? imageApp.needs_restart || saved?.features?.prediction?.display_pending ? "restart" : "focus"
49
+ : imageApp.status === "stopped" ? "open" : "check";
50
+ void codexAction(operation, intent, button);
51
+ };
52
+ el("image-open").addEventListener("click", () => appButton("image", el("image-open")));
53
+ el("additional-capabilities").addEventListener("toggle", () => {
54
+ if (el("additional-capabilities").open) void codexAction("check", "image", el("image-check"), { quiet: true });
12
55
  });
13
56
  const prediction = operation => change({ action: "prediction", operation }, el("prediction-continue"));
14
57
  el("setting-prediction_enabled").addEventListener("change", () => void prediction(el("setting-prediction_enabled").checked ? "enable" : "disable"));
15
58
  el("prediction-continue").addEventListener("click", () => void prediction(saved?.features?.prediction?.enabled ? "enable" : "disable"));
16
59
  el("fix-prediction").addEventListener("click", () => void prediction("repair"));
17
- el("prediction-open").addEventListener("click", () => void prediction("open"));
60
+ el("prediction-open").addEventListener("click", () => appButton("prediction", el("prediction-open")));
18
61
  el("prediction-setup").addEventListener("click", () => void prediction("setup"));
19
62
  el("prediction-remove").addEventListener("click", () => { if (window.confirm(globalThis.ccdxLanguage.format("prediction_remove_confirm"))) void prediction("remove"); });
20
63
  el("decoded-limit").addEventListener("input", () => { limitDirty = true; });
@@ -35,13 +78,12 @@
35
78
  el("setting-prediction_enabled").disabled = !value || value.status === "unavailable";
36
79
  const pending = value?.display_pending || value?.enabled && (!value.configured || value.display?.enabled === false);
37
80
  el("prediction-continue").hidden = !pending;
38
- el("prediction-open").disabled = !value?.configured;
81
+ el("prediction-open").disabled = !value?.configured && !value?.display_pending;
39
82
  el("prediction-remove").disabled = !value?.configured;
40
83
  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");
41
84
  el("effect-prediction_enabled").hidden = !pending;
42
85
  if (pending) localize(el("effect-prediction_enabled"), "feature_pending");
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");
86
+ renderImageApp();
45
87
  const image = data.features?.image, signature = JSON.stringify(image ? { ...image, runtime: undefined } : null);
46
88
  if (signature !== imageSignature) {
47
89
  imageSignature = signature;
@@ -68,6 +110,9 @@
68
110
  el("install-update").disabled = !data.manual_update?.available;
69
111
  const update = data.nightly_update;
70
112
  if (notes) localize(el("manual-update-note"), !data.manual_update?.available ? "update_external_launch" : update?.manual ? `manual_update_${update.phase}` : "update_idle_switch");
113
+ if (!appInspectionStarted && el("prediction-open").closest('[data-view="codex"]')?.hidden === false) {
114
+ appInspectionStarted = true;setTimeout(() => void codexAction("check", "prediction", el("prediction-open"), { quiet: true }), 0);
115
+ }
71
116
  }
72
117
  return { render };
73
118
  }
@@ -122,6 +122,7 @@
122
122
  <summary class="panel-heading"><h2 data-i18n="codex_input_predictions">INPUT SUGGESTIONS</h2></summary>
123
123
  <div class="setting-row"><label for="setting-prediction_enabled" data-i18n="predictions_enable">Input suggestions</label><input id="setting-prediction_enabled" type="checkbox" role="switch" disabled><span id="effect-prediction_enabled" class="hint" role="status"></span></div>
124
124
  <p id="prediction-action-note" class="hint" role="status"></p><div class="section-actions"><button id="prediction-continue" type="button" data-i18n="feature_continue" hidden>Continue setup</button><button id="prediction-open" type="button" data-i18n="prediction_open">Open Codex</button></div>
125
+ <p id="prediction-restart-warning" class="hint" role="status" data-i18n="image_restart_warning" hidden>Restarting Codex interrupts its running tasks. Finish or save them first.</p>
125
126
  <details class="tool-details"><summary data-i18n="status_and_repair">Status and repair</summary>
126
127
  <dl class="stats"><div><dt data-i18n="prediction_integration_setup">Suggestion setup</dt><dd id="prediction-preference">—</dd></div><div><dt data-i18n="local_bridge">Local service</dt><dd id="prediction-bridge">—</dd></div><div><dt data-i18n="client_route">App settings requests</dt><dd id="prediction-route">—</dd></div><div><dt data-i18n="visible_candidate">Suggestion displayed</dt><dd id="prediction-candidate">—</dd></div></dl>
127
128
  <p id="prediction-note" class="hint">—</p>
@@ -135,6 +136,7 @@
135
136
  <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
137
  <div id="image-models" class="image-models" role="group" aria-label="Image model" data-i18n-label="image_model"></div>
137
138
  <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>
139
+ <p id="image-restart-warning" class="hint" role="status" data-i18n="image_restart_warning" hidden>Restarting Codex interrupts its running tasks. Finish or save them first.</p>
138
140
  <p id="image-host-note" class="hint" role="status"></p>
139
141
  <p id="image-action-note" class="hint" role="status" hidden></p>
140
142
  <p id="image-model-note" class="hint" role="status" hidden></p>
@@ -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。"],
@@ -93,6 +116,10 @@
93
116
  "issue_brief": ["{cause} · {model} · {time}", "{cause} · {model} · {time}"],
94
117
  "issue_count_unavailable": ["Token counting unavailable", "令牌计数接口不可用"],
95
118
  "issue_source_limit": ["Source usage limit reached", "模型来源用量受限"],
119
+ "issue_source_quota": ["Source credits or quota exhausted", "模型来源余额或配额不足"],
120
+ "issue_source_rate": ["Source request rate limited", "模型来源请求频率受限"],
121
+ "issue_context_limit": ["Source reports context too long", "模型来源报告上下文过长"],
122
+ "issue_content_policy": ["Source content policy rejected the request", "模型来源内容策略拒绝了请求"],
96
123
  "issue_catalog_unavailable": ["Model catalog could not be read", "模型目录读取失败"],
97
124
  "issue_model_not_selected": ["Model not selected for this app", "应用尚未选用此模型"],
98
125
  "issue_access_denied": ["Access was denied", "请求被拒绝访问"],
@@ -989,6 +1016,7 @@
989
1016
  "message": ["Error details", "错误详情"],
990
1017
  "response_id": ["Response ID", "回答编号"],
991
1018
  "upstream_request_id": ["Source request ID", "来源编号"],
1019
+ "upstream_code": ["Source error code", "来源错误码"],
992
1020
  "request_id": ["CCDX request ID", "本机编号"],
993
1021
  "outcome_25a63": ["Result", "处理结果"],
994
1022
  "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,
@@ -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();
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 {