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.
package/README.md CHANGED
@@ -60,6 +60,8 @@ Use `ccdx help` or `ccdx <command> --help` for options. The CLI uses English; th
60
60
 
61
61
  ## Features and maintenance
62
62
 
63
+ Start CCDX to open Codex with native image tools, then use a new chat. If image access is missing, use the Web UI image checks or `ccdx app codex image check`, `repair` and `open`. Running Apps are never forcibly restarted.
64
+
63
65
  Use the Web UI for accounts, APIs, models, client access, input suggestions, native images, local masking, appearance, diagnostics and updates. CLI commands remain available for automation and recovery. See the [control reference](docs/REFERENCE.md#webui-and-cli-controls).
64
66
 
65
67
  - **Input suggestions:** new integrations attempt setup by default when Codex is closed. Saved off choices are retained. The Web UI can enable, disable, finish setup, open Codex and repair the bridge. Setup synchronizes Show predictions, adds App-profile trust and locally decrypts the prediction hosts' HTTPS traffic. App/thread eligibility still applies. [Details](docs/REFERENCE.md#optional-native-predictions).
@@ -1110,3 +1110,17 @@ The 1.3.13 native helper groups uncached short CPU sequences under the existing
1110
1110
  Claude App 3.x and 4.x share the inspected effort-capable adapter. Later unknown major versions retain conservative routes and preserve existing shared capability settings. Contiguous effort declarations select the source-qualified reasoning route; a gapped declaration with at least two lower contiguous levels can expose that safe prefix with an App maximum cap, while retaining the complete upstream declaration and reporting the hidden levels as limited. Prior route spellings remain accepted for existing conversations. Resynchronization carries long-context preference and model order between the two known source-qualified spellings, and replaces only owned shared capability fields. No undeclared effort is added. The sidebar brand places its shared atom icon and text in one grid row so the intro icon's two-row span cannot offset the label.
1111
1111
 
1112
1112
  Usage presentation maps configured api_ identifiers to current provider labels after aggregation. Rows, chart filters and historical statistics keep their original keys. Provider-label changes refresh only the table/model labels, preserving the selected raw model key, day and existing chart nodes. The native capability replay disables usage persistence and gives its process a temporary usage path; no production filter recognizes test model names or response IDs.
1113
+
1114
+ ## Native image recovery and request correlation (1.3.17)
1115
+
1116
+ `image-control.mjs` owns explicit check/repair/open operations for WebUI and terminal commands, reusing client configuration, host preparation and the existing prediction-aware launcher. Repair cannot kill an App or start another service. `image-host-state.mjs` retains bounded, process-local host evidence; the stdio bridge reports initialization and successful new-thread registration through the protected same-origin settings channel without blocking model traffic. Reporter work is bounded and aborted when the original CLI exits. Runtime evidence never contains prompts, images, paths or raw chat identifiers and cannot establish registration in unobserved chats. Manual loopback checks echo a nonce and explicitly identify their Node-only scope.
1117
+
1118
+ The existing salted session observation is projected into request metadata. Active requests can reference the previous retained request from the same anonymous session, application and provider; this does not change request routing, history or tool caches. Chat endpoint recognition accepts both `/chat/completions` and `/v1/chat/completions`. Bare JSON error lines in a Messages event stream terminate with an explicit protocol diagnostic rather than waiting for message_stop; normal SSE frames retain their bytes.
1119
+
1120
+ ## Boundary reliability (1.3.18)
1121
+
1122
+ Native image failures cancel the vendor response and project safe JSON; API Responses compatibility consumes the existing sanitized error once and retains its metadata. Image history collection records whether the current container appended references instead of rescanning previous containers.
1123
+
1124
+ The stdio host uses a paused-source line pump only while a destination is blocked or a frame requires asynchronous work. Passthrough stays synchronous. Both directions serialize destination writes; output batching is bounded by the destination high-water mark plus one complete frame. Child close, input cancellation and stdout drain are coordinated before removing listeners. Host-tool registration, image return items, account/approval traffic and App launch ownership are unchanged.
1125
+
1126
+ `bounded-file.mjs` and `atomic-file.mjs` provide asynchronous bounded reads and durable single/paired writes for request-path state. Other synchronous configuration callers retain their APIs. Conversation admission and company-account guards use abortable asynchronous lock waiting with their prior timeout/stale policy. Messages transfer plans reserve in-process ownership while committing; primary and marker writes retain rollback behavior. JSON/SSE delivery awaits the applicable commit, and settled source checks keep a synchronous cached path. No new cache, file format or provider-selection policy is introduced.
package/docs/REFERENCE.md CHANGED
@@ -578,18 +578,33 @@ unknown candidate-visibility value. A successful recovery only means the bridge
578
578
  was recreated on the original address, not that gray text appeared.
579
579
 
580
580
 
581
+ ## Error delivery and conversation commits
582
+
583
+ Image upstream HTTP errors return safe JSON with a `ccdx_images_http_<status>` code, the original status and allowlisted response metadata. Vendor error bodies are cancelled rather than forwarded. Custom API Responses reuse the provider's already-sanitized JSON and validated Retry-After in both streaming and non-streaming requests; these changes do not introduce retries.
584
+
585
+ Conversation-source admission and Messages checkpoint commits wait asynchronously for the existing cross-process locks. Cancellation ends lock waits. Checkpoint writes retain the primary/marker ordering and rollback behavior; the gateway awaits a successful commit before forwarding corresponding usable JSON or SSE output. Cached source checks keep their synchronous fast path. CLI configuration writers retain their existing synchronous behavior.
586
+
581
587
  ## Native image generation
582
588
 
583
- Codex’s built-in `image_gen.imagegen` tool uses the current CCDX address for separate Images API requests. CCDX serves `POST /v1/images/generations` and `POST /v1/images/edits`, reuses the existing GitHub Copilot authentication, and maps the native client’s `gpt-image-2` request to the selected available GHC image model. GPT Image 2.5 Flare is the default when advertised. The `X-CCDX-Image-Model` response header identifies the actual model. Image usage counts toward the GitHub account’s image credits; organization model policies still apply. The image model does not replace the selected conversation model.
589
+ The native image host uses the current CCDX address for separate Images API requests. CCDX serves `POST /v1/images/generations` and `POST /v1/images/edits`, reuses the existing GitHub Copilot authentication, and maps the native client’s `gpt-image-2` request to the selected available GHC image model. GPT Image 2.5 Flare is the default when advertised. The `X-CCDX-Image-Model` response header identifies the actual model. Image usage counts toward the GitHub account’s image credits; organization model policies still apply. The image model does not replace the selected conversation model.
584
590
 
585
591
  On macOS with Codex 0.166 or later, CCDX launches the unchanged Codex CLI through a local stdio host adapter. The adapter registers `ccdx_images.imagegen` using Codex’s native `dynamicTools` interface. Codex emits native tool progress and includes image content in the chat history; display in the signed App depends on the client and requires a real-window check. CCDX saves image files under the active Codex home’s `generated_images/ccdx/` directory and uses these files for later edits, including after a host restart. No separate image address or key, image MCP registration, or CCDX image skill is required. Windows continues to expose the Images API; automatic host activation on Windows is not yet provided.
586
592
 
593
+ The Web UI image panel and terminal `check`, `repair`, and `open` controls share the service's image controller. `check` verifies the Node loopback response with a fresh nonce and checks the launcher and runtime evidence; it does not prove the Codex App's proxy route. `repair` prepares owned launch files and client configuration without opening or closing the App. `open` preserves the established prediction route and opens Codex only when it is closed. A running App produces `needs_app_relaunch`; finish tasks and quit it yourself, then use `open` and a new chat. Disabled image settings and custom launch routes are preserved.
594
+
595
+ The stdio host pauses each input source when its destination is blocked or an asynchronous frame operation is pending. Ordinary frames retain their synchronous path and original wire text; output batching follows the destination high-water mark. Shutdown waits for child close and queued stdout delivery, including a final frame without a newline. No arbitrary new protocol-frame byte limit is imposed.
596
+
597
+ The runtime separately reports host initialization, accepted new-chat registration and image-call outcomes. Reports contain only host PID, anonymous host/chat identifiers, event type and time, remain in bounded process memory, and are not an automatic image-generation probe. Registration evidence applies to observed chats, not every existing conversation. Dead host processes are unconfirmed. The TUI exposes the repair command; terminal image status includes the same host state. Request details show anonymous session correlation and the previous retained request's outcome when supplied session metadata allows it; missing identity stays unassigned.
598
+
587
599
  The adapter uses `CODEX_CLI_PATH` only for the App launch requested by CCDX. It does not modify App binaries, ChatGPT authentication files, credential storage mode or account-plan declarations. All other app-server traffic, including Apps and approval requests, passes through to the original CLI. Existing custom CLI routes and unowned launcher files are preserved. A running App retains its existing launch environment. If its image tool is missing, fully quit the App, start Codex through CCDX, and use a new chat. CCDX does not forcibly restart the App. Native built-in image tool availability still depends on the installed client and thread. A successful direct API request alone does not establish visible App behavior.
588
600
 
589
601
  The WebUI’s image switch is on by default and pauses or resumes new requests. A previously saved off choice is preserved. Available GHC image models appear below the switch; multiple models use one radio selection. The same image purpose appears in Model sources and Codex model configuration. Image models stay out of Codex’s conversation-model picker and conversation default selection. Saved pause choices survive upgrades, and active calls may finish. The CLI uses the same preference:
590
602
 
591
603
  ```bash
592
604
  ccdx app codex image status
605
+ ccdx app codex image check
606
+ ccdx app codex image repair
607
+ ccdx app codex image open
593
608
  ccdx app codex image models
594
609
  ccdx app codex image select --id gpt-image-2.5-flare
595
610
  ccdx app codex image enable
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.16",
3
+ "version": "1.3.18",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -135,3 +135,45 @@ export function atomicWriteFileIfChangedSync(filePath, data, options = {}) {
135
135
  atomicWriteFileSync(filePath, data, options);
136
136
  return true;
137
137
  }
138
+
139
+ export async function atomicWriteFile(filePath, data, { mode = 0o600, preserveMode = true } = {}) {
140
+ const io = fs.promises, directory = path.dirname(filePath);
141
+ let finalMode = mode;
142
+ if (preserveMode) { try { finalMode = (await io.stat(filePath)).mode & 0o777; } catch (error) { if (error.code !== "ENOENT") throw error; } }
143
+ await io.mkdir(directory, { recursive: true, mode: 0o700 });
144
+ const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`);
145
+ let file;
146
+ try {
147
+ file = await io.open(tempPath, "wx", finalMode);await file.writeFile(data);await file.sync();await file.close();file = null;
148
+ await io.rename(tempPath, filePath);await io.chmod(filePath, finalMode);
149
+ if (process.platform !== "win32") {
150
+ let dir;
151
+ try { dir = await io.open(directory, "r");await dir.sync(); }
152
+ catch (error) { if (!["EINVAL", "ENOTSUP", "EBADF"].includes(error.code)) throw error; }
153
+ finally { await dir?.close(); }
154
+ }
155
+ } finally {
156
+ await file?.close();
157
+ try { await io.unlink(tempPath); } catch (error) { if (error.code !== "ENOENT") throw error; }
158
+ }
159
+ }
160
+
161
+ export async function atomicWriteFilePair(primaryPath, primaryData, secondaryPath, secondaryData, { mode = 0o600, writeFile = atomicWriteFile, unlinkFile = file => fs.promises.unlink(file) } = {}) {
162
+ const snapshot = async file => {
163
+ try { return { data: await fs.promises.readFile(file), mode: (await fs.promises.stat(file)).mode & 0o777 }; }
164
+ catch (error) { if (error.code === "ENOENT") return null;throw error; }
165
+ };
166
+ const remove = async file => { try { await unlinkFile(file); } catch (error) { if (error.code !== "ENOENT") throw error; } };
167
+ const write = (file, data, mode) => writeFile(file, data, { mode, preserveMode: false });
168
+ const before = [await snapshot(primaryPath), await snapshot(secondaryPath)];
169
+ try {
170
+ await write(primaryPath, primaryData, mode);
171
+ if (secondaryData === null) await remove(secondaryPath);else await write(secondaryPath, secondaryData, mode);
172
+ } catch (error) {
173
+ for (const [file, saved] of [[primaryPath, before[0]], [secondaryPath, before[1]]]) {
174
+ try { if (saved) await write(file, saved.data, saved.mode);else await remove(file); }
175
+ catch (cause) { error.rollbackError ||= cause; }
176
+ }
177
+ throw error;
178
+ }
179
+ }
@@ -26,3 +26,19 @@ export function readBoundedFileSync(filePath, { maxBytes = MAX_SETTINGS_FILE_BYT
26
26
  return encoding ? value.toString(encoding) : value;
27
27
  } finally { fs.closeSync(fd); }
28
28
  }
29
+
30
+ export async function readBoundedFile(filePath, { maxBytes = MAX_SETTINGS_FILE_BYTES, encoding } = {}) {
31
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError("Invalid local file byte limit");
32
+ const file = await fs.promises.open(filePath, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0));
33
+ try {
34
+ const stat = await file.stat();
35
+ if (!stat.isFile() || stat.size > maxBytes) throw Object.assign(new Error("Local configuration file exceeds its read limit or is not a regular file"), { code: "ccdx_local_file_limit" });
36
+ const buffer = Buffer.alloc(stat.size + 1);let size = 0;
37
+ while (size < buffer.length) {
38
+ const { bytesRead } = await file.read(buffer, size, buffer.length - size, size);
39
+ if (!bytesRead) break;size += bytesRead;
40
+ }
41
+ if (size > stat.size) throw Object.assign(new Error("Local configuration file grew during reading; retry after the write finishes"), { code: "ccdx_local_file_changed" });
42
+ const value = buffer.subarray(0, size);return encoding ? value.toString(encoding) : value;
43
+ } finally { await file.close(); }
44
+ }
@@ -75,6 +75,13 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
75
75
  }
76
76
  if (value.endsWith("\r")) value = value.slice(0, -1);
77
77
  if (!value) frame();
78
+ else if (value.startsWith("{")) {
79
+ let error;try { error = JSON.parse(value); } catch {}
80
+ if (error?.type === "error" || error?.error && typeof error.error === "object") {
81
+ onEvent({ ...error, type: "error" });
82
+ throw new Error("Upstream returned a JSON error outside an SSE data frame");
83
+ }
84
+ }
78
85
  else if (value.startsWith("data:")) {
79
86
  const part = value.slice(5).replace(/^ /, "");frameBytes += Buffer.byteLength(part);
80
87
  if (frameBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");data.push(part);
@@ -168,7 +175,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
168
175
  observeMessagesWindow(selectedProvider, configuredModel || model, selectedCapability, selectedModel);
169
176
  }
170
177
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
171
- conversation = validateConversation?.(body, req.headers, selectedProvider);
178
+ conversation = await validateConversation?.(body, req.headers, selectedProvider, abort.signal);
172
179
  if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
173
180
  terminalOrigin = "transport";
174
181
  const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
@@ -213,7 +220,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
213
220
  if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
214
221
  origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
215
222
  if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
216
- if (value.content.some(hasMessageState)) conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
223
+ if (value.content.some(hasMessageState)) await conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
224
+ abort.signal.throwIfAborted();
217
225
  model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
218
226
  sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
219
227
  } else if (countTokens && upstream.ok && !modelFailure) outcome = "completed";
@@ -223,6 +231,14 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
223
231
  if (!/^text\/event-stream(?:\s*;|$)/i.test(upstream.headers.get("content-type") || "")) throw new Error("Expected a Claude event stream");
224
232
  abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
225
233
  res.writeHead(upstream.status, { ...headers, "Cache-Control": "no-cache" });
234
+ let commitState = null, conversationCommitted = false;
235
+ const commitOutput = async () => {
236
+ if (commitState && !conversationCommitted && conversation?.commit) {
237
+ conversationCommitted = await conversation.commit(commitState) === true;
238
+ abort.signal.throwIfAborted();
239
+ }
240
+ commitState = null;
241
+ };
226
242
  const observer = createMessagesObserver(event => {
227
243
  if (event.type === "error") {
228
244
  failedEvent = true;outcome = "failed";
@@ -231,7 +247,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
231
247
  }
232
248
  if (sawStop || failedEvent) return;
233
249
  if (event.type === "content_block_start" && hasMessageState(event.content_block)
234
- || event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) conversation?.commit?.({ tool: event.content_block?.type === "tool_use" });
250
+ || event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) {
251
+ if (!conversationCommitted) commitState = { tool: commitState?.tool === true || event.content_block?.type === "tool_use" };
252
+ }
235
253
  if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
236
254
  if (event.type === "content_block_delta" && isMessagesOutputDelta(event.delta)) tracker?.firstOutput();
237
255
  if (event.type === "message_delta") {
@@ -246,12 +264,14 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
246
264
  const { value, done } = await reader.read();if (done) break;
247
265
  tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
248
266
  const frames = observer.write(value);
267
+ await commitOutput();
249
268
  let writable = true;
250
269
  for (const chunk of frames) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) { writable = false;break; }
251
270
  if (!writable) break;
252
271
  if (sawStop || failedEvent) break;
253
272
  }
254
- for (const chunk of observer.finish()) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
273
+ const tail = observer.finish();await commitOutput();
274
+ for (const chunk of tail) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
255
275
  if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
256
276
  if (!res.writableEnded) res.end();
257
277
  } finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
@@ -132,8 +132,8 @@ export const MANAGED_COMMANDS = [
132
132
  action: { setup: "on", remove: "off", repair: "fix" }[action] || action,
133
133
  }))
134
134
  ),
135
- ...["status", "models", "enable", "disable"].map(action =>
136
- command(`app codex image ${action}`, ({ status: "Show native image status", models: "List available GitHub image models", enable: "Enable native images", disable: "Disable native images" })[action], read, flags => ({ command: "image", action, outputFormat: flags.format }))
135
+ ...["status", "models", "enable", "disable", "check", "repair", "open"].map(action =>
136
+ command(`app codex image ${action}`, ({ status: "Show native image status", models: "List available GitHub image models", enable: "Enable native images", disable: "Disable native images", check: "Check native image access", repair: "Repair image launch configuration", open: "Open Codex with native image tools" })[action], read, flags => ({ command: "image", action, outputFormat: flags.format }))
137
137
  ),
138
138
  command("app codex image select", "Choose the native image model", { "--id": "value", ...read }, flags => ({ command: "image", action: "select", imageModel: flags.id, outputFormat: flags.format })),
139
139
  command("app codex review status", "Show the Codex Auto-review selection", read),
package/src/cli-image.mjs CHANGED
@@ -4,20 +4,23 @@ import { dashboardToolRequest, pauseServiceFeature } from "./cli-tools.mjs";
4
4
 
5
5
  export async function runImageCommand({ action, model, output = process.stdout, home, env = process.env,
6
6
  adapterPort = 2026, adapterHost = "127.0.0.1", request = dashboardToolRequest } = {}) {
7
- if (!["status", "models", "enable", "disable", "select"].includes(action)) throw new Error("Choose image status, models, enable, disable or select --id MODEL");
7
+ if (!["status", "models", "enable", "disable", "select", "check", "repair", "open"].includes(action)) throw new Error("Choose image status, models, enable, disable, check, repair, open or select --id MODEL");
8
8
  const local = { home, env }, address = { port: adapterPort, host: adapterHost };
9
9
  if (["enable", "disable"].includes(action)) output.write(await pauseServiceFeature({ ...local, ...address, feature: "image", action: action === "enable" ? "resume" : "pause", request }) + "\n");
10
10
  let result;
11
11
  try {
12
12
  if (action === "select" && !model) throw new Error("Supply --id with an available image model ID");
13
- const data = await request({ ...address, path: "settings", timeoutMs: action === "status" ? 1000 : 5000,
13
+ const data = await request({ ...address, path: "settings", timeoutMs: action === "open" ? 210000 : action === "repair" ? 15000 : action === "status" ? 1000 : 5000,
14
+ ...(["check", "repair", "open"].includes(action) ? { body: { action: "image", operation: action } } : {}),
14
15
  ...(action === "select" ? { body: { action: "image", operation: "select", model } } : {}) });
15
16
  result = data.features.image;
17
+ if (data.last_operation?.feature === "image") output.write(JSON.stringify(data.last_operation.result, null, 2) + "\n");
16
18
  } catch (error) {
17
- if (["models", "select"].includes(action)) throw error;
19
+ if (["models", "select", "check", "repair", "open"].includes(action)) throw error;
18
20
  result = imageSetupSummary(local);
19
21
  }
20
22
  output.write(`Native Codex images: ${!result.enabled ? "disabled" : result.configured ? "enabled" : "needs GitHub access"}\n`);
23
+ if (result.runtime) output.write(`App host: ${result.runtime.connected ? "connected" : "unconfirmed"}; chat tool: ${result.runtime.tool_registration}\n`);
21
24
  output.write(`Image model: ${terminalCell(result.selected_model || "Automatic; catalog unavailable")}\n`);
22
25
  if (result.availability === "selected_unavailable") output.write("Saved image model is unavailable; choose an available model.\n");
23
26
  for (const item of result.models || []) output.write(`${item.id === result.selected_model ? "*" : " "} ${terminalCell(item.name || item.id)} (${terminalCell(item.id)})\n`);
@@ -58,10 +58,11 @@ function imageType(bytes) {
58
58
  const inside = (root, file) => file === root || file.startsWith(root + path.sep);
59
59
 
60
60
  export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchImpl = fetch, imageEnabled,
61
- now = Date.now } = {}) {
61
+ now = Date.now, onEvent = () => {} } = {}) {
62
62
  baseUrl = imageHostBaseUrl(baseUrl);
63
63
  const requests = new Map(), threads = new Map(), active = new Map();
64
64
  let experimental = false, sequence = 0;
65
+ const observe = (event, thread) => { try { onEvent({ event, ...(thread ? { thread: createHash("sha256").update(thread).digest("hex").slice(0, 32) } : {}) }); } catch {} };
65
66
  const root = path.join(codexHome, "generated_images", "ccdx");
66
67
  const folder = id => path.join(root, createHash("sha256").update(id).digest("hex").slice(0, 32));
67
68
  const enabled = imageEnabled || (async () => {
@@ -139,11 +140,18 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
139
140
  }
140
141
 
141
142
  return {
142
- async client(message) {
143
- if (message.method === "initialize") experimental = message.params?.capabilities?.experimentalApi === true;
143
+ client(message) {
144
+ if (message.method === "initialize") {
145
+ experimental = message.params?.capabilities?.experimentalApi === true;
146
+ requests.set(JSON.stringify(message.id), { method: "initialize" });
147
+ }
144
148
  if (["thread/start", "thread/resume", "thread/fork"].includes(message.method)) {
145
- requests.set(JSON.stringify(message.id), { method: message.method, params: message.params || {} });
146
- if (message.method === "thread/start" && experimental && await enabled()) return { ...message, params: addImageHostTool(message.params || {}) };
149
+ const remember = registered => {
150
+ requests.set(JSON.stringify(message.id), { method: message.method, params: message.params || {}, registered });
151
+ return registered ? { ...message, params: addImageHostTool(message.params || {}) } : message;
152
+ };
153
+ if (message.method === "thread/start" && experimental) return Promise.resolve(enabled()).then(remember);
154
+ return remember(false);
147
155
  }
148
156
  if (message.method === "turn/start") {
149
157
  const context = threads.get(message.params?.threadId);
@@ -157,6 +165,8 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
157
165
  const pending = requests.get(JSON.stringify(message.id));
158
166
  if (pending && !message.method) {
159
167
  requests.delete(JSON.stringify(message.id));const thread = message.result?.thread;
168
+ if (!message.error && message.result && pending.method === "initialize") observe("connected");
169
+ if (thread?.id && pending.registered) observe("registered", thread.id);
160
170
  if (thread?.id && thread.cwd) threads.set(thread.id, { cwd: thread.cwd, roots: pending.params.runtimeWorkspaceRoots || [], attachments: [], generated: [] });
161
171
  }
162
172
  if (message.method === "item/completed" && message.params?.item?.type === "imageGeneration" && message.params.item.savedPath) {
@@ -166,24 +176,86 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
166
176
  const controller = new AbortController(), key = JSON.stringify(message.id);
167
177
  active.set(key, { controller, threadId: message.params.threadId });
168
178
  void runImage(message.params, AbortSignal.any([controller.signal, AbortSignal.timeout(180000)]))
169
- .then(result => sendToCodex({ id: message.id, result }))
170
- .catch(error => sendToCodex({ id: message.id, result: { success: false, contentItems: [{ type: "inputText", text: error.message }] } }))
179
+ .then(async result => { observe("generated", message.params.threadId);await sendToCodex({ id: message.id, result }); })
180
+ .catch(async error => { observe("failed", message.params.threadId);try { await sendToCodex({ id: message.id, result: { success: false, contentItems: [{ type: "inputText", text: error.message }] } }); } catch {} })
171
181
  .finally(() => active.delete(key));
172
182
  return true;
173
183
  },
174
- close() { for (const value of active.values()) value.controller.abort(new Error("Image host closed")); },
184
+ close() { observe("closed");for (const value of active.values()) value.controller.abort(new Error("Image host closed")); },
175
185
  };
176
186
  }
177
187
 
178
- function lines(stream, accept) {
179
- const decoder = new StringDecoder("utf8");let buffer = "";
180
- const data = chunk => {
181
- buffer += decoder.write(chunk);let boundary;
182
- while ((boundary = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, boundary);buffer = buffer.slice(boundary + 1);accept(line); }
188
+ function waitStream(stream, event, signal) {
189
+ return new Promise((resolve, reject) => {
190
+ const cleanup = () => {
191
+ stream.off(event, ready);stream.off("end", ended);stream.off("close", ended);stream.off("error", failed);
192
+ signal?.removeEventListener("abort", ended);
193
+ };
194
+ const ready = () => { cleanup();resolve(true); }, ended = () => { cleanup();resolve(false); }, failed = error => { cleanup();reject(error); };
195
+ stream.once(event, ready);stream.once("end", ended);stream.once("close", ended);stream.once("error", failed);
196
+ signal?.addEventListener("abort", ended, { once: true });
197
+ if (signal?.aborted || stream.destroyed) ended();
198
+ });
199
+ }
200
+
201
+ function pumpLines(stream, accept, signal, flush = () => {}) {
202
+ const decoder = new StringDecoder("utf8");let buffer = "", ended = false, pending = false, stopped = false;
203
+ let resolve, reject;
204
+ const done = new Promise((ok, fail) => { resolve = ok;reject = fail; });
205
+ const stop = error => {
206
+ if (stopped) return;stopped = true;
207
+ stream.off("data", data);stream.off("end", end);stream.off("close", end);stream.off("error", stop);
208
+ signal.removeEventListener("abort", abort);stream.pause();
209
+ if (error) reject(error);else resolve();
210
+ };
211
+ const abort = () => stop();
212
+ const wait = operation => {
213
+ pending = true;stream.pause();
214
+ operation.then(() => { pending = false;consume(); }, stop);
215
+ };
216
+ const consume = () => {
217
+ if (stopped || pending) return;
218
+ try {
219
+ let boundary;
220
+ while ((boundary = buffer.indexOf("\n")) >= 0) {
221
+ const wire = buffer.slice(0, boundary + 1);buffer = buffer.slice(boundary + 1);
222
+ const operation = accept(wire.slice(0, -1), wire);
223
+ if (operation?.then) { wait(operation);return; }
224
+ }
225
+ if (ended && buffer) {
226
+ const wire = buffer;buffer = "";const operation = accept(wire, wire);
227
+ if (operation?.then) { wait(operation);return; }
228
+ }
229
+ const operation = flush();
230
+ if (operation?.then) { wait(operation);return; }
231
+ if (ended) stop();else stream.resume();
232
+ } catch (error) { stop(error); }
233
+ };
234
+ const data = chunk => { buffer += decoder.write(chunk);consume(); };
235
+ const end = () => { if (!ended) { ended = true;buffer += decoder.end();consume(); } };
236
+ stream.on("data", data);stream.once("end", end);stream.once("close", end);stream.once("error", stop);
237
+ signal.addEventListener("abort", abort, { once: true });
238
+ if (signal.aborted) abort();else if (stream.readableEnded || stream.destroyed) end();
239
+ return done;
240
+ }
241
+
242
+ function hostWriter(stream, signal) {
243
+ let pending = null;
244
+ const direct = chunk => {
245
+ if (signal.aborted || stream.destroyed || stream.writableEnded) throw new Error("Image host destination closed");
246
+ if (!stream.write(chunk)) return waitStream(stream, "drain", signal).then(ready => { if (!ready) throw new Error("Image host destination closed"); });
247
+ };
248
+ return {
249
+ get pending() { return pending; },
250
+ write(chunk) {
251
+ const next = pending ? pending.then(() => direct(chunk)) : direct(chunk);
252
+ if (next) {
253
+ pending = next;
254
+ next.then(() => { if (pending === next) pending = null; }, () => {});
255
+ }
256
+ return next;
257
+ },
183
258
  };
184
- const end = () => { buffer += decoder.end();if (buffer) accept(buffer); };
185
- stream.on("data", data);stream.on("end", end);
186
- return () => { stream.removeListener("data", data);stream.removeListener("end", end); };
187
259
  }
188
260
 
189
261
  export async function runCodexImageHost({ codex, argv, baseUrl, env = process.env, input = process.stdin, output = process.stdout, error = process.stderr, spawnImpl = spawn } = {}) {
@@ -193,26 +265,67 @@ export async function runCodexImageHost({ codex, argv, baseUrl, env = process.en
193
265
  && (rest.indexOf("--listen") < 0 || rest[rest.indexOf("--listen") + 1] === "stdio://");
194
266
  const childEnv = { ...env, CODEX_APP_RUNTIME_CLI_PATH: codex };delete childEnv.CODEX_CLI_PATH;
195
267
  const child = spawnImpl(codex, args, { env: childEnv, stdio: ["pipe", "pipe", "pipe"] });
196
- child.stdin.on("error", () => {});child.stderr.pipe(error, { end: false });
197
- let bridge, queue = Promise.resolve();const cleanups = [];
198
- const write = message => { if (!child.stdin.destroyed) child.stdin.write(JSON.stringify(message) + "\n"); };
268
+ const completed = once(child, "close");completed.catch(() => {});
269
+ const inputAbort = new AbortController(), outputAbort = new AbortController(), reportingAbort = new AbortController();
270
+ let bridge, failure;
271
+ const fail = cause => { if (failure) return;failure = cause;inputAbort.abort();outputAbort.abort();bridge?.close();child.kill("SIGTERM"); };
272
+ const inputClosed = () => inputAbort.abort();
273
+ child.stdin.on("error", inputClosed);child.stdin.on("close", inputClosed);input.on("error", fail);child.stdout.on("error", fail);output.on("error", fail);
274
+ child.stderr.pipe(error, { end: false });
275
+ const hostId = randomUUID();let reporting = Promise.resolve(), pendingReports = 0;
276
+ const report = evidence => {
277
+ if (pendingReports >= 16) return;
278
+ pendingReports++;
279
+ reporting = reporting.then(async () => {
280
+ const url = new URL(baseUrl);url.pathname = "/_ccdx/ui/settings";
281
+ const response = await fetch(url, { method: "POST", redirect: "error", signal: AbortSignal.any([reportingAbort.signal, AbortSignal.timeout(1000)]),
282
+ headers: { "X-CCDX-Dashboard": "1", Origin: url.origin, "Content-Type": "application/json" },
283
+ body: JSON.stringify({ action: "image", operation: "report", evidence: { ...evidence, id: hostId, pid: process.pid } }) });
284
+ await response.body?.cancel();
285
+ }).catch(() => {}).finally(() => { pendingReports--; });
286
+ };
287
+ const destination = hostWriter(child.stdin, inputAbort.signal), client = hostWriter(output, outputAbort.signal);
288
+ const write = message => destination.write(JSON.stringify(message) + "\n");
289
+ let inputPump = Promise.resolve(), outputPump = Promise.resolve();
199
290
  if (!stdio) { input.pipe(child.stdin);child.stdout.pipe(output, { end: false }); }
200
291
  else {
201
- bridge = createImageHostBridge({ baseUrl, codexHome: path.resolve(env.CODEX_HOME || path.join(env.HOME || process.env.HOME, ".codex")), sendToCodex: write });
202
- cleanups.push(lines(input, raw => {
203
- queue = queue.then(async () => {
204
- let message;try { message = JSON.parse(raw); } catch { child.stdin.write(raw + "\n");return; }
205
- try { const next = await bridge.client(message);if (next === message) child.stdin.write(raw + "\n");else write(next); }
206
- catch (failure) { output.write(JSON.stringify({ id: message.id, error: { code: -32602, message: failure.message } }) + "\n"); }
207
- });
208
- }));
209
- cleanups.push(lines(child.stdout, raw => { let value;try { value = JSON.parse(raw); } catch {}if (!value || !bridge.codex(value)) output.write(raw + "\n"); }));
210
- const end = () => { void queue.finally(() => { bridge.close();child.stdin.end(); }); };
211
- input.on("end", end);cleanups.push(() => input.removeListener("end", end));
292
+ bridge = createImageHostBridge({ baseUrl, codexHome: path.resolve(env.CODEX_HOME || path.join(env.HOME || process.env.HOME, ".codex")), sendToCodex: write, onEvent: report });
293
+ inputPump = pumpLines(input, (raw, wire) => {
294
+ let message;try { message = JSON.parse(raw); } catch { return destination.write(wire); }
295
+ const forward = next => next === message ? destination.write(wire) : write(next);
296
+ const invalid = failure => client.write(JSON.stringify({ id: message.id, error: { code: -32602, message: failure.message } }) + "\n");
297
+ let next;try { next = bridge.client(message); } catch (failure) { return invalid(failure); }
298
+ return next?.then ? next.then(forward, invalid) : forward(next);
299
+ }, inputAbort.signal).then(() => {
300
+ if (!inputAbort.signal.aborted) { bridge.close();child.stdin.end(); }
301
+ }).catch(cause => { if (!inputAbort.signal.aborted) fail(cause); });
302
+ let buffered = "", bytes = 0;
303
+ const flush = () => {
304
+ if (!buffered) return;
305
+ const wire = buffered;buffered = "";bytes = 0;return client.write(wire);
306
+ };
307
+ const accept = (value, wire) => {
308
+ if (!value || !bridge.codex(value)) { buffered += wire;bytes += Buffer.byteLength(wire); }
309
+ if (bytes >= (output.writableHighWaterMark || 1)) return flush();
310
+ };
311
+ outputPump = pumpLines(child.stdout, (raw, wire) => {
312
+ let value;try { value = JSON.parse(raw); } catch {}
313
+ if (value?.method === "item/tool/call" && value.params?.namespace === IMAGE_HOST_NAMESPACE && destination.pending) return destination.pending.then(() => accept(value, wire));
314
+ return accept(value, wire);
315
+ }, outputAbort.signal, flush).catch(fail);
212
316
  }
213
- const stop = signal => { bridge?.close();child.kill(signal); };
317
+ const stop = signal => { bridge?.close();inputAbort.abort();outputAbort.abort();child.kill(signal); };
214
318
  const interrupt = () => stop("SIGINT"), terminate = () => stop("SIGTERM");
215
319
  process.once("SIGINT", interrupt);process.once("SIGTERM", terminate);
216
- try { const [code, signal] = await once(child, "exit");await queue;return code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 1); }
217
- finally { bridge?.close();for (const cleanup of cleanups) cleanup();input.unpipe(child.stdin);input.pause();process.removeListener("SIGINT", interrupt);process.removeListener("SIGTERM", terminate); }
320
+ try {
321
+ const [code, signal] = await completed;
322
+ bridge?.close();inputAbort.abort();await inputPump;await outputPump;
323
+ if (failure) throw failure;
324
+ return code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 1);
325
+ } finally {
326
+ bridge?.close();inputAbort.abort();outputAbort.abort();reportingAbort.abort();
327
+ input.unpipe(child.stdin);input.pause();
328
+ child.stdin.off("error", inputClosed);child.stdin.off("close", inputClosed);input.off("error", fail);child.stdout.off("error", fail);output.off("error", fail);
329
+ process.removeListener("SIGINT", interrupt);process.removeListener("SIGTERM", terminate);
330
+ }
218
331
  }
@@ -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
  }
@@ -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
  }