codex-copilot-dx 1.2.12 → 1.2.14

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.
Files changed (43) hide show
  1. package/README.md +14 -14
  2. package/bin/cli.mjs +12 -8
  3. package/docs/ARCHITECTURE.md +54 -5
  4. package/docs/REFERENCE.md +91 -1
  5. package/package.json +2 -2
  6. package/src/access-settings.mjs +98 -0
  7. package/src/adapter.mjs +19 -7
  8. package/src/api-secrets.mjs +69 -0
  9. package/src/auto-review-model.mjs +4 -3
  10. package/src/claude-client-config.mjs +16 -11
  11. package/src/claude-gateway.mjs +11 -8
  12. package/src/cli-m365.mjs +48 -8
  13. package/src/cli-models.mjs +2 -1
  14. package/src/cli-options.mjs +1 -1
  15. package/src/cli-status.mjs +1 -1
  16. package/src/client-gateway-keys.mjs +29 -0
  17. package/src/codex-api-config.mjs +51 -0
  18. package/src/connection-runtime.mjs +289 -0
  19. package/src/conversation-source-guard.mjs +42 -0
  20. package/src/dashboard/connections.js +182 -0
  21. package/src/dashboard/console.js +6 -4
  22. package/src/dashboard/flow.js +4 -4
  23. package/src/dashboard/index.html +43 -0
  24. package/src/dashboard/language.js +85 -2
  25. package/src/dashboard/status.js +1 -1
  26. package/src/dashboard/ui.css +24 -0
  27. package/src/dashboard/ui.js +4 -2
  28. package/src/dashboard-api.mjs +19 -4
  29. package/src/dashboard.mjs +1 -0
  30. package/src/optional-routes.mjs +2 -2
  31. package/src/private-helper-environment.mjs +7 -0
  32. package/src/provider-management.mjs +1 -1
  33. package/src/provider-runtime.mjs +37 -5
  34. package/src/providers/api-network.mjs +51 -0
  35. package/src/providers/api.mjs +129 -0
  36. package/src/proxy-tunnel.mjs +6 -4
  37. package/src/responses-handler.mjs +6 -4
  38. package/src/startup-ui.mjs +9 -0
  39. package/src/stream-performance.mjs +7 -6
  40. package/src/terminal-console.mjs +1 -1
  41. package/src/usage-store.mjs +1 -1
  42. package/src/windows-http-network.mjs +11 -6
  43. package/src/windows-prediction-network.cs +6 -4
package/README.md CHANGED
@@ -1,9 +1,6 @@
1
1
  # codex-copilot-dx
2
2
 
3
- Use Codex App with GitHub Copilot through a local adapter, with isolated Microsoft 365 access where authorized.
4
-
5
- CCDX keeps GitHub Copilot as the default Codex source: discovery, adapted model catalogs, Responses streaming, tool calls and conversation history. Eligible Microsoft 365 environments can also use a protocol-isolated Claude gateway on the main listener and manually select M365 as a Codex backup.
6
- Default Auto-review: **GPT-6.1 Sol / low**. Image generation is **off by default**. Native predictions are also **off by default**.
3
+ CCDX connects Codex App to GitHub Copilot by default: discovery, adapted model catalogs, Responses streaming, tool calls and conversation history. Eligible Microsoft 365 environments can also use a protocol-isolated Claude gateway on the main listener and manually select M365 as a Codex backup. Default Auto-review: **GPT-6.1 Sol / low**. Image generation is **off by default**. Native predictions are also **off by default**.
7
4
 
8
5
  ## Install and run
9
6
 
@@ -14,18 +11,13 @@ npm install -g codex-copilot-dx@latest
14
11
  ccdx
15
12
  ```
16
13
 
17
- No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.12/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.12/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
14
+ No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.14/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.14/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
18
15
 
19
16
  CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
20
17
 
21
- The [local control console](http://127.0.0.1:2026/) separates Overview, indented Codex/Claude pages, Model sources, Usage, Requests, Checks & repairs and Settings. Its sticky header stays stable across modules; page switches return to the top, while refreshes preserve scroll. Codex owns source/model, Auto Review, images, input suggestions and conversation buffering, with request performance separate from maintenance. Model sources owns accounts, catalogs and M365 access; browsing never changes routing. Claude shows each app's setup separately and labels combined Messages performance. Checks & repairs owns runtime diagnostics; Settings keeps appearance, startup and updates. Usage offers animated bars (default) or curves with scoped filters and no extra requests; reduced motion stays static. Trends load on demand. Recent requests open by default, with technical metadata folded into each row. Overview and the live terminal share an approximate token cache hit rate, preserving partial/unknown states. Overview's six activity dots share status polling; only idle has a breathing halo, failed or six-second-old evidence is unknown, and short requests can fall between snapshots. The existing style and logo remain. System proxy exceptions accept shortened IPv4 networks; M365 network failures retain specific, redacted reasons.
22
-
23
- Startup shows bounded checks, sources with discovered model lists and Claude Code/App configuration. Prediction normally uses one summary line; `ccdx prediction status` retains recovery and environment details. After Ready, an interactive terminal shows current source/Claude state and a line-framed table of this process's returned usage and inference counters. Notices and activity each have their own line; individual requests do not scroll. Input includes reused input tokens. `ccdx --verbose` (also `--show-request-id`, or debug logging) retains detail output; optional file logging remains independently controlled. Source and Claude summaries wrap on narrow terminals. Failed reads show previous-data status and the last successful update time. Non-TTY, CI, dumb, or terminals too small for the full region use plain output (at least 40 columns / 16 rows are required). `Ready` only means the core service is available; discovered catalogs and configured clients do not prove inference access.
18
+ The [local control console](http://127.0.0.1:2026/) separates Overview, Codex/Claude, Model sources, Usage, Requests, Checks & repairs and Settings, with a stable sticky header. Settings owns API/client access, independent web/terminal colors (classic green, Klein blue or Soft pink), startup and updates. Accounts and model catalogs stay with Model sources; client-specific tools stay with their application. CLI remains English; WebUI supports English/Chinese. An interactive terminal shows bounded startup checks, source/client state, a usage table with approximate cache hit rate, notices and animation. Plain/NO_COLOR/narrow output remains supported; `--verbose` retains request detail.
24
19
 
25
- WebUI settings apply animation choices live, pause/resume configured image calls and prediction adaptation without removing credentials/trust, change the Codex source explicitly, and manage the conversation-buffer limit. Saved preference and effective state are separate; browser opening is labeled for the next start. Clearing the conversation buffer clears **all** buffered continuations. Busy cleanup is refused; retry after active requests finish. Saved Codex transcripts are retained. First-time image/prediction setup still uses the existing CLI; trust, client routing and cached client capabilities may require a normal App relaunch. Busy M365 requests must finish before disabling that provider. Settings also offers independent webpage/terminal colors: classic green (default), Klein blue or Soft pink. Web colors stay in this browser; terminal colors persist locally. Failed saves are reported. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings).
26
-
27
- While visible and auto-refresh is on, the console reads the small status snapshot about every two seconds and source/settings evidence about every 16 seconds. Catalogs and retained usage are fetched on demand and at most once per 30-minute refresh interval while their view is open. Hidden pages stop scheduled reads. First output uses **ms**, estimated speed **token/s**, and each protocol has its own samples. HTTP traffic includes catalog and routing requests; it is not a conversation count.
28
- The **Requests** view shows live app/source/model flow above the source summary and finished records. Motion follows observed output; waiting, retries, idle and expired status stay distinct. Single routes stay straight; concurrent counts sit beside names. Name selections filter active details only. Codex client hints are recognized conservatively; unknown apps stay unidentified. Codex/Claude performance includes approximate first-output P50/P95 with sample counts. CLI stays English; WebUI keeps both languages and the existing palettes. See [1.2.12 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.12.md) and the [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md).
20
+ Requests shows live app/source/model flow above existing summaries and finished records. Usage offers animated bars or curves; reduced motion stays static. Hidden pages stop scheduled reads; status refreshes about every two seconds and source/settings evidence about every 16 seconds. Catalogs and retained usage load on demand or every 30 minutes while open. The UI does not add inference calls. Ready means local service availability, not verified model access. First output uses ms, speed token/s, and partial/unknown usage remains explicit. Images/predictions stay opt-in; their first setup uses CLI. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings), [1.2.14 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.14.md) and [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md).
29
21
 
30
22
  ## Commands
31
23
  | Command | Purpose |
@@ -40,7 +32,7 @@ The **Requests** view shows live app/source/model flow above the source summary
40
32
  | `ccdx doctor config` | Read-only configuration check |
41
33
  | `ccdx doctor --compat` | Online inference/continuation compatibility probes |
42
34
  | `ccdx auth status` / `login` / `reauth` / `check` / `logout` | Inspect, verify or safely replace CCDX sign-in; other apps stay signed in |
43
- | `ccdx models` | Fresh upstream model list |
35
+ | `ccdx models` | Current source models; manual APIs show configured models without an online probe |
44
36
  | `ccdx usage` | Recorded tokens and upstream prompt-cache hit rate |
45
37
  | `ccdx usage --provider ID` | Filter current or historical source-specific usage |
46
38
  | `ccdx m365 status` / `models` | M365 authorization, Claude gateway and Claude models |
@@ -58,6 +50,14 @@ The **Requests** view shows live app/source/model flow above the source summary
58
50
  | `ccdx prediction on` / `off` / `status` | Opt in to native predictions (macOS and Windows) |
59
51
  | `ccdx update` | Update the global package |
60
52
 
53
+ ## Add your own API
54
+
55
+ Run `ccdx web` without GitHub sign-in. In **Settings → Model sources → Add API**, enter the HTTPS address/key and declare each model's real interfaces. Save, allow clients, then choose their **Current source** under **Clients**. Claude App/Code use Messages; Codex uses Responses, all on port 2026. Reopen clients for first setup and start a new conversation after source/key changes. To use Claude alone, close Codex access. Stop management before normal `ccdx` startup for the live terminal.
56
+
57
+ Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving does not probe models or select routes. Disabled sources/clients leave normal views and can be restored from **Disabled**, retaining grants/configuration without selecting a source. Closing client access does not quit its app. In-use sources require explicit replacements or pauses; pinned API requests finish on their original source. Existing user/managed app settings remain protected.
58
+
59
+ There is no automatic fallback, cross-source replay or Chat-only protocol conversion. Configured models are not verified online entitlement; unknown models have conservative metadata. No runtime dependency or enterprise policy exception is added. See the [complete API, credential and client reference](docs/REFERENCE.md#manual-apis-and-client-access).
60
+
61
61
  ## Microsoft 365 access
62
62
 
63
63
  Eligible macOS/Windows machines attempt silent Microsoft authorization at startup, without Copilot CLI or a browser login. MDM alone is insufficient: account, tenant,
@@ -66,7 +66,7 @@ device policy and Loki entitlement must permit access. Optional failure does not
66
66
  Claude clients use `http://127.0.0.1:2026/anthropic` (or the configured main port), a private local gateway key and a Claude-only catalog. No second Claude listener is opened. Existing unchanged CCDX-owned 2027 addresses migrate automatically; hand-written or managed addresses are preserved and need explicit migration. The optional prediction CONNECT/PAC bridge remains a separate transport.
67
67
  Existing custom/managed settings are preserved; already-running clients may need a normal restart.
68
68
  Canonical Claude IDs and advertised effort caps refresh only in unchanged CCDX-owned settings. User and managed choices are preserved; supported App versions can update model knowledge through Anthropic's signed catalog. New protocol semantics may require a client or CCDX update. See the [model reference](docs/REFERENCE.md#claude-gateway-and-client-ownership).
69
- `ccdx m365 off` restores unchanged owned fields; `remove` also clears owned M365 state.
69
+ `ccdx m365 off` restores unchanged owned fields; `remove` also clears owned M365 state. With managed client connections, off pauses affected bindings instead of selecting another source; removal retains shared client-ownership records needed by manual APIs.
70
70
 
71
71
  Codex stays on GitHub until `ccdx m365 switch`. Select available GPT/review models;
72
72
  there is no automatic failover or missing-model substitution. Use **Standard** on M365:
package/bin/cli.mjs CHANGED
@@ -364,7 +364,8 @@ async function reuseRunningAdapterIfAvailable() {
364
364
  const serviceStatus = readAdapterStatus({ host: ADAPTER_HOST, port: ADAPTER_PORT }).catch(() => null);
365
365
  console.log(startupCheck("ok", "Service", `Using running service: ${running.baseUrl}`));
366
366
  console.log(startupCheck("info", "Sign-in", "Using saved sign-in; not rechecked"));
367
- const { compressionSetup, imageEnabled, imageMcpSkipped } = await configureCodexClient();
367
+ const codexEnabled = (await serviceStatus)?.data?.providers?.connections?.clients?.find(client => client.id === "codex")?.enabled !== false;
368
+ const { compressionSetup, imageEnabled, imageMcpSkipped } = codexEnabled ? await configureCodexClient() : { compressionSetup: Promise.resolve(), imageEnabled: false, imageMcpSkipped: false };
368
369
 
369
370
  let predictionPacUrl = null;
370
371
  let predictionApp = null;
@@ -376,7 +377,7 @@ async function reuseRunningAdapterIfAvailable() {
376
377
  const { readPredictionSettings } = await import("../src/native-prediction-profile.mjs");
377
378
  const preference = readPredictionSettings();
378
379
  predictionConfigured = preference.enabled;
379
- if (preference.enabled) {
380
+ if (preference.enabled && codexEnabled) {
380
381
  predictionPacUrl = running.data?.native_prediction_pac || null;
381
382
  predictionApp = preference.app?.app;
382
383
  predictionProfile = preference.app?.profile;
@@ -386,7 +387,7 @@ async function reuseRunningAdapterIfAvailable() {
386
387
  if (!predictionPacUrl) console.warn(status("warn", "Restart ccdx to activate the newly enabled prediction bridge"));
387
388
  }
388
389
  } catch (error) { console.warn(status("warn", error.message)); }
389
- await openCodex({ predictionPacUrl, predictionApp, predictionProfile, persistedPredictionRoute,
390
+ if (codexEnabled) await openCodex({ predictionPacUrl, predictionApp, predictionProfile, persistedPredictionRoute,
390
391
  onPredictionRoute: route => { launchRoute = route; }, log: startupLogger("App") });
391
392
  console.log(predictionStartupCheck({ configured: predictionConfigured, bridge: predictionPacUrl ? "running" : "unknown", launch_route: launchRoute }));
392
393
  console.log(startupCheck(imageEnabled && imageMcpSkipped ? "warn" : "info", "Images", imageEnabled
@@ -449,7 +450,6 @@ try {
449
450
  // Restore the opted-in listener alongside authentication/model initialization;
450
451
  // a slow company-proxy setup must not delay the core listener.
451
452
  const earlyIntegration = await clientIntegrations();
452
- const predictionSetup = runInBackground(() => earlyIntegration.start());
453
453
 
454
454
  let profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient });
455
455
  let startupComplete = false;
@@ -463,15 +463,19 @@ try {
463
463
  });
464
464
  providerRuntime = createProviderRuntime({ githubClient: profileRuntime.codexClient, githubRegistry: profileModels.codexRegistry,
465
465
  corePort: ADAPTER_PORT,
466
+ clientAccessChanged: async enabled => { earlyIntegration.setPredictionActive(enabled && servicePreferences().prediction_enabled);if (enabled) await earlyIntegration.configure(); },
466
467
  githubCredentialFingerprint: () => profileRuntime.codexCredentialFingerprint,
467
468
  log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "M365", message)) });
469
+ const codexEnabled = providerRuntime.connections().clients.find(client => client.id === "codex").enabled;
470
+ const predictionSetup = codexEnabled ? runInBackground(() => earlyIntegration.start()) : Promise.resolve(null);
468
471
  const m365Setup = runInBackground(() => providerRuntime.start());
469
472
  if (providerRuntime.selection().codex === "github") {
470
473
  try { await ensureAuth({ log: startupLogger("Sign-in") }); }
471
474
  catch (error) { console.warn(startupCheck("warn", "Sign-in", "Sign-in unavailable. Use the dashboard or ccdx auth login; saved credentials kept.")); }
472
475
  } else {
473
- await m365Setup;
474
- console.log(startupCheck("info", "Source", "Codex source: Microsoft 365"));
476
+ if (providerRuntime.selection().codex === "m365") await m365Setup;
477
+ const source = providerRuntime.connections().providers.find(source => source.id === providerRuntime.selection().codex);
478
+ console.log(startupCheck("info", "Source", source ? `Codex source: ${source.name}` : "Codex access off"));
475
479
  }
476
480
  profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient });
477
481
 
@@ -515,14 +519,14 @@ try {
515
519
  });
516
520
 
517
521
  // Point Codex App at the adapter.
518
- const { compressionSetup, imageEnabled, imageMcpSkipped } = await configureCodexClient();
522
+ const { compressionSetup, imageEnabled, imageMcpSkipped } = codexEnabled ? await configureCodexClient() : { compressionSetup: Promise.resolve(), imageEnabled: false, imageMcpSkipped: false };
519
523
 
520
524
  // Optional native prediction setup must never prevent the core adapter from running.
521
525
  nativePrediction = await predictionSetup;
522
526
  const persistentRoute = await nativePrediction?.prepareRoute();
523
527
 
524
528
  // Launch Codex when available. A running App is never forcibly restarted.
525
- await openCodex({ predictionPacUrl: nativePrediction?.pacUrl, predictionApp: nativePrediction?.app, predictionProfile: nativePrediction?.profile,
529
+ if (codexEnabled) await openCodex({ predictionPacUrl: nativePrediction?.pacUrl, predictionApp: nativePrediction?.app, predictionProfile: nativePrediction?.profile,
526
530
  preparePredictionRoute: () => nativePrediction?.prepareRoute(), persistedPredictionRoute: persistentRoute?.status === "installed",
527
531
  onPredictionRoute: route => clientIntegration?.launched(route), log: startupLogger("App") });
528
532
  console.log(predictionStartupCheck(clientIntegration?.snapshot().prediction));
@@ -1,14 +1,14 @@
1
1
  # Architecture boundaries
2
2
 
3
3
  CCDX is one local Node service with client-specific protocol surfaces and isolated
4
- upstream providers. GitHub is the default Codex provider; Microsoft 365 is optional.
4
+ upstream providers. GitHub is the default Codex provider; Microsoft 365 and explicit manual API connections are optional.
5
5
  Client integration, image tools and the dashboard are not a general plugin framework.
6
6
 
7
7
  | Responsibility | Ownership | Boundary |
8
8
  | --- | --- | --- |
9
9
  | Core inference | `adapter.mjs`, Responses modules, model catalog, history | Codex wire contracts, streaming and recovery |
10
- | Providers | `providers/github.mjs`, `providers/m365*.mjs` | Source-owned auth, discovery, routing, capabilities and transport |
11
- | Provider composition | `provider-runtime.mjs`, `provider-registry.mjs`, `provider-settings.mjs` | Explicit selection, lifecycle, history namespaces and snapshots |
10
+ | Providers | `providers/github.mjs`, `providers/m365*.mjs`, `providers/api*.mjs` | Source-owned auth, discovery, routing, capabilities and transport |
11
+ | Provider composition | `provider-runtime.mjs`, `connection-runtime.mjs`, provider/access settings | Explicit selection, lifecycle, history namespaces and snapshots |
12
12
  | Claude clients | `claude-gateway.mjs`, `claude-client-lifecycle.mjs`, `claude-client-config.mjs`, `claude-models.mjs` | Native Messages relay and field-owned reversible client setup |
13
13
  | Client integration | `client-integration.mjs`, Codex config, native prediction | Client setup, optional start/stop, diagnostic snapshots |
14
14
  | Optional images | Image provider, CLI setup, image MCP and skill | Opt-in API access and image delivery; failures do not block core startup |
@@ -17,6 +17,55 @@ Client integration, image tools and the dashboard are not a general plugin frame
17
17
 
18
18
  ## Composition and lifecycle
19
19
 
20
+ ### Manual connection graph (1.2.13)
21
+
22
+ `provider-runtime.mjs` composes built-in lifecycle with `connection-runtime.mjs`,
23
+ which owns grants, switches and explicit current bindings. `access-settings.mjs`
24
+ validates strict versioned metadata and locked atomic writes; stale cross-process
25
+ saves are rejected. Accepted inputs and public snapshots do not share mutable
26
+ objects with the live graph. The built-in registry does not load external code.
27
+
28
+ `providers/api.mjs` owns configured native clients, model capabilities,
29
+ configuration/key history identity and explicit bounded discovery. It uses no
30
+ Copilot/M365 retry or request-body policy. Its lazy transport is retained per
31
+ configuration, not rebuilt or serialized against the whole catalog per request.
32
+ `providers/api-network.mjs` preserves enterprise routing/TLS and pins exact HTTPS
33
+ targets. The WinHTTP API mode checks its allowlist in JS and C#; prediction/M365
34
+ retain their original host restrictions. A failed worker can be replaced only
35
+ for a later request, without replaying the failed request.
36
+
37
+ The API editor separates catalog candidates from selected models. Only selected
38
+ models enter the strict saved graph, with a required native protocol; unused
39
+ ID-only catalog entries cannot invalidate a save. Client grants remain separate
40
+ from route availability: manual sources need configured models for the client's
41
+ protocol before they are offered as its current source.
42
+
43
+ `api-secrets.mjs` owns OS-protected credentials and a private-pipe cache; no
44
+ command argument contains an upstream key. Failed metadata commits remove their
45
+ candidate key. Retired keys/transports wait for pinned requests. An environment
46
+ reference provides headless operation without plaintext files or a new npm
47
+ dependency. `private-helper-environment.mjs` retains OS credential-service and
48
+ company-network inputs while omitting unrelated credentials and Node hooks.
49
+
50
+ `client-gateway-keys.mjs` separates caller identity from display hints and upstream
51
+ credentials. `codex-api-config.mjs` reconciles an owned provider/model/table with
52
+ paired writes. Claude uses its existing mounted relay and field journal with
53
+ independent app/code lifecycles. M365 beta policy is not imposed on API clients;
54
+ adding a source alone never migrates old client credentials. Configuring clients
55
+ does not patch/restart their binaries or override managed settings.
56
+
57
+ `conversation-source-guard.mjs` retains bounded HMAC correlations for observed
58
+ managed histories. Known source/key conflicts fail before forwarding. It does
59
+ not establish provenance for an unseen history or implement dynamic affinity.
60
+ The existing Responses route-plan boundary continues to own opaque-state checks.
61
+
62
+ `dashboard/connections.js` owns settings forms; application source/review and
63
+ account/catalog views keep their existing scopes and use the same backend graph.
64
+ Full configuration is on-demand; ordinary status uses compact cached summaries.
65
+ Shared Messages observation includes all sources, while M365-specific status
66
+ projects M365 counts. Bounds cover two built-ins plus 16 APIs without unbounded
67
+ labels, request histories, body logging or a new refresh loop.
68
+
20
69
  ### Provider boundary
21
70
 
22
71
  Each provider supplies its client, model registry, route plan, model/request policy
@@ -25,7 +74,7 @@ its Fast mapping, retries and recovery are not applied blindly to M365. Protocol
25
74
  adaptation belongs to the client boundary. There is no generic intermediate message
26
75
  format that would erase native Responses or Anthropic semantics.
27
76
 
28
- `provider-registry.mjs` declares the bounded internal source metadata used by selection validation and dashboard source choices. It loads no external code; GitHub and M365 are the two production sources. Source-specific selection/model rules remain with composition. A third source is only a contract test fixture.
77
+ `provider-registry.mjs` declares the bounded internal source metadata used by selection validation and dashboard source choices. It loads no external code; GitHub and M365 remain built-in sources. `access-settings.mjs` validates up to 16 user-defined API records; `providers/api.mjs` is their first-party implementation, not a third-party code loader. Client grants and the explicit current source remain in composition.
29
78
 
30
79
  `provider-runtime.mjs` owns source selection, not the providers themselves. Each
31
80
  request pins a provider before admission. An explicit change affects later requests;
@@ -397,7 +446,7 @@ the lockfile fixes CI transitives, not consumers' future transitive resolution.
397
446
 
398
447
  ### Source-level observations
399
448
 
400
- Stream performance retains existing route totals and adds `by_route.<route>.by_provider`. Each source has started/active/finished counts, terminal totals, bounded model outcomes, request-to-first-output timing and preparation histograms. Source assignment is pinned once. There are at most 16 source labels plus `other`, and 32 model labels plus `other` per source. Unassigned finished requests use `unknown`; request IDs, accounts and URLs never become metric labels. Recent requests remain capped at 20. `runtime_usage.by_provider` has at most 16 labels plus `other`; unknown usage stays partial and persisted historical records retain their source.
449
+ Stream performance retains existing route totals and adds `by_route.<route>.by_provider`. Each source has started/active/finished counts, terminal totals, bounded model outcomes, request-to-first-output timing and preparation histograms. Source assignment is pinned once. There are at most 18 source labels (two built-ins and 16 APIs) plus `other`, and 32 model labels plus `other` per source. Unassigned finished requests use `unknown`; request IDs, accounts and URLs never become metric labels. Recent requests remain capped at 20. `runtime_usage.by_provider` has at most 18 labels plus `other`; unknown usage stays partial and persisted historical records retain their source.
401
450
 
402
451
  `operation-error.mjs` distinguishes client cancellation, unspecified abort, timeout, network/TLS/proxy, authentication and access denial. HTTP 403 is not proof of credential expiry. Claude and Codex cancellations are informational; request-body timeouts use 408, upstream/idle timeouts 504, and local client cancellation diagnostics 499. Original upstream error status/body and protocol-specific stream bytes retain their existing path.
403
452
 
package/docs/REFERENCE.md CHANGED
@@ -4,6 +4,96 @@ Use Codex App with GPT models available to your **GitHub Copilot** account by de
4
4
  The optional [Microsoft 365 provider](#microsoft-365-provider) supplies a protocol-isolated
5
5
  Claude gateway and an explicitly selected Codex backup.
6
6
 
7
+ ## Manual APIs and client access
8
+
9
+ `ccdx web` starts management without GitHub sign-in or automatic App launch.
10
+ Use **Settings → Model sources → Add API**, save the HTTPS API base address/key
11
+ (including a required prefix such as `/v1`), then reopen **Manage → Read models**.
12
+ Select the models to use and their supported interfaces, save, then choose each
13
+ client's current source under **Settings → Clients**. Unselected catalog entries
14
+ are not saved. A selected model needs at least one interface; choosing an
15
+ interface also selects its model. Manual ID entry is an optional collapsed path
16
+ for models absent from the catalog. Only Codex on GitHub needs the default
17
+ GitHub sign-in path. To use Claude alone, disable Codex access. Stop the
18
+ management-only process before normal `ccdx` startup for the live terminal.
19
+
20
+ | Client | Local base path | Required upstream API |
21
+ | --- | --- | --- |
22
+ | Codex App / CLI | `/v1` | Responses |
23
+ | Claude App / Claude Code | `/anthropic` | Messages |
24
+
25
+ All paths share the main port, normally 2026. Manual Codex and explicitly managed
26
+ Claude clients receive distinct private local credentials; never the upstream
27
+ key. Display hints do not authorize requests. API addresses require HTTPS, no
28
+ userinfo/query/fragment, and endpoint overrides on the base address's origin.
29
+ Redirects are refused. Existing proxy/bypass/private-CA rules remain; unsupported
30
+ dynamic macOS routing fails without a direct fallback. Windows delegates system
31
+ routing to a target-pinned WinHTTP worker. Failed calls are not replayed; a dead
32
+ worker can be recreated for a later request.
33
+
34
+ Up to 16 uniquely named manual APIs and 500 unique models per API are supported. Model IDs are limited to 160 characters; `codex-auto-review` remains an internal alias. Custom model
35
+ IDs are not filtered by a GPT/Claude prefix. Each model declares Messages,
36
+ Responses and/or Chat Completions; optional stored `context_window` and
37
+ `reasoning_efforts` metadata remain explicit. Chat-only records are catalog
38
+ information, not converted into another client protocol. Saving makes no catalog
39
+ or inference call. **Read models** performs one explicit catalog read, with a
40
+ 20-second deadline and 8 MiB body bound. An ID-only result has unknown protocol
41
+ support until reviewed. Opening normal views reads saved models rather than
42
+ probing every API. `ccdx models` labels manual models as configured, not live.
43
+
44
+ `connections.json` beside user settings (respecting `XDG_CONFIG_HOME`) stores a
45
+ strict version-one graph of provider switches, API metadata and each client's
46
+ allowed/current sources. It stores only credential references or an environment
47
+ variable name. Keys use macOS Keychain service `codex-copilot-dx.manual-api`,
48
+ Windows CurrentUser DPAPI-protected bytes, or Linux Secret Service (`secret-tool`).
49
+ Unavailable protection fails without plaintext fallback. Headless installations
50
+ may use `key_env` under Addresses & authentication; set the variable before CCDX
51
+ starts. Its value is never returned by management or copied into client config.
52
+ Private helpers omit unrelated credentials and Node hooks. API error bodies are
53
+ replaced with stable codes; valid Retry-After metadata is retained.
54
+
55
+ `client-gateway-keys.json` holds local credentials separately. Disabled sources
56
+ and clients leave normal lists/navigation and remain in collapsed **Disabled**.
57
+ Closing a client stops CCDX access, not the app. Disabling an in-use source
58
+ requires explicit replacements or pauses. Pinned API streams finish on their
59
+ original provider; retired transports/keys are released afterwards. Legacy M365
60
+ work is guarded before its old gateway is removed. Recovery preserves grants,
61
+ configuration and historical usage without choosing a current source. With a
62
+ managed graph, `m365 off` pauses affected bindings; `m365 remove` preserves shared
63
+ Claude ownership records still needed by APIs.
64
+
65
+ Claude's existing field-owned journal protects custom/managed edits. Manual
66
+ clients use the existing profile with generic name CCDX; M365's beta restriction
67
+ is not imposed on APIs. Only an unchanged owned restriction is restored. Adding
68
+ an API alone does not migrate existing M365 client credentials. First explicit
69
+ Claude connection management installs private client keys; reopen affected apps.
70
+ Codex reconciliation owns only the provider/model/table and preserves user edits.
71
+ Repeated identical setup does not rewrite its file.
72
+
73
+ A manual Codex provider includes an authenticated `model_catalog_url` on the same
74
+ listener. Supported native selectors list configured custom names. Unknown names
75
+ use conservative metadata without borrowed model instructions, invented context,
76
+ vision, web search or Fast claims. API-specific Auto Review uses its configured
77
+ model and advertised efforts; following the client does not synthesize low.
78
+ See the official [provider configuration](https://learn.chatgpt.com/docs/config-file/config-advanced#custom-model-providers)
79
+ and [gateway catalog requirements](https://learn.chatgpt.com/docs/enterprise/roll-out-a-gateway#use-a-model-catalog-for-custom-names).
80
+
81
+ Responses namespaces include API configuration/key identity. Managed native
82
+ histories retain at most 1,024 HMAC-only correlation/owner pairs in
83
+ `conversation-sources.json`. No prompt, raw session ID or key is stored. A known
84
+ session or first-message correlation that changes source/key returns 409 before
85
+ forwarding history. This is bounded observation, not proof of the provenance of
86
+ unseen external history. Start a new conversation after source/key changes; do
87
+ not transfer opaque reasoning, compaction or signed history between services.
88
+ There is no automatic load balancing, fallback or cross-source history replay.
89
+
90
+ `/_ccdx/ui/connections` requires loopback, the dashboard header, same-origin JSON
91
+ POSTs and a 256 KiB body bound. It returns redacted configuration and explicit
92
+ action results. Invalid/conflicting files are retained. The ordinary two-second
93
+ status returns compact source/client summaries, not all model records. Metrics
94
+ allow the two built-ins plus 16 APIs (18 labels plus bounded `other`). Aggregate
95
+ Claude observation covers all Messages sources; M365 counts keep their own scope.
96
+
7
97
  ## Microsoft 365 provider
8
98
 
9
99
  Starting with 0.10.0, CCDX can discover authorized M365 models independently of
@@ -1037,7 +1127,7 @@ Unknown support prevents an explicitly requested exception from starting.
1037
1127
  For an older updater that still requires Git, install the Release tarball directly:
1038
1128
 
1039
1129
  ```sh
1040
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.12/codex-copilot-dx-1.2.12.tgz
1130
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.14/codex-copilot-dx-1.2.14.tgz
1041
1131
  # Windows PowerShell: use npm.cmd instead of npm.
1042
1132
  ```
1043
1133
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.12",
4
- "description": "Local Codex adapter and optional Microsoft 365 Claude gateway",
3
+ "version": "1.2.14",
4
+ "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
7
7
  "bin": {
@@ -0,0 +1,98 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { userSettingsPath } from "./user-settings.mjs";
4
+ import { readBoundedFileSync } from "./bounded-file.mjs";
5
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
6
+ import { withFileLockSync } from "./lock.mjs";
7
+ import { isProviderId } from "./provider-metadata.mjs";
8
+ import { CODEX_AUTO_REVIEW_MODEL } from "./models.mjs";
9
+
10
+ export const CLIENT_IDS = Object.freeze(["codex", "claude_app", "claude_code"]);
11
+ export const CLIENT_NAMES = Object.freeze({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" });
12
+ const APIS = ["messages", "responses", "chat"];
13
+ const messages = {
14
+ ccdx_client_source_disabled: "This client's CCDX access or selected source is disabled. Review Settings.",
15
+ ccdx_client_credential_required: "The client's local CCDX credential is missing or outdated. Reopen the client after setup.",
16
+ ccdx_conversation_source_changed: "This conversation was observed on another source or key. Start a new conversation.",
17
+ ccdx_conversation_state_invalid: "Conversation source records are unreadable. The existing file was preserved.",
18
+ ccdx_api_model_unavailable: "This model is not configured for the requested API. Review the source's model list.",
19
+ ccdx_api_environment_key_missing: "Set the configured API-key environment variable before starting CCDX.",
20
+ ccdx_api_secret_unavailable: "The system credential store is unavailable. No plaintext fallback was used.",
21
+ ccdx_client_source_mismatch: "Save the source before changing its review model.",
22
+ };
23
+ export const accessError = (code, statusCode = 400) => {
24
+ const message = messages[code] || code;return Object.assign(new Error(message), { code, statusCode,
25
+ jsonBody: { type: "error", error: { type: statusCode >= 500 ? "api_error" : "invalid_request_error", code, message } } });
26
+ };
27
+ export function accessSettingsPath(options = {}) { return path.join(path.dirname(userSettingsPath(options)), "connections.json"); }
28
+ export function apiUrl(value) {
29
+ let url;try { url = new URL(value); } catch { throw accessError("ccdx_api_url_invalid"); }
30
+ if (typeof value !== "string" || value.length > 2048 || url.protocol !== "https:"
31
+ || url.username || url.password || url.search || url.hash) throw accessError("ccdx_api_url_invalid");
32
+ return url.href;
33
+ }
34
+ const fields = (value, allowed) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => allowed.includes(key));
35
+ const modelId = value => typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value) && !value.includes("..") && !value.includes("//");
36
+ export function checkedApi(value) {
37
+ if (!fields(value, ["id", "name", "enabled", "base_url", "endpoints", "auth_header", "secret_ref", "key_env", "models", "checked_at"])
38
+ || !isProviderId(value.id) || !value.id.startsWith("api_") || typeof value.name !== "string" || !value.name.trim() || value.name.length > 60
39
+ || /[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/.test(value.name) || typeof value.enabled !== "boolean"
40
+ || (value.key_env ? !/^[A-Z][A-Z0-9_]{0,95}$/.test(value.key_env) || value.secret_ref !== undefined : !/^[a-f0-9]{32}$/.test(value.secret_ref || "")) || !["x-api-key", "bearer"].includes(value.auth_header)
41
+ || !fields(value.endpoints, APIS) || !Object.keys(value.endpoints).length
42
+ || !Array.isArray(value.models) || value.models.length > 500) throw accessError("ccdx_api_config_invalid");
43
+ apiUrl(value.base_url);
44
+ const origin = new URL(value.base_url).origin;
45
+ for (const url of Object.values(value.endpoints)) if (new URL(apiUrl(url)).origin !== origin) throw accessError("ccdx_api_origin_mismatch");
46
+ const seen = new Set();
47
+ for (const model of value.models) {
48
+ if (model?.id === CODEX_AUTO_REVIEW_MODEL) throw accessError("ccdx_api_model_reserved");
49
+ if (!fields(model, ["id", "protocols", "context_window", "reasoning_efforts"]) || !modelId(model.id) || seen.has(model.id)
50
+ || !Array.isArray(model.protocols) || !model.protocols.length || new Set(model.protocols).size !== model.protocols.length
51
+ || model.protocols.some(api => !value.endpoints[api])
52
+ || model.context_window !== undefined && (!Number.isSafeInteger(model.context_window) || model.context_window < 1)
53
+ || model.reasoning_efforts !== undefined && (!Array.isArray(model.reasoning_efforts) || model.reasoning_efforts.length > 8
54
+ || model.reasoning_efforts.some(effort => !["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(effort)))) throw accessError("ccdx_api_models_invalid");
55
+ seen.add(model.id);
56
+ }
57
+ if (value.checked_at !== undefined && (typeof value.checked_at !== "string" || !Number.isFinite(Date.parse(value.checked_at)))) throw accessError("ccdx_api_config_invalid");
58
+ return value;
59
+ }
60
+ export function defaultAccessSettings() {
61
+ return { version: 1, claude_private_keys: false, providers: { github: true, m365: true }, apis: [], clients: Object.fromEntries(CLIENT_IDS.map(id => [id,
62
+ { enabled: true, allowed: id === "codex" ? ["github", "m365"] : ["m365"], source: null }])) };
63
+ }
64
+ export function checkedAccessSettings(value) {
65
+ if (!fields(value, ["version", "claude_private_keys", "providers", "apis", "clients"]) || value.version !== 1 || typeof value.claude_private_keys !== "boolean"
66
+ || !fields(value.providers, ["github", "m365"]) || ["github", "m365"].some(id => typeof value.providers[id] !== "boolean")
67
+ || !Array.isArray(value.apis) || value.apis.length > 16 || !fields(value.clients, CLIENT_IDS)) throw accessError("ccdx_connections_invalid");
68
+ const ids = new Set(["github", "m365"]), names = new Set(["github copilot", "microsoft 365"]);
69
+ for (const api of value.apis) { checkedApi(api);if (ids.has(api.id)) throw accessError("ccdx_connections_invalid");ids.add(api.id);
70
+ const name = api.name.trim().toLowerCase();if (names.has(name)) throw accessError("ccdx_api_name_exists");names.add(name);
71
+ }
72
+ for (const id of CLIENT_IDS) {
73
+ const client = value.clients[id];
74
+ if (!fields(client, ["enabled", "allowed", "source", "model", "auto_review_model", "auto_review_effort", "history_isolation"])
75
+ || typeof client.enabled !== "boolean" || !Array.isArray(client.allowed) || client.allowed.length > 18 || new Set(client.allowed).size !== client.allowed.length
76
+ || client.allowed.some(source => !ids.has(source)) || client.source !== null && !client.allowed.includes(client.source)
77
+ || ["model", "auto_review_model"].some(key => client[key] !== undefined && !modelId(client[key]))
78
+ || client.history_isolation !== undefined && typeof client.history_isolation !== "boolean"
79
+ || client.auto_review_effort !== undefined && client.auto_review_effort !== null && !["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(client.auto_review_effort)) throw accessError("ccdx_connections_invalid");
80
+ for (const source of client.allowed) {
81
+ const apis = source === "github" ? ["responses"] : source === "m365" ? ["messages", "responses"] : Object.keys(value.apis.find(api => api.id === source).endpoints);
82
+ if (!apis.includes(id === "codex" ? "responses" : "messages")) throw accessError("ccdx_api_protocol_required");
83
+ }
84
+ }
85
+ return value;
86
+ }
87
+ export function readAccessSettings(options = {}) {
88
+ try { return checkedAccessSettings(JSON.parse(readBoundedFileSync(accessSettingsPath(options), { maxBytes: 8 * 1024 * 1024, encoding: "utf8" }))); }
89
+ catch (error) { if (error.code === "ENOENT") return defaultAccessSettings();throw accessError("ccdx_connections_invalid", 409); }
90
+ }
91
+ export function updateAccessSettings(change, options = {}) {
92
+ const file = accessSettingsPath(options);fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
93
+ return withFileLockSync(`${file}.lock`, () => {
94
+ const next = checkedAccessSettings(change(readAccessSettings(options)));
95
+ const text = JSON.stringify(next, null, 2) + "\n";if (Buffer.byteLength(text) > 8 * 1024 * 1024) throw accessError("ccdx_connections_limit", 413);
96
+ atomicWriteFileSync(file, text, { mode: 0o600 });return next;
97
+ });
98
+ }
package/src/adapter.mjs CHANGED
@@ -100,9 +100,11 @@ async function sendModelList(res, models, {
100
100
  rawBody,
101
101
  statusCode = 200,
102
102
  restrictToUpstream = false,
103
+ providerCatalog,
103
104
  } = {}) {
104
105
  let body = rawBody || JSON.stringify(models);
105
- if (clientVersion && typeof codexModelCatalog?.load === "function") {
106
+ if (clientVersion && typeof providerCatalog === "function") body = JSON.stringify(providerCatalog(models));
107
+ else if (clientVersion && typeof codexModelCatalog?.load === "function") {
106
108
  let response = null;
107
109
  try {
108
110
  const codexCatalog = await codexModelCatalog.load({ clientVersion });
@@ -172,7 +174,8 @@ export function createAdapterHandler(options = {}) {
172
174
  credentialsChanged: options.dashboardOptions?.credentialsChanged || (() => codexClient.invalidateCredentials?.()),
173
175
  ...(options.providerRuntime ? { providerCatalogFn: input => options.providerRuntime.dashboardCatalog(input),
174
176
  providerStateFn: () => options.providerRuntime.dashboardProviders(),
175
- providerAccountsFn: () => options.providerRuntime.action({ action: "accounts" }) } : {}) } });
177
+ providerAccountsFn: () => options.providerRuntime.action({ action: "accounts" }),
178
+ connectionsFn: input => options.providerRuntime.manageConnections(input) } : {}) } });
176
179
  let statusSnapshot;
177
180
  const managementHandler = createManagementHandler({
178
181
  nativePredictionPac: options.nativePredictionPac, fixPrediction: options.fixPrediction, requestBodyTimeoutMs,
@@ -188,10 +191,16 @@ export function createAdapterHandler(options = {}) {
188
191
  source: providers.m365.models?.source || "unavailable", provider: "m365",
189
192
  refresh_in_flight: providers.m365.refresh_in_flight === true };
190
193
  }
194
+ if (providers?.codex_provider?.startsWith("api_")) {
195
+ const source = providers.connections.providers.find(entry => entry.id === providers.codex_provider);
196
+ snapshot.routing = { ...snapshot.routing, responses: providers.codex_provider };
197
+ snapshot.models = { ...snapshot.models, provider: providers.codex_provider, source: "configured", models: source?.codex_model_count || 0, refresh_in_flight: false };
198
+ }
191
199
  return { ...snapshot, http_errors: httpErrors.snapshot(), ...(providers ? { providers } : {}) };
192
200
  },
193
201
  });
194
202
  const responsesHandler = createResponsesHandler({
203
+ validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
195
204
  provider: options.provider || options.providerRuntime?.github,
196
205
  acquireRequest,
197
206
  autoReviewModelResolver: options.autoReviewModelResolver,
@@ -211,6 +220,7 @@ export function createAdapterHandler(options = {}) {
211
220
  upstreamTimeoutMs,
212
221
  });
213
222
  const responsesCompactHandler = createResponsesCompactHandler({
223
+ validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
214
224
  provider: options.provider || options.providerRuntime?.github,
215
225
  acquireRequest,
216
226
  autoReviewModelResolver: options.autoReviewModelResolver,
@@ -230,9 +240,10 @@ export function createAdapterHandler(options = {}) {
230
240
  if (!provider || provider.id === "github") return githubHandlers;
231
241
  if (!providerHandlers.has(provider)) {
232
242
  const common = { provider, acquireRequest, imagePressure, keepaliveIntervalMs: options.keepaliveIntervalMs,
243
+ validateConversation: (body, headers, source) => options.providerRuntime?.validateConversation?.(body, headers, source),
233
244
  modelRegistry: provider.registry, now: options.now, openAIModelEnv: { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" },
234
- autoReviewModelResolver: () => { const preference = options.providerRuntime.selection().m365;
235
- return { model: preference.auto_review_model, reasoningEffort: preference.auto_review_effort === undefined ? "low" : preference.auto_review_effort }; },
245
+ autoReviewModelResolver: () => { const preference = options.providerRuntime.providerPreference?.(provider.id) || options.providerRuntime.selection().m365;
246
+ return { model: preference?.auto_review_model, reasoningEffort: preference?.auto_review_effort === undefined ? Object.hasOwn(provider, "defaultReviewEffort") ? provider.defaultReviewEffort : "low" : preference.auto_review_effort }; },
236
247
  requestBodyTimeoutMs, responsesPayloadOptions: options.responsesPayloadOptions, responseFailures,
237
248
  streamHandshakeTimeoutMs, streamIdleTimeoutMs, upstreamTimeoutMs };
238
249
  providerHandlers.set(provider, {
@@ -252,6 +263,7 @@ export function createAdapterHandler(options = {}) {
252
263
  const query = new URL(req.url, "http://localhost").search;
253
264
  req.url = pathname.slice("/anthropic".length) + query;
254
265
  try { return await options.providerRuntime.handleClaude(req, res); }
266
+ catch (error) { sendJsonError(res, error, error.statusCode || 502); }
255
267
  finally { req.url = original; }
256
268
  }
257
269
  if (req.method === "POST" && ["/v1/responses", "/v1/responses/compact"].includes(pathname)
@@ -267,7 +279,7 @@ export function createAdapterHandler(options = {}) {
267
279
 
268
280
  let target;
269
281
  if (["/v1/responses", "/v1/responses/compact", "/v1/models"].includes(pathname) && options.providerRuntime) {
270
- try { target = options.providerRuntime.current(); }
282
+ try { target = options.providerRuntime.current(req); }
271
283
  catch (error) { sendJsonError(res, error, 503);return; }
272
284
  const context = currentRequestContext();
273
285
  if (context) {
@@ -294,8 +306,8 @@ export function createAdapterHandler(options = {}) {
294
306
  if (req.method === "GET" && pathname === "/v1/models") {
295
307
  const clientVersion = modelClientVersion(req.url);
296
308
  const selectedRegistry = target?.registry || codexModelRegistry;
297
- const selectedListModels = target?.id === "m365" ? target.client.listModels : listModelsFn;
298
- const modelOptions = { codexModelCatalog, clientVersion, restrictToUpstream: target?.id === "m365" };
309
+ const selectedListModels = target && target.id !== "github" ? target.client.listModels : listModelsFn;
310
+ const modelOptions = { codexModelCatalog, clientVersion, providerCatalog: target?.codexCatalog, restrictToUpstream: Boolean(target && target.id !== "github") };
299
311
  const abort = createRequestAbort(req, res);
300
312
  // Keep live discovery and explicit auth failures authoritative, but do
301
313
  // not make a usable cached picker wait the full inference timeout.