codex-copilot-dx 1.3.18 → 1.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -67,6 +67,7 @@ Use the Web UI for accounts, APIs, models, client access, input suggestions, nat
67
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).
68
68
  - **Images:** Codex native host tools use the selected GitHub image model, with GPT Image 2.5 Flare as the default. Images start enabled; saved off choices are retained. On macOS with Codex 0.166+, fully quit a running App that lacks the host, start Codex through CCDX, and use a new chat. ChatGPT sign-in and Apps are retained. The Web UI provides model selection without an extra API key, MCP or CCDX image skill. [Details](docs/REFERENCE.md#native-image-generation).
69
69
  - **Updates:** Settings → Install update downloads and verifies a stable release, then switches the installed service when idle. Busy work postpones the switch. Unmanaged launches require the installer or an installed command. [Details](docs/REFERENCE.md#installation-and-updates).
70
+ - **App updates:** Checks & repairs and `ccdx doctor` show observed installed Codex and Claude versions. A version change does not by itself verify the running App or its integrations. [Details](docs/REFERENCE.md#checks-and-troubleshooting).
70
71
 
71
72
  Web UI activity updates through server push; the terminal uses the same in-process activity feed. Reconnecting restores current state and bounded recent records.
72
73
 
package/bin/cli.mjs CHANGED
@@ -315,6 +315,19 @@ let clientIntegration = null;
315
315
  let providerRuntime = null;
316
316
  let terminalConsole = null;
317
317
  const webUiUrl = `http://${ADAPTER_HOST === "::1" ? "[::1]" : "127.0.0.1"}:${ADAPTER_PORT}`;
318
+ let versionMonitor = null, versionModule = null;
319
+ const clientVersions = {
320
+ snapshot: () => versionMonitor?.snapshot() || null,
321
+ refresh() {
322
+ if (shuttingDown || serviceWorker?.warming || serviceWorker?.draining || serviceWorker?.preserving) return Promise.resolve(clientVersions.snapshot());
323
+ versionModule ||= import("../src/client-versions.mjs").then(({ createClientVersionMonitor }) => {
324
+ if (shuttingDown) return null;
325
+ versionMonitor = createClientVersionMonitor({ onChange: names => console.log(status("info", `Installed ${names.map(name => name === "codex" ? "Codex" : "Claude").join(" and ")} App updated; check integration in the WebUI or ccdx doctor`)) });
326
+ return versionMonitor;
327
+ }).catch(error => { versionModule = null;throw error; });
328
+ return versionModule.then(monitor => monitor?.refresh());
329
+ },
330
+ };
318
331
  async function launchDashboard() {
319
332
  try {
320
333
  const result = await openDashboard(webUiUrl, { enabled: !CLI.noBrowser && servicePreferences().open_webui });
@@ -349,6 +362,8 @@ async function reuseRunningAdapterIfAvailable() {
349
362
  }
350
363
  if (!running.ok) return false;
351
364
 
365
+ void fetch(`${webUiUrl}/_ccdx/ui/settings`, { method: "POST", headers: { "X-CCDX-Dashboard": "1", Origin: webUiUrl, "Content-Type": "application/json" },
366
+ body: JSON.stringify({ action: "client_versions" }), signal: AbortSignal.timeout(1000) }).catch(() => {});
352
367
  const serviceStatus = readAdapterStatus({ host: ADAPTER_HOST, port: ADAPTER_PORT }).catch(() => null);
353
368
  console.log(startupCheck("ok", "Service", `Using running service: ${running.baseUrl}`));
354
369
  console.log(startupCheck("info", "Sign-in", "Using saved sign-in; not rechecked"));
@@ -455,6 +470,7 @@ try {
455
470
  providerRuntime = createProviderRuntime({ githubClient: profileRuntime.codexClient, githubRegistry: profileModels.codexRegistry,
456
471
  refreshGithubCatalog: () => profileModels.refreshCodex({ strict: true }),
457
472
  corePort: ADAPTER_PORT, preserveClientConfiguration: () => serviceWorker?.preserving === true || serviceWorker?.draining === true,
473
+ clientVersionsSnapshot: clientVersions.snapshot,
458
474
  clientAccessChanged: async enabled => { earlyIntegration.setPredictionActive(enabled && servicePreferences().prediction_enabled);if (enabled) await earlyIntegration.configure(); },
459
475
  githubCredentialFingerprint: () => profileRuntime.codexCredentialFingerprint,
460
476
  log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "M365", message)) });
@@ -498,7 +514,7 @@ try {
498
514
  snapshot: () => activeServer?.ccdxSnapshot?.() || {},
499
515
  subscribe: listener => activeServer?.ccdxSubscribeActivity?.(listener),
500
516
  preferences: () => { const { saved, theme, color_theme } = serviceSettingsSnapshot();return { ...saved, theme, color_theme }; } });
501
- const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole,
517
+ const serviceControl = createServiceControl({ providerRuntime, clientIntegration: earlyIntegration, terminal: terminalConsole, clientVersions,
502
518
  adapterPort: ADAPTER_PORT, adapterHost: ADAPTER_HOST, manualUpdate: serviceWorker ? () => serviceWorker.requestUpdate() : undefined,
503
519
  nightlyStatus: () => serviceWorker?.status() || null, nightlyChanged: enabled => serviceWorker?.preferenceChanged(enabled) });
504
520
  const codexModelCatalog = createCodexModelCatalog();
@@ -516,7 +532,7 @@ try {
516
532
  terminalAnimationTheme,
517
533
  terminalActivity: terminalConsole,
518
534
  handoffState: serviceWorker?.takeState(), isDraining: () => serviceWorker?.draining === true,
519
- dashboardOptions: { serviceControl, host: ADAPTER_HOST, port: ADAPTER_PORT,
535
+ dashboardOptions: { serviceControl, clientVersions, host: ADAPTER_HOST, port: ADAPTER_PORT,
520
536
  credentialsChanged: () => { defaultCopilotClient.invalidateCredentials();profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient }); },
521
537
  applyAnimation: theme => terminalConsole.apply({ theme }) },
522
538
  nativePredictionPac: () => clientIntegration?.pacUrl() || null,
@@ -547,12 +563,14 @@ try {
547
563
  modelRefreshTimer = setInterval(() => {
548
564
  if (providerRuntime.selection().codex === "github") profileModels.refreshAll().then(() => providerRuntime.selection().codex === "github" && providerRuntime.syncClients(["codex"])).catch(() => {});
549
565
  providerRuntime.refresh().catch(() => {});
566
+ void clientVersions.refresh().catch(() => {});
550
567
  }, refreshIntervalMs);
551
568
  modelRefreshTimer.unref?.();
552
569
  }
553
570
 
554
571
  startupComplete = true;
555
572
  if (!startupPresentation.enabled) console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
573
+ void clientVersions.refresh().catch(() => {});
556
574
  runInBackground(printUpdateNotice);
557
575
  await launchDashboard();
558
576
  if (!serviceWorker?.warming) {
@@ -569,6 +587,7 @@ try {
569
587
  let exitCode = 0;
570
588
  try {
571
589
  if (modelRefreshTimer) clearInterval(modelRefreshTimer);
590
+ versionMonitor?.close();
572
591
  const result = await closeHttpServer(activeServer, { timeoutMs: RUNTIME.shutdownTimeoutMs });
573
592
  if (result.forced) console.warn(status("warn", "Remaining service connections closed"));
574
593
  await clientIntegration?.close();
@@ -612,6 +631,7 @@ try {
612
631
  await LOGGING.cleanup();try { LOGGING = configureLogging(); } catch { LOGGING = configureLogging({ env: { ...process.env, CCDX_LOG_PATH: "" } }); }
613
632
  terminalConsole.start();LOGGING.setTerminalSink((method, args) => terminalConsole.log(method, args));
614
633
  earlyIntegration.retireImages();
634
+ setImmediate(() => void clientVersions.refresh().catch(() => {}));
615
635
  },
616
636
  inspect: () => {
617
637
  const data = activeServer.ccdxSnapshot(), routes = data.requests.by_route;
@@ -1124,3 +1124,19 @@ Native image failures cancel the vendor response and project safe JSON; API Resp
1124
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
1125
 
1126
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.
1135
+
1136
+ ## Client updates and streaming boundaries (1.3.20)
1137
+
1138
+ `client-versions.mjs` inspects bounded local App metadata asynchronously after service readiness. It coalesces checks, preserves a corrupt observation file, and atomically records only installed versions, builds and change times. A timed-out inspection cannot block service startup or inference. The current App process and actual capability adoption remain unverified. A detected unrecognized system Claude App major prevents later writes to shared capability fields without changing existing routing or model aliases. The existing model-refresh timer, manual checks and a nonblocking service-reuse notification schedule observation; a disabled timer leaves startup and manual checks available.
1139
+
1140
+ The Codex catalog retains at most two previously verified bundled catalogs in memory when the client supplies an exact prerelease/build version. A binary identity change during extraction, or two binaries reporting the same exact version, prevents that retained fallback. Requests containing only a core version keep their existing matching behavior and report its limited precision. No catalog is fetched from the network and no new persistent model cache is introduced.
1141
+
1142
+ Responses and Messages parsers, Chat line reading and the privacy restoration layer accept LF, CRLF and CR SSE lines. Existing output ordering, retry eligibility, error handling, comment heartbeats and backpressure remain. Source-lock cancellation signals reach both Responses handlers without changing ownership rules.
package/docs/REFERENCE.md CHANGED
@@ -106,10 +106,13 @@ Catalog diagnostics distinguish local cached data from an online response and ex
106
106
  - **Request failure:** use Requests or `ccdx requests --failed`. HTTP failures and model completion outcomes are separate. A successful HTTP transport can still carry a model error.
107
107
  - **Token counting unavailable:** an observed API count-endpoint 404 is cached briefly per model/header scope. Inference and token counting are separate capabilities; no synthetic count is returned.
108
108
  - **Local checks:** `doctor` is read-only by default. `--online` checks access; `--compat` sends minimal inference and consumes usage. `--fix` backs up owned configuration and performs bounded repairs. It does not enable optional features, change company policy or force-restart apps. Partial repairs exit 1.
109
+ - **App updates:** after the service is ready, CCDX observes installed App versions in the background. Checks & repairs shows the result; `ccdx doctor` can inspect it locally. On macOS this uses known App bundle metadata and, when available, the bundled Codex CLI version. On Windows the registered Codex package is inspected; Claude App remains unknown if reliable metadata is unavailable. The running process may still be an older build, and a version observation does not verify images, predictions, model access or protocol compatibility. A detected unrecognized Claude App major version preserves existing shared capability fields during later synchronization. The compact local version record contains only App versions, builds and observation times, not credentials or conversation data. It is refreshed on startup, local checks and the existing model-refresh cadence; a reused service receives a nonblocking refresh notification.
109
110
  - **Cache cleanup:** adding `--history` can break the next continuation. It does not delete client transcripts or generated images.
110
111
 
111
112
  Request inspection covers bounded retained records, not a full conversation archive. Unidentified clients stay unidentified. Routine diagnostics omit secrets, prompts and error bodies. Explicit error excerpts use bounded, redacted collection. The usage JSON `requests` field counts recorded usage rows, not HTTP calls. Usage is returned token metadata; cache hit is reused input divided by input from records with valid counts for both. Unknown/invalid records remain in token totals but are excluded from both sides of the rate, with partial coverage indicated. It is not a request-based cache rate or a billing receipt.
112
113
 
114
+ For an identified conversation, hovering a point in the input-history chart shows that request's available cache-reuse ratio. Missing or invalid counts remain unknown; the bounded in-memory history and retained usage do not change.
115
+
113
116
  ## Settings and appearance
114
117
 
115
118
  Settings separates saved preferences from effective state. Auto-save applies changes by default; required restarts remain explicit. Restore-defaults creates a backup first and keeps accounts, keys, model plans and chats. CLI preference reset/restore uses its own service-only backup; it does not change browser appearance or replace the Web UI's backup.
@@ -208,6 +211,11 @@ metadata and records a bounded error; a changed endpoint/key invalidates prior
208
211
  catalog evidence. A listing or minimal successful reply is not a capability test.
209
212
  Ordinary page reads use saved data and never probe each model. No public model-name
210
213
  heuristic or original-vendor limit is applied to an arbitrary relay deployment.
214
+ The managed Codex catalog uses an explicitly declared input modality in preference
215
+ to the native template. Unknown modalities retain the existing template fallback.
216
+ For GitHub models, fast/priority tiers are shown only when the full source catalog
217
+ supports the existing priority route, including an eligible fast variant that is
218
+ not itself selected in the model picker.
211
219
 
212
220
  Claude configuration and gateway catalogs use the same compiled model plan.
213
221
  Explicit App bindings use opaque source-qualified aliases and actual model/source
@@ -274,7 +282,7 @@ CLI-only interaction forms include JSON output, file input, key stdin and shell
274
282
 
275
283
  ## Prediction controls
276
284
 
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.
285
+ 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
286
 
279
287
  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
288
 
@@ -580,7 +588,7 @@ was recreated on the original address, not that gray text appeared.
580
588
 
581
589
  ## Error delivery and conversation commits
582
590
 
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.
591
+ 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.
584
592
 
585
593
  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
594
 
@@ -590,13 +598,15 @@ The native image host uses the current CCDX address for separate Images API requ
590
598
 
591
599
  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.
592
600
 
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.
601
+ 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.
602
+
603
+ 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.
594
604
 
595
605
  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
606
 
597
607
  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
608
 
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.
609
+ 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.
600
610
 
601
611
  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:
602
612
 
@@ -749,6 +759,8 @@ Downstream backpressure waits also observe cancellation and the stream deadline.
749
759
 
750
760
  Successful streaming responses are accepted only when the upstream body is SSE and reaches its protocol terminal event. Unexpected EOF becomes a protocol-native stream error, and repeated blank tool-argument deltas are stopped per tool call. Allowlisted rate-limit, retry, model, trace, and upstream request-ID metadata are forwarded; cookies, authorization, body-length, and encoding headers are not.
751
761
 
762
+ Responses, Chat fallback, Messages and local response restoration accept LF, CRLF and CR SSE line endings. Existing comment heartbeats, upstream timeouts, retry eligibility, output and usage remain unchanged.
763
+
752
764
  CCDX keeps each native Responses message on its first upstream ID when Copilot changes that ID during streaming. Message deltas, completion events, and cached history stay consistent, addressing this cause of duplicate live messages in Codex App. Tool identities, reasoning/encrypted content, message phases, and speed-tier routing are unchanged by this ID normalization. Stable events retain their original SSE bytes; changed events are rewritten with bounded, backpressured streaming.
753
765
 
754
766
  Newer Codex App builds can advertise an `image_gen` namespace that already exists upstream. CCDX removes that exact conflicting client tool before forwarding and retries once only when Copilot explicitly reports an image namespace collision. Image input and screenshot optimization remain enabled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.3.18",
3
+ "version": "1.3.20",
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",
package/src/adapter.mjs CHANGED
@@ -237,7 +237,7 @@ export function createAdapterHandler(options = {}) {
237
237
  });
238
238
  const responsesHandler = createResponsesHandler({
239
239
  privacy,
240
- validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
240
+ validateConversation: (body, headers, source, signal) => options.providerRuntime?.validateConversation?.(body, headers, source, signal),
241
241
  resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
242
242
  providerPreference: id => options.providerRuntime?.providerPreference?.(id),
243
243
  provider: options.provider || options.providerRuntime?.github,
@@ -260,7 +260,7 @@ export function createAdapterHandler(options = {}) {
260
260
  });
261
261
  const responsesCompactHandler = createResponsesCompactHandler({
262
262
  privacy,
263
- validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
263
+ validateConversation: (body, headers, source, signal) => options.providerRuntime?.validateConversation?.(body, headers, source, signal),
264
264
  resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
265
265
  providerPreference: id => options.providerRuntime?.providerPreference?.(id),
266
266
  provider: options.provider || options.providerRuntime?.github,
@@ -282,7 +282,7 @@ export function createAdapterHandler(options = {}) {
282
282
  if (!provider || provider.id === "github") return githubHandlers;
283
283
  if (!providerHandlers.has(provider)) {
284
284
  const common = { provider, privacy, acquireRequest, imagePressure, keepaliveIntervalMs: options.keepaliveIntervalMs,
285
- validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
285
+ validateConversation: (body, headers, source, signal) => options.providerRuntime?.validateConversation?.(body, headers, source, signal),
286
286
  resolveProvider: (body, req) => options.providerRuntime?.resolveCodex?.(body, req),
287
287
  providerPreference: id => options.providerRuntime?.providerPreference?.(id),
288
288
  modelRegistry: provider.registry, now: options.now, openAIModelEnv: { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" },
@@ -26,6 +26,12 @@ export function inspectClaudeCapabilitySupport({ platform = process.platform, en
26
26
  return { app_version: appVersion || null, app: /^[34]\./.test(appVersion || ""), code_version: codeVersion || null, code: /^2\.1\./.test(codeVersion || "") && Number(codeVersion.split(".")[2]) >= 293 };
27
27
  }
28
28
 
29
+ export function claudeSupportForSync(support, observations) {
30
+ const rows = Array.isArray(observations?.claude) ? observations.claude : [];
31
+ const app = rows.find(entry => entry.id === "claude_system_claude");
32
+ return observations?.claude_unrecognized === true || app?.version && !/^[34]\./.test(app.version) ? { ...support, app: false } : support;
33
+ }
34
+
29
35
  export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} } = {}) {
30
36
  const limitations = [], budgets = {}, caps = [], consumers = [...app.map(model => ({ model, app: true })), ...code.map(model => ({ model, app: false }))];
31
37
  let context = 0, output = 0, safeContext = consumers.length > 0, knownAdapters = true;
@@ -51,6 +51,7 @@ function authenticated(headers, key) {
51
51
  // other frames retain their wire text. Client backpressure controls upstream reads.
52
52
  export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clientModel = null) {
53
53
  const decoder = new TextDecoder("utf-8", { fatal: true });let fragments = [], lineBytes = 0, data = [], frameBytes = 0, wire = [], wireBytes = 0, output = [];
54
+ let pendingCR = false, bareCR = false, optionalLF = false;
54
55
  const frame = () => {
55
56
  let value;
56
57
  if (data.length) { try { value = JSON.parse(data.join("\n")); } catch { throw new Error("Invalid Claude stream event"); }onEvent(value); }
@@ -60,16 +61,16 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
60
61
  wire = wire.map(line => {
61
62
  if (!line.startsWith("data:")) return line;
62
63
  if (replaced) return "";replaced = true;
63
- return `data: ${replacement}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : ""}`;
64
+ return `data: ${replacement}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : line.endsWith("\r") ? "\r" : ""}`;
64
65
  });
65
66
  }
66
67
  output.push(Buffer.from(wire.join("")));wire = [];wireBytes = 0;
67
68
  }
68
69
  data = [];frameBytes = 0;
69
70
  };
70
- const line = (value, newline = true) => {
71
+ const line = (value, newline = true, bytes) => {
71
72
  {
72
- wireBytes += Buffer.byteLength(value) + (newline ? 1 : 0);
73
+ wireBytes += (bytes ?? Buffer.byteLength(value)) + (newline ? 1 : 0);
73
74
  if (wireBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");
74
75
  wire.push(value + (newline ? "\n" : ""));
75
76
  }
@@ -87,19 +88,63 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
87
88
  if (frameBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");data.push(part);
88
89
  }
89
90
  };
91
+ const completeLine = ending => { line(fragments.join("") + (ending.startsWith("\r") ? "\r" : ""), ending.endsWith("\n"));fragments = [];lineBytes = 0; };
90
92
  function consume(text) {
91
93
  let start = 0;
94
+ if (!bareCR && text.length) {
95
+ const tailCR = fragments.at(-1)?.endsWith("\r") === true;
96
+ if (tailCR && text[0] !== "\n") {
97
+ bareCR = true;
98
+ fragments[fragments.length - 1] = fragments.at(-1).slice(0, -1);lineBytes--;
99
+ completeLine("\r");
100
+ }
101
+ }
102
+ if (!bareCR) {
103
+ let nextCR = text.indexOf("\r", start);
104
+ while (start < text.length) {
105
+ const newline = text.indexOf("\n", start), end = newline < 0 ? text.length : newline, part = text.slice(start, end);
106
+ if (nextCR >= 0 && nextCR < end - 1) { bareCR = true;break; }
107
+ lineBytes += Buffer.byteLength(part);
108
+ if (lineBytes > maxBytes || wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
109
+ fragments.push(part);
110
+ if (newline < 0) break;
111
+ line(fragments.length === 1 ? fragments[0] : fragments.join(""), true, lineBytes);
112
+ fragments = [];lineBytes = 0;start = newline + 1;
113
+ if (nextCR >= 0 && nextCR === end - 1) nextCR = text.indexOf("\r", start);
114
+ }
115
+ if (!bareCR) return;
116
+ }
117
+ if (optionalLF) {
118
+ optionalLF = false;
119
+ if (text.startsWith("\n")) { output.push(Buffer.from("\n"));start = 1; }
120
+ }
121
+ if (pendingCR && start < text.length) {
122
+ pendingCR = false;
123
+ if (text[start] === "\n") { completeLine("\r\n");start++; }
124
+ else { bareCR = true;completeLine("\r"); }
125
+ }
92
126
  while (start < text.length) {
93
- const newline = text.indexOf("\n", start), end = newline < 0 ? text.length : newline, part = text.slice(start, end);
127
+ const lf = text.indexOf("\n", start), cr = text.indexOf("\r", start);
128
+ const end = lf < 0 ? (cr < 0 ? text.length : cr) : cr < 0 ? lf : Math.min(lf, cr);
129
+ const part = text.slice(start, end);
94
130
  lineBytes += Buffer.byteLength(part);
95
131
  if (lineBytes > maxBytes || wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
96
132
  fragments.push(part);
97
- if (newline < 0) break;
98
- line(fragments.join(""));fragments = [];lineBytes = 0;start = newline + 1;
133
+ if (end === text.length) break;
134
+ if (text[end] === "\n") { completeLine("\n");start = end + 1;continue; }
135
+ if (end + 1 === text.length) {
136
+ if (bareCR && lineBytes === 0) { completeLine("\r");optionalLF = true; }
137
+ else pendingCR = true;
138
+ break;
139
+ }
140
+ if (text[end + 1] === "\n") { completeLine("\r\n");start = end + 2; }
141
+ else { bareCR = true;completeLine("\r");start = end + 1; }
99
142
  }
100
143
  }
101
144
  return { write(chunk) { output = [];consume(decoder.decode(chunk, { stream: true }));return output; },
102
- finish() { output = [];consume(decoder.decode());if (fragments.length) line(fragments.join(""), false);if (wire.length && !/\r?\n\r?\n$/.test(wire.join(""))) wire.push("\n\n");frame();return output; } };
145
+ finish() { output = [];consume(decoder.decode());if (pendingCR) { pendingCR = false;completeLine("\r"); }
146
+ if (!bareCR && fragments.at(-1)?.endsWith("\r")) { fragments[fragments.length - 1] = fragments.at(-1).slice(0, -1);lineBytes--;completeLine("\r"); }
147
+ if (fragments.length) completeLine("");if (wire.length) wire.push("\n\n");frame();return output; } };
103
148
  }
104
149
 
105
150
  export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
@@ -179,7 +224,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
179
224
  if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
180
225
  terminalOrigin = "transport";
181
226
  const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
227
+ let upstreamHeadersObserved = false;
182
228
  const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
229
+ onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
183
230
  onCountObservation(value) {
184
231
  context.countObservation = { ...context.countObservation, ...value };
185
232
  if (value.upstream) { context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;tracker?.upstreamStarted(false); }
@@ -201,7 +248,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
201
248
  } else upstream = await call(body, callOptions);
202
249
  body = null;
203
250
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
204
- tracker?.upstreamHeaders(upstream.status);
251
+ if (!upstreamHeadersObserved) tracker?.upstreamHeaders(upstream.status);
205
252
  release();release = () => {};
206
253
  try { onRequest({ client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude" }); } catch {}
207
254
  const headers = safeUpstreamResponseHeaders(upstream.headers);
@@ -217,7 +264,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
217
264
  const evidence = upstreamErrorEvidence(raw);
218
265
  context.onHttpError?.({ ...evidence, code: evidence.code || evidence.error_type || "upstream_error", model_error: true, origin: "upstream_response", headers: upstream.headers });
219
266
  }
220
- if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
267
+ if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw, { status: upstream.status }),
221
268
  origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
222
269
  if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
223
270
  if (value.content.some(hasMessageState)) await conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
@@ -0,0 +1,139 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { atomicWriteFile } from "./atomic-file.mjs";
5
+ import { readBoundedFile } from "./bounded-file.mjs";
6
+ import { userSettingsPath } from "./user-settings.mjs";
7
+
8
+ const MAX_METADATA_BYTES = 64 * 1024;
9
+ const validVersion = value => typeof value === "string" && /^[0-9][0-9A-Za-z.+_-]{0,63}$/.test(value);
10
+ const optionalVersion = value => value == null || validVersion(value);
11
+ const validDate = value => value == null || typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(value);
12
+ const fields = (value, allowed) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => allowed.includes(key));
13
+ const validEntry = value => fields(value, ["version", "build", "cli_version", "previous", "changed_at"])
14
+ && validVersion(value.version) && optionalVersion(value.build) && optionalVersion(value.cli_version)
15
+ && validDate(value.changed_at) && (value.previous == null || fields(value.previous, ["version", "build", "cli_version"])
16
+ && validVersion(value.previous.version) && optionalVersion(value.previous.build) && optionalVersion(value.previous.cli_version));
17
+ const changed = (left, right) => left.version !== right.version
18
+ || Boolean(left.build && right.build && left.build !== right.build)
19
+ || Boolean(left.cli_version && right.cli_version && left.cli_version !== right.cli_version);
20
+ const sameFile = (left, right) => left.size === right.size && left.mtimeMs === right.mtimeMs && left.ino === right.ino && left.dev === right.dev;
21
+ const installed = value => ({ version: value.version, build: value.build || null, cli_version: value.cli_version || null });
22
+ const tag = (text, key) => new RegExp(`<key>${key}</key>\\s*<(string|integer)>([^<]+)</\\1>`).exec(text)?.[2]?.trim();
23
+
24
+ async function stableRead(file) {
25
+ const before = await fs.stat(file), data = await readBoundedFile(file, { maxBytes: MAX_METADATA_BYTES, encoding: "utf8" }), after = await fs.stat(file);
26
+ if (!sameFile(before, after)) throw new Error("App metadata changed during inspection");
27
+ return { data, identity: after };
28
+ }
29
+
30
+ async function macBundle(root, scope, name, client) {
31
+ const bundle = path.join(root, name), infoPath = path.join(bundle, "Contents", "Info.plist"), info = await stableRead(infoPath), plist = info.data;
32
+ const expected = client === "codex" ? "com.openai.codex" : "com.anthropic.claudefordesktop";
33
+ const version = tag(plist, "CFBundleShortVersionString"), build = tag(plist, "CFBundleVersion");
34
+ if (tag(plist, "CFBundleIdentifier") !== expected || !validVersion(version) || !optionalVersion(build)) return null;
35
+ let cliVersion = null;
36
+ if (client === "codex") try {
37
+ const metadata = JSON.parse((await stableRead(path.join(bundle, "Contents", "Resources", "codex-cli", "codex-package.json"))).data);
38
+ if (validVersion(metadata.version)) cliVersion = metadata.version;
39
+ } catch { /* Older App bundles need not provide CLI metadata. */ }
40
+ if (client === "codex" && !sameFile(info.identity, await fs.stat(infoPath))) return null;
41
+ return { id: `${client}_${scope}_${name.slice(0, -4).toLowerCase()}`, name, client, scope, version, build: build || null, cli_version: cliVersion };
42
+ }
43
+
44
+ export async function inspectInstalledClientVersions({ home = os.homedir(), env = process.env, platform = process.platform,
45
+ systemApplications = "/Applications", windowsCodexVersion } = {}) {
46
+ if (platform === "darwin") {
47
+ const roots = [["system", systemApplications], ["user", path.join(home, "Applications")]], jobs = [];
48
+ for (const [scope, root] of roots) for (const [name, client] of [["ChatGPT.app", "codex"], ["Codex.app", "codex"], ["Claude.app", "claude"]]) {
49
+ jobs.push(macBundle(root, scope, name, client).catch(() => null));
50
+ }
51
+ return (await Promise.all(jobs)).filter(Boolean);
52
+ }
53
+ if (platform === "win32") {
54
+ const inspect = windowsCodexVersion || (await import("./native-prediction-windows.mjs")).inspectWindowsCodexVersion;
55
+ const version = await inspect({ env }).catch(() => null);
56
+ return validVersion(version) ? [{ id: "codex_windows_codex", name: "Codex", client: "codex", scope: "windows", version, build: null, cli_version: null }] : [];
57
+ }
58
+ return [];
59
+ }
60
+
61
+ export function createClientVersionMonitor({ home = os.homedir(), env = process.env, platform = process.platform,
62
+ inspect = inspectInstalledClientVersions, persist = true, timeoutMs = 3000, now = Date.now, onChange = () => {}, ...options } = {}) {
63
+ const file = path.join(path.dirname(userSettingsPath({ home, env })), "client-versions.json");
64
+ let saved, writable = true, flight = null, closed = false;
65
+ let state = { checked_at: null, codex: [], claude: [], claude_unrecognized: false, persistence: "unknown" };
66
+ const snapshot = () => structuredClone(state);
67
+ async function load() {
68
+ if (saved) return saved;
69
+ try {
70
+ const value = JSON.parse(await readBoundedFile(file, { maxBytes: MAX_METADATA_BYTES, encoding: "utf8" }));
71
+ if (!fields(value, ["version", "apps"]) || value.version !== 1 || !value.apps || typeof value.apps !== "object" || Array.isArray(value.apps)
72
+ || Object.entries(value.apps).length > 7 || Object.entries(value.apps).some(([id, entry]) =>
73
+ !/^(?:codex|claude)_(?:system|user|windows)_(?:chatgpt|codex|claude)$/.test(id) || !validEntry(entry))) throw new Error("Invalid saved App versions");
74
+ saved = value.apps;
75
+ } catch (error) {
76
+ if (error.code !== "ENOENT") writable = false;
77
+ saved = {};
78
+ }
79
+ return saved;
80
+ }
81
+ async function run() {
82
+ const baseline = await load(), rows = await inspect({ home, env, platform, ...options });
83
+ if (!Array.isArray(rows) || rows.length > 7) throw new Error("Invalid App version results");
84
+ const at = new Date(now()).toISOString(), next = { ...baseline }, updates = [];
85
+ const groups = { codex: [], claude: [] };
86
+ for (const row of rows) {
87
+ if (!/^(?:codex|claude)_(?:system|user|windows)_(?:chatgpt|codex|claude)$/.test(row.id || "")
88
+ || !["codex", "claude"].includes(row.client) || !validVersion(row.version) || !optionalVersion(row.build) || !optionalVersion(row.cli_version)) continue;
89
+ const current = installed(row), previous = baseline[row.id];let entry;
90
+ if (!previous) entry = { ...current, previous: null, changed_at: null };
91
+ else if (changed(previous, current)) {
92
+ entry = { ...current, previous: installed(previous), changed_at: at };updates.push(row.client);
93
+ } else entry = { ...current, build: current.build || previous.build || null, cli_version: current.cli_version || previous.cli_version || null,
94
+ previous: previous.previous || null, changed_at: previous.changed_at || null };
95
+ next[row.id] = entry;
96
+ groups[row.client].push({ id: row.id, name: row.name, scope: row.scope, ...entry, ...current, first_observed: !previous });
97
+ }
98
+ if (closed) return snapshot();
99
+ const modified = JSON.stringify(next) !== JSON.stringify(baseline);
100
+ saved = next;
101
+ const observed = { checked_at: at, ...groups, claude_unrecognized: Boolean(next.claude_system_claude?.version && !/^[34]\./.test(next.claude_system_claude.version)) };
102
+ state = { ...observed, persistence: persist ? writable && modified ? "pending" : writable ? "saved" : "unavailable" : "read_only" };
103
+ if (updates.length) try { onChange([...new Set(updates)], snapshot()); } catch { /* Display only. */ }
104
+ if (persist && writable && modified) try {
105
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
106
+ if (!closed) await atomicWriteFile(file, `${JSON.stringify({ version: 1, apps: next })}\n`, { mode: 0o600, preserveMode: false });
107
+ } catch { writable = false; }
108
+ if (!closed) state = { ...observed, persistence: persist ? writable ? "saved" : "unavailable" : "read_only" };
109
+ return snapshot();
110
+ }
111
+ function refresh() {
112
+ if (closed) return Promise.resolve(snapshot());
113
+ if (flight) return flight.result;
114
+ let timer, task;
115
+ const work = Promise.resolve().then(run);
116
+ const timeout = new Promise(resolve => { timer = setTimeout(() => resolve(null), timeoutMs); });
117
+ const result = Promise.race([work, timeout]).then(value => {
118
+ if (value) return value;
119
+ state = { ...state, checked_at: new Date(now()).toISOString(), codex: [], claude: [], persistence: "unavailable" };
120
+ return snapshot();
121
+ }).catch(() => {
122
+ state = { ...state, checked_at: new Date(now()).toISOString(), codex: [], claude: [], persistence: "unavailable" };
123
+ return snapshot();
124
+ }).finally(() => clearTimeout(timer));
125
+ task = { result };flight = task;
126
+ work.finally(() => { if (flight === task) flight = null; }).catch(() => {});
127
+ return result;
128
+ }
129
+ return { snapshot, refresh, close() { closed = true; } };
130
+ }
131
+
132
+ export function clientVersionChecks(snapshot) {
133
+ return ["codex", "claude"].map(client => {
134
+ const rows = snapshot?.[client] || [], name = client === "codex" ? "Codex App" : "Claude App";
135
+ if (!rows.length) return { id: "client-versions", kind: "info", message: `${name}: installed version not observed` };
136
+ const versions = rows.map(row => `${row.name} ${row.version}${row.build ? ` (build ${row.build})` : ""}${row.cli_version ? `, CLI ${row.cli_version}` : ""}${row.changed_at ? `, changed ${row.changed_at}` : ""}`).join("; ");
137
+ return { id: "client-versions", kind: "info", message: `${name}: ${versions}. Running version and feature compatibility are not confirmed` };
138
+ });
139
+ }
@@ -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) {