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.
@@ -1116,3 +1116,19 @@ Usage presentation maps configured api_ identifiers to current provider labels a
1116
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
1117
 
1118
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.
1127
+
1128
+ ## Shared Codex App restart and source reliability (1.3.19)
1129
+
1130
+ The image and input-suggestion panels share `codex-launch-control.mjs`. `codex-app-control.mjs` associates live host reports with the verified macOS App by process ancestry and checks its prediction PAC argument without treating another process's host or an unobserved chat as proof. Its AppKit control targets only the verified bundle path and PID. A restart requires an explicit user action, prepares enabled routes, asks the App to quit normally, waits for exit, applies any pending prediction display setting and then uses the existing launcher. A refusal, unknown identity, multiple Apps or timeout stops the action without force-quit. A failed post-close display write stays pending and is reported after the App is reopened. Host evidence is accepted independently of serialized settings operations so a restarting App's short-lived report is not lost behind its own restart. Later host tool events also re-establish evidence if CCDX restarted while the host remained live.
1131
+
1132
+ The managed Codex catalog projects explicit source input modalities ahead of native templates and checks GitHub priority eligibility against the full live source registry. Unknown modality metadata keeps the prior fallback. Source identities, selected models and routing remain unchanged.
1133
+
1134
+ `safe-upstream-error.mjs` reads only failed image or custom API responses, with a 64 KiB size bound, a 200 ms timer and four concurrent readers. Only fixed code/status pairs and local messages escape the reader. Original status, stable CCDX codes and validated Retry-After remain intact. Error-header callbacks release request admission before the optional body read; image processing slots are released at the same point. Count-token singleflight forwards those callbacks only to the appropriate waiters. Successful requests never invoke the reader.
package/docs/REFERENCE.md CHANGED
@@ -208,6 +208,11 @@ metadata and records a bounded error; a changed endpoint/key invalidates prior
208
208
  catalog evidence. A listing or minimal successful reply is not a capability test.
209
209
  Ordinary page reads use saved data and never probe each model. No public model-name
210
210
  heuristic or original-vendor limit is applied to an arbitrary relay deployment.
211
+ The managed Codex catalog uses an explicitly declared input modality in preference
212
+ to the native template. Unknown modalities retain the existing template fallback.
213
+ For GitHub models, fast/priority tiers are shown only when the full source catalog
214
+ supports the existing priority route, including an eligible fast variant that is
215
+ not itself selected in the model picker.
211
216
 
212
217
  Claude configuration and gateway catalogs use the same compiled model plan.
213
218
  Explicit App bindings use opaque source-qualified aliases and actual model/source
@@ -274,7 +279,7 @@ CLI-only interaction forms include JSON output, file input, key stdin and shell
274
279
 
275
280
  ## Prediction controls
276
281
 
277
- WebUI → Codex → Input suggestions is the complete enable/disable control. Setup and explicit enable write only `desktop.composer-predictions-enabled` in Codex TOML and its legacy persisted-atom equivalent; unrelated configuration/state remains intact. Writes require Codex to be closed. An open App keeps a pending display change; quit it and Continue setup, or normally launch CCDX again. The WebUI can open Codex after setup without a terminal command. No running App is forcibly closed.
282
+ WebUI → Codex → Input suggestions is the complete enable/disable control. Setup and explicit enable write only `desktop.composer-predictions-enabled` in Codex TOML and its legacy persisted-atom equivalent; unrelated configuration/state remains intact. Writes require Codex to be closed. An open App keeps a pending display change. On macOS, the WebUI can apply it during an explicitly requested normal Codex restart; alternatively, quit the App and Continue setup. Windows retains its existing open and manual-close flow. No running App is forcibly closed.
278
283
 
279
284
  Native configuration and startup environment checks use temporary work threads so OS/crypto work does not block the core service. Missing Apps are checked before trust/proxy setup. A normal cold startup attempts setup once when no CCDX prediction record exists, prediction access is allowed, and the App display preference is not saved off. Failed setup leaves core startup available and can be completed in WebUI. Saved off records and App off choices are preserved. Explicit enable intentionally overrides a prior App display-off setting. Repair keeps the selected on/off intent. Disable retains trust and routing; Remove setup owns trust/route cleanup and may defer cleanup until Codex closes. Visible predictions still require native App/thread eligibility and an actual returned suggestion.
280
285
 
@@ -578,17 +583,27 @@ unknown candidate-visibility value. A successful recovery only means the bridge
578
583
  was recreated on the original address, not that gray text appeared.
579
584
 
580
585
 
586
+ ## Error delivery and conversation commits
587
+
588
+ Image and custom API HTTP errors keep their stable `ccdx_images_http_<status>` or `ccdx_api_http_<status>` code, status and validated Retry-After. A failure-only reader can retain a small allowlist of structured source codes in `upstream_code`; source messages and bodies are not forwarded. Reads are limited to 64 KiB and a 200 ms timer, with at most four concurrent readers. Unknown or unfinished bodies fall back to the existing generic error. Request admission and image-generation slots are released before this optional read. Successful responses do not enter the reader. These changes do not introduce retries.
589
+
590
+ 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.
591
+
581
592
  ## Native image generation
582
593
 
583
594
  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
595
 
585
596
  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
597
 
587
- 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.
598
+ The Web UI image panel and terminal `check`, `repair`, and `open` controls use the service's image setup and launch controls. `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. The terminal `open` command opens Codex only when it is closed. Disabled image settings and custom launch routes are preserved.
599
+
600
+ On macOS, the image and input-suggestion panels use the same App state and launch control. If Codex is closed, the button opens it; if the enabled integrations are ready, it switches to Codex; if they need a restart or their route is unconfirmed, it offers **Restart Codex to connect** with a warning that running tasks can be interrupted. The restart happens only when that button is clicked. CCDX prepares enabled routes first, requests a normal App exit, waits for it to close, applies a pending suggestion display change, and opens it through the existing launcher. It does not force-quit the App or restart CCDX. If the App refuses to close, its identity changes, or preparation fails, the action stops and reports the reason. If a post-close display change fails, CCDX retains it as pending and reports it when reopening. A successful launch request does not prove that the current chat has the image tool; an older chat without the tool still needs a new chat.
601
+
602
+ 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.
588
603
 
589
604
  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.
590
605
 
591
- 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.
606
+ 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. Use the image panel's explicit restart when that App has not loaded the host, then use a new chat if the existing chat lacks the tool. 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.
592
607
 
593
608
  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:
594
609
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.17",
3
+ "version": "1.3.19",
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
+ }
@@ -175,11 +175,13 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
175
175
  observeMessagesWindow(selectedProvider, configuredModel || model, selectedCapability, selectedModel);
176
176
  }
177
177
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
178
- conversation = validateConversation?.(body, req.headers, selectedProvider);
178
+ conversation = await validateConversation?.(body, req.headers, selectedProvider, abort.signal);
179
179
  if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
180
180
  terminalOrigin = "transport";
181
181
  const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
182
+ let upstreamHeadersObserved = false;
182
183
  const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
184
+ onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
183
185
  onCountObservation(value) {
184
186
  context.countObservation = { ...context.countObservation, ...value };
185
187
  if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
@@ -201,7 +203,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
201
203
  } else upstream = await call(body, callOptions);
202
204
  body = null;
203
205
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
204
- tracker?.upstreamHeaders(upstream.status);
206
+ if (!upstreamHeadersObserved) tracker?.upstreamHeaders(upstream.status);
205
207
  release();release = () => {};
206
208
  try { onRequest({ client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude" }); } catch {}
207
209
  const headers = safeUpstreamResponseHeaders(upstream.headers);
@@ -217,10 +219,11 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
217
219
  const evidence = upstreamErrorEvidence(raw);
218
220
  context.onHttpError?.({ ...evidence, code: evidence.code || evidence.error_type || "upstream_error", model_error: true, origin: "upstream_response", headers: upstream.headers });
219
221
  }
220
- if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
222
+ if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw, { status: upstream.status }),
221
223
  origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
222
224
  if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
223
- if (value.content.some(hasMessageState)) conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
225
+ if (value.content.some(hasMessageState)) await conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
226
+ abort.signal.throwIfAborted();
224
227
  model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
225
228
  sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
226
229
  } else if (countTokens && upstream.ok && !modelFailure) outcome = "completed";
@@ -230,6 +233,14 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
230
233
  if (!/^text\/event-stream(?:\s*;|$)/i.test(upstream.headers.get("content-type") || "")) throw new Error("Expected a Claude event stream");
231
234
  abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
232
235
  res.writeHead(upstream.status, { ...headers, "Cache-Control": "no-cache" });
236
+ let commitState = null, conversationCommitted = false;
237
+ const commitOutput = async () => {
238
+ if (commitState && !conversationCommitted && conversation?.commit) {
239
+ conversationCommitted = await conversation.commit(commitState) === true;
240
+ abort.signal.throwIfAborted();
241
+ }
242
+ commitState = null;
243
+ };
233
244
  const observer = createMessagesObserver(event => {
234
245
  if (event.type === "error") {
235
246
  failedEvent = true;outcome = "failed";
@@ -238,7 +249,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
238
249
  }
239
250
  if (sawStop || failedEvent) return;
240
251
  if (event.type === "content_block_start" && hasMessageState(event.content_block)
241
- || 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" });
252
+ || event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) {
253
+ if (!conversationCommitted) commitState = { tool: commitState?.tool === true || event.content_block?.type === "tool_use" };
254
+ }
242
255
  if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
243
256
  if (event.type === "content_block_delta" && isMessagesOutputDelta(event.delta)) tracker?.firstOutput();
244
257
  if (event.type === "message_delta") {
@@ -253,12 +266,14 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
253
266
  const { value, done } = await reader.read();if (done) break;
254
267
  tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
255
268
  const frames = observer.write(value);
269
+ await commitOutput();
256
270
  let writable = true;
257
271
  for (const chunk of frames) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) { writable = false;break; }
258
272
  if (!writable) break;
259
273
  if (sawStop || failedEvent) break;
260
274
  }
261
- for (const chunk of observer.finish()) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
275
+ const tail = observer.finish();await commitOutput();
276
+ for (const chunk of tail) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
262
277
  if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
263
278
  if (!res.writableEnded) res.end();
264
279
  } finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
@@ -1,19 +1,30 @@
1
+ import { resolveCopilotPriorityTierModel } from "../models.mjs";
2
+
1
3
  // Codex's native catalog is an application projection, not provider metadata.
2
4
  export function codexModelEntry(model, { priority = 0, name = "", template = {} } = {}) {
3
5
  const values = model.capability?.values || {}, efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
4
6
  return { shell_type: "unified_exec", availability_nux: null, upgrade: null, additional_speed_tiers: [], service_tiers: [],
5
7
  base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
6
8
  supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
7
- experimental_supported_tools: [], input_modalities: values.input_modalities || ["text"], ...template,
9
+ experimental_supported_tools: [], ...template,
10
+ input_modalities: values.input_modalities || template.input_modalities || ["text"],
8
11
  slug: model.public_id || model.id, display_name: model.display_name || template.display_name || model.name || model.id, description: model.description || template.description || name, visibility: "list", supported_in_api: true, priority,
9
12
  default_reasoning_level: efforts[0] || null, supported_reasoning_levels: efforts.map(effort => ({ effort, description: effort })),
10
13
  context_window: values.context_window || template.context_window || null, max_context_window: values.context_window || template.max_context_window || null };
11
14
  }
12
- export function codexClientCatalog(plan) {
13
- return Object.assign((value, nativeCatalog) => ({ ...value, models: plan.models.map((model, priority) => {
14
- const template = model.source_id === "github" ? nativeCatalog?.models?.find(entry => entry.slug === model.id) : undefined;
15
- return codexModelEntry(model, { priority, template, name: model.source_name || model.source_id });
16
- }) }), { needsNativeCatalog: plan.models.some(model => model.source_id === "github") });
15
+ export function codexClientCatalog(plan, githubModels = () => null) {
16
+ const needsNativeCatalog = plan.models.some(model => model.source_id === "github");
17
+ return Object.assign((value, nativeCatalog) => {
18
+ const github = needsNativeCatalog ? githubModels() : null;
19
+ return { ...value, models: plan.models.map((model, priority) => {
20
+ const template = model.source_id === "github" ? nativeCatalog?.models?.find(entry => entry.slug === model.id) : undefined;
21
+ const entry = codexModelEntry(model, { priority, template, name: model.source_name || model.source_id });
22
+ if (model.source_id === "github" && !resolveCopilotPriorityTierModel(model.id, "priority", github)) {
23
+ entry.additional_speed_tiers = [];entry.service_tiers = [];delete entry.default_service_tier;
24
+ }
25
+ return entry;
26
+ }) };
27
+ }, { needsNativeCatalog });
17
28
  }
18
29
 
19
30
  export function codexSourceCatalog(source) {
@@ -0,0 +1,67 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { isPredictionPacUrl } from "./prediction-pac.mjs";
4
+
5
+ const execute = promisify(execFile);
6
+ const apps = new Set(["/Applications/Codex.app", "/Applications/ChatGPT.app"]);
7
+
8
+ // AppKit asks an existing application to quit normally or become active. It
9
+ // never launches a new process and never force-quits an application.
10
+ const appScript = `ObjC.import("AppKit");
11
+ function run(argv) {
12
+ var app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(argv[0]));
13
+ if (app.isNil()) return "absent";
14
+ if (ObjC.unwrap(app.bundleIdentifier) !== "com.openai.codex" || ObjC.unwrap(app.bundleURL.path) !== argv[1]) return "different";
15
+ var sent = argv[2] === "quit" ? app.terminate : app.activateWithOptions($.NSApplicationActivateIgnoringOtherApps);
16
+ return sent ? "sent" : "refused";
17
+ }`;
18
+
19
+ export async function inspectCodexApp(app, hosts = [], { platform = process.platform, exec = execute, predictionPacUrl } = {}) {
20
+ if (platform !== "darwin") return { status: "unsupported" };
21
+ if (!apps.has(app)) throw new Error("Unrecognized Codex App path");
22
+ const result = await exec("/bin/ps", ["-axo", "pid=,ppid=,comm="], { encoding: "utf8", timeout: 3000, maxBuffer: 4 * 1024 * 1024 });
23
+ const processes = new Map();
24
+ for (const line of String(result?.stdout ?? result).split("\n")) {
25
+ const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
26
+ if (match) processes.set(Number(match[1]), { pid: Number(match[1]), parent: Number(match[2]), command: match[3] });
27
+ }
28
+ const matches = [...processes.values()].filter(row => [`${app}/Contents/MacOS/ChatGPT`, `${app}/Contents/MacOS/Codex`].includes(row.command));
29
+ if (!matches.length) return { status: "stopped" };
30
+ if (matches.length !== 1) return { status: "multiple" };
31
+ const pid = matches[0].pid;
32
+ const belongsToApp = host => {
33
+ if (!host.connected) return false;
34
+ let node = processes.get(host.pid);const visited = new Set();
35
+ while (node && !visited.has(node.pid)) {
36
+ if (node.pid === pid) return true;
37
+ visited.add(node.pid);node = processes.get(node.parent);
38
+ }
39
+ return false;
40
+ };
41
+ const linked = hosts.filter(belongsToApp);
42
+ let predictionRoute;
43
+ if (isPredictionPacUrl(predictionPacUrl)) {
44
+ predictionRoute = "unconfirmed";
45
+ try {
46
+ const result = await exec("/bin/ps", ["-p", String(pid), "-o", "args="], { encoding: "utf8", timeout: 3000, maxBuffer: 64 * 1024 });
47
+ const args = String(result?.stdout ?? result).trim(), executable = matches[0].command;
48
+ const route = /(?:^|\s)--proxy-pac-url=(?:"(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?)"|(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?)(?=\s|$))/.exec(args);
49
+ if ((args === executable || args.startsWith(executable + " ")) && (args.match(/(?:^|\s)--proxy-pac-url=/g) || []).length === 1
50
+ && (route?.[1] || route?.[2]) === predictionPacUrl) predictionRoute = "verified";
51
+ } catch { /* A missing route is not proof that the App uses one. */ }
52
+ }
53
+ return { status: "running", pid, host: linked.length ? "connected" : "unconfirmed",
54
+ ...(predictionRoute ? { prediction_route: predictionRoute } : {}),
55
+ tool_registration: linked.some(host => host.threads?.length) ? "observed" : "unconfirmed" };
56
+ }
57
+
58
+ export async function controlCodexApp(app, pid, action, { platform = process.platform, exec = execute } = {}) {
59
+ if (platform !== "darwin" || !apps.has(app) || !Number.isSafeInteger(pid) || pid <= 0 || !["quit", "activate"].includes(action)) {
60
+ throw new Error("Invalid Codex App control request");
61
+ }
62
+ const result = await exec("/usr/bin/osascript", ["-l", "JavaScript", "-e", appScript, String(pid), app, action],
63
+ { encoding: "utf8", timeout: 5000, maxBuffer: 4096 });
64
+ const value = String(result?.stdout ?? result).trim();
65
+ if (!["sent", "absent", "different", "refused"].includes(value)) throw new Error("Could not control the verified Codex App");
66
+ return value;
67
+ }
@@ -140,15 +140,18 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
140
140
  }
141
141
 
142
142
  return {
143
- async client(message) {
143
+ client(message) {
144
144
  if (message.method === "initialize") {
145
145
  experimental = message.params?.capabilities?.experimentalApi === true;
146
146
  requests.set(JSON.stringify(message.id), { method: "initialize" });
147
147
  }
148
148
  if (["thread/start", "thread/resume", "thread/fork"].includes(message.method)) {
149
- const registered = message.method === "thread/start" && experimental && await enabled();
150
- requests.set(JSON.stringify(message.id), { method: message.method, params: message.params || {}, registered });
151
- if (registered) 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);
152
155
  }
153
156
  if (message.method === "turn/start") {
154
157
  const context = threads.get(message.params?.threadId);
@@ -173,8 +176,8 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
173
176
  const controller = new AbortController(), key = JSON.stringify(message.id);
174
177
  active.set(key, { controller, threadId: message.params.threadId });
175
178
  void runImage(message.params, AbortSignal.any([controller.signal, AbortSignal.timeout(180000)]))
176
- .then(result => { observe("generated", message.params.threadId);sendToCodex({ id: message.id, result }); })
177
- .catch(error => { observe("failed", message.params.threadId);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 {} })
178
181
  .finally(() => active.delete(key));
179
182
  return true;
180
183
  },
@@ -182,15 +185,77 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
182
185
  };
183
186
  }
184
187
 
185
- function lines(stream, accept) {
186
- const decoder = new StringDecoder("utf8");let buffer = "";
187
- const data = chunk => {
188
- buffer += decoder.write(chunk);let boundary;
189
- 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
+ },
190
258
  };
191
- const end = () => { buffer += decoder.end();if (buffer) accept(buffer); };
192
- stream.on("data", data);stream.on("end", end);
193
- return () => { stream.removeListener("data", data);stream.removeListener("end", end); };
194
259
  }
195
260
 
196
261
  export async function runCodexImageHost({ codex, argv, baseUrl, env = process.env, input = process.stdin, output = process.stdout, error = process.stderr, spawnImpl = spawn } = {}) {
@@ -200,9 +265,13 @@ export async function runCodexImageHost({ codex, argv, baseUrl, env = process.en
200
265
  && (rest.indexOf("--listen") < 0 || rest[rest.indexOf("--listen") + 1] === "stdio://");
201
266
  const childEnv = { ...env, CODEX_APP_RUNTIME_CLI_PATH: codex };delete childEnv.CODEX_CLI_PATH;
202
267
  const child = spawnImpl(codex, args, { env: childEnv, stdio: ["pipe", "pipe", "pipe"] });
203
- child.stdin.on("error", () => {});child.stderr.pipe(error, { end: false });
204
- let bridge, queue = Promise.resolve();const cleanups = [];
205
- const reportingAbort = new AbortController();
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 });
206
275
  const hostId = randomUUID();let reporting = Promise.resolve(), pendingReports = 0;
207
276
  const report = evidence => {
208
277
  if (pendingReports >= 16) return;
@@ -215,24 +284,48 @@ export async function runCodexImageHost({ codex, argv, baseUrl, env = process.en
215
284
  await response.body?.cancel();
216
285
  }).catch(() => {}).finally(() => { pendingReports--; });
217
286
  };
218
- const write = message => { if (!child.stdin.destroyed) child.stdin.write(JSON.stringify(message) + "\n"); };
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();
219
290
  if (!stdio) { input.pipe(child.stdin);child.stdout.pipe(output, { end: false }); }
220
291
  else {
221
292
  bridge = createImageHostBridge({ baseUrl, codexHome: path.resolve(env.CODEX_HOME || path.join(env.HOME || process.env.HOME, ".codex")), sendToCodex: write, onEvent: report });
222
- cleanups.push(lines(input, raw => {
223
- queue = queue.then(async () => {
224
- let message;try { message = JSON.parse(raw); } catch { child.stdin.write(raw + "\n");return; }
225
- try { const next = await bridge.client(message);if (next === message) child.stdin.write(raw + "\n");else write(next); }
226
- catch (failure) { output.write(JSON.stringify({ id: message.id, error: { code: -32602, message: failure.message } }) + "\n"); }
227
- });
228
- }));
229
- cleanups.push(lines(child.stdout, raw => { let value;try { value = JSON.parse(raw); } catch {}if (!value || !bridge.codex(value)) output.write(raw + "\n"); }));
230
- const end = () => { void queue.finally(() => { bridge.close();child.stdin.end(); }); };
231
- input.on("end", end);cleanups.push(() => input.removeListener("end", end));
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);
232
316
  }
233
- const stop = signal => { bridge?.close();child.kill(signal); };
317
+ const stop = signal => { bridge?.close();inputAbort.abort();outputAbort.abort();child.kill(signal); };
234
318
  const interrupt = () => stop("SIGINT"), terminate = () => stop("SIGTERM");
235
319
  process.once("SIGINT", interrupt);process.once("SIGTERM", terminate);
236
- try { const [code, signal] = await once(child, "exit");await queue;return code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 1); }
237
- finally { bridge?.close();reportingAbort.abort();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
+ }
238
331
  }