codex-copilot-dx 1.2.19 → 1.2.21

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
@@ -11,7 +11,7 @@ npm install -g codex-copilot-dx@latest
11
11
  ccdx
12
12
  ```
13
13
 
14
- No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.19/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.19/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.21/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.21/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).
15
15
 
16
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.
17
17
 
@@ -52,11 +52,11 @@ Requests shows live app/source/model flow above existing summaries and finished
52
52
 
53
53
  ## Add your own API
54
54
 
55
- Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
55
+ Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
56
56
 
57
57
  Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving reads model metadata automatically, without inference. Startup and the existing model refresh cycle also refresh enabled APIs when the 30-minute cache expires; failed reads retain saved configuration. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
58
58
 
59
- Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.19 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.19.md) cover automatic capability discovery and application adapter boundaries, retaining the 1.2.18 sign-in safeguards.
59
+ Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.21 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.21.md) cover native GitHub integration, friendly model names and startup/ownership protection.
60
60
 
61
61
  ## Microsoft 365 access
62
62
 
package/bin/cli.mjs CHANGED
@@ -481,7 +481,14 @@ try {
481
481
 
482
482
  // Refresh the VS Code version in the background; fallback is non-blocking.
483
483
  void refreshVSCodeVersion();
484
- if (providerRuntime.selection().codex === "github") await profileModels.initialize();
484
+ if (providerRuntime.selection().codex === "github") {
485
+ await profileModels.initialize();
486
+ // Provider setup can run before GitHub's directory exists. Reconcile again
487
+ // before opening the App, then join any existing stale-cache refresh.
488
+ const refreshing = profileModels.codexRegistry.refreshInFlight ? profileModels.refreshAll() : null;
489
+ await providerRuntime.syncClients(["codex"]);
490
+ void refreshing?.then(() => providerRuntime.selection().codex === "github" && providerRuntime.syncClients(["codex"])).catch(() => {});
491
+ }
485
492
  if (profileModels.codexRegistry.source !== "live") {
486
493
  console.log(startupCheck("info", "Models", `${profileModels.codexRegistry.source} list loaded${profileModels.codexRegistry.refreshInFlight ? "; refreshing" : ""}`));
487
494
  }
@@ -539,7 +546,7 @@ try {
539
546
  const refreshIntervalMs = RUNTIME.modelRefreshIntervalMs;
540
547
  if (Number.isFinite(refreshIntervalMs) && refreshIntervalMs > 0) {
541
548
  modelRefreshTimer = setInterval(() => {
542
- if (providerRuntime.selection().codex === "github") profileModels.refreshAll().catch(() => {});
549
+ if (providerRuntime.selection().codex === "github") profileModels.refreshAll().then(() => providerRuntime.selection().codex === "github" && providerRuntime.syncClients(["codex"])).catch(() => {});
543
550
  providerRuntime.refresh().catch(() => {});
544
551
  }, refreshIntervalMs);
545
552
  modelRefreshTimer.unref?.();
@@ -648,3 +648,56 @@ Language controls have intrinsic width and no-wrap/no-shrink. Shared button-link
648
648
  styling keeps the M365 navigation link semantically a link while matching the
649
649
  existing GitHub shortcut; wording describes navigation rather than a silent check.
650
650
  No new polling, framework, runtime dependency, setting or endpoint is introduced.
651
+
652
+ ## Catalog transactions and default identity (1.2.20)
653
+
654
+ `api-catalog-refresh.mjs` owns bounded catalog I/O, same-source single-flight,
655
+ existing success/failure cooldowns, cancellation and deployment-version checks.
656
+ It receives source/config/commit callbacks; it does not write configuration or
657
+ client files. `connection-runtime.mjs` serializes only management changes and
658
+ result publication. A cancelled or obsolete read cannot publish; pinned source
659
+ instances drain through the existing reference tracking. The existing refresh
660
+ cycle remains the scheduler; no extra timer or background process is added.
661
+
662
+ Metadata commits merge only matching configured model IDs into the current
663
+ configuration and sync affected clients. Shared Claude capability projection
664
+ continues to consider both consumers and ownership journals. Metadata never
665
+ changes the selected model set, grants, default identity or native sign-in.
666
+
667
+ `client-model-plan.mjs` distinguishes an unspecified default from an unavailable
668
+ explicit default and indexes each source catalog once per compilation. Native
669
+ catalog projection does not depend on finding a default provider. Request
670
+ resolution still checks the selected source-qualified model before opening an
671
+ upstream call; no substitute model, cross-source fallback or auth recovery is
672
+ introduced. Builtin raw capability structures pass through normalization only;
673
+ validated manual fields belong to manual API configurations.
674
+
675
+ The existing dashboard connection controller owns one draft per client and
676
+ local operation feedback. Source browsing is one shared selection for management,
677
+ account and catalog. Presentation retains existing palettes, motion and native
678
+ controls; it adds no runtime UI dependency or protocol abstraction framework.
679
+
680
+ ## Native Codex provider identity
681
+
682
+ GitHub-only managed bindings use the built-in OpenAI provider and a journal-owned
683
+ `openai_base_url`. Non-GitHub bindings retain the private keyed provider. Provider
684
+ identity is a client UI/auth boundary, not merely a transport setting; a native
685
+ app-server catalog does not establish the App's custom-provider rendering path.
686
+ The Codex reconciliation journal migrates v1 entries, records/restores root base
687
+ URLs, shares the startup configuration lock and protects user edits. Startup
688
+ leaves journal-owned base URLs to that writer. An unchanged inactive legacy
689
+ provider table remains available to sessions that recorded its ID; session files
690
+ and native authentication are not migrated or rewritten.
691
+
692
+ Codex exposes unambiguous upstream IDs and friendly metadata. Qualified defaults
693
+ and legacy route aliases stay internal and source-bound. Same-named deployments
694
+ remain distinct, with suffixes only where needed. Native replay covers a legacy
695
+ session, first model/list after cold/warm/old-cache starts, authMethod, effective
696
+ provider, model visibility and synthetic inference. Real App UI acceptance remains
697
+ separate from this RPC evidence.
698
+
699
+ A complete recognized qualified-ID model cache can be retired to a single private
700
+ backup during native reconciliation, before the config transaction commits.
701
+ Unknown/partial caches are not claimed. On config commit failure, the old cache
702
+ is restored only if the client has not created a new cache. This is a bounded
703
+ schema migration, not a periodic cache purge or a credential/session reset.
package/docs/REFERENCE.md CHANGED
@@ -107,16 +107,27 @@ clients use the existing profile with generic name CCDX; M365's beta restriction
107
107
  is not imposed on APIs. Only an unchanged owned restriction is restored. Adding
108
108
  an API alone does not migrate existing M365 client credentials. First explicit
109
109
  Claude connection management installs private client keys; reopen affected apps.
110
- Codex reconciliation owns only the provider/model/table and preserves user edits.
111
- Repeated identical setup does not rewrite its file.
112
- When an existing native sign-in or credential-store policy is present, the owned
113
- provider keeps `requires_openai_auth = true`. Native account operations keep their
114
- own authentication; model traffic uses only CCDX's local bearer credential. A fresh
115
- API-only profile without native authentication remains usable without a ChatGPT
116
- login. Reconciliation never writes `auth.json` or deletes/replaces native credentials.
117
- A changed default model is preserved independently; it does not prevent repair
118
- of an otherwise unchanged owned provider table. Reopen Codex after an owned
119
- provider/authentication configuration change.
110
+ Codex reconciliation owns provider selection, the selected model, the private
111
+ provider table and, in native mode, `openai_base_url`. GitHub-only selections use
112
+ this base URL with the built-in `openai` provider; fresh native setups create no
113
+ custom provider table. The App therefore keeps its native provider branch.
114
+ An unchanged old `ccdx_gateway` table is retained inactive during migration so
115
+ existing sessions can still resume their recorded provider. New sessions use
116
+ `openai`; existing session files are never rewritten to disguise their provider.
117
+
118
+ The versioned ownership journal records exact prior/owned declarations and
119
+ supports native/private switching and restoration. Startup defers an owned base
120
+ URL to this reconciliation instead of overwriting preserved user edits. Identical
121
+ setup does not rewrite the file. A missing default keeps its identity and does
122
+ not prevent a safe native route repair. User model/base edits remain protected.
123
+ Reconciliation never writes `auth.json` or replaces native credentials.
124
+
125
+ Non-GitHub deployments retain the private provider/local-key route. Existing
126
+ native sign-in or credential-store policy keeps `requires_openai_auth = true`;
127
+ a fresh API-only profile remains usable without ChatGPT login. Native account
128
+ operations retain their own authentication. App custom-provider controls can
129
+ differ from native OpenAI controls; CLI catalogs do not prove App UI parity.
130
+ Reopen Codex after an owned provider/authentication configuration change.
120
131
 
121
132
  GitHub-only explicit bindings preserve the legacy native loopback access contract,
122
133
  including requests from a process that has not yet reloaded its configuration.
@@ -130,7 +141,8 @@ Saving them fails without changing prior settings; refresh the catalog or explic
130
141
  clear the affected selection. A missing directory entry never means deselection.
131
142
 
132
143
  A manual Codex provider includes an authenticated `model_catalog_url` on the same
133
- listener. Supported native selectors list configured custom names. Unknown names
144
+ listener. Native app-server catalogs list configured names; the App may still use
145
+ its custom-provider UI for non-GitHub selections. Unknown names
134
146
  use conservative metadata without borrowed model instructions, invented context,
135
147
  vision, web search or Fast claims. API-specific Auto Review uses its configured
136
148
  model and advertised efforts; following the client does not synthesize low.
@@ -155,11 +167,37 @@ Claude observation covers all Messages sources; M365 counts keep their own scope
155
167
 
156
168
  ## Model capabilities and Claude synchronization
157
169
 
170
+ An explicitly selected default keeps its identity when its catalog entry becomes
171
+ unavailable. CCDX does not substitute the first model or rewrite that client's
172
+ existing configuration. Other authorized models remain in the catalog and can be
173
+ requested explicitly; an unavailable model produces a model error rather than a
174
+ sign-in challenge. The application page retains the unavailable selection and
175
+ asks for a valid default before saving. Catalog recovery restores the same route.
176
+
177
+ API saves complete independently of metadata reads. Catalog network work runs
178
+ outside the configuration transaction; only a version-checked result commit
179
+ holds that queue. Same-source, same-deployment reads join the active request.
180
+ Changing its endpoint/key, disabling the source, cancelling the read or stopping
181
+ the service prevents obsolete results from publishing. Failed reads retain saved
182
+ metadata and selections. Capability commits synchronize only affected clients;
183
+ shared Claude settings still respect both consumers and manual ownership.
184
+
185
+
158
186
  Model sources owns source credentials, native interface declarations and model details.
159
187
  Codex/Claude own the selected deployment set, default and automatic synchronization.
160
188
  Claude App and Claude Code have separate segments and local keys. Settings retains
161
189
  appearance, startup and updates; source/client editors are not duplicated there.
162
190
 
191
+ Codex catalogs and its `model` setting use an unambiguous upstream ID. Source
192
+ suffixes appear only for same-named authorized deployments; friendly upstream
193
+ names/descriptions are retained. Internal defaults and route aliases remain
194
+ source-qualified, so adding another same-named source cannot move an existing
195
+ default. Existing qualified IDs continue to resolve to their original source. During the
196
+ one-time native ID migration, a complete cache containing exactly the recognized
197
+ old selected route IDs is moved to `models_cache.json.ccdx-qualified.bak` with
198
+ private permissions. The client then reads the current directory; unknown or
199
+ partial caches and native authentication/session data are preserved.
200
+
163
201
  A deployment is identified by source plus actual model ID. Its stable public route
164
202
  is independent of catalog order and key rotation; its private history/evidence
165
203
  identity includes endpoint, authentication and credential generation. Same-named
@@ -1264,7 +1302,7 @@ Unknown support prevents an explicitly requested exception from starting.
1264
1302
  For an older updater that still requires Git, install the Release tarball directly:
1265
1303
 
1266
1304
  ```sh
1267
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.19/codex-copilot-dx-1.2.19.tgz
1305
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.21/codex-copilot-dx-1.2.21.tgz
1268
1306
  # Windows PowerShell: use npm.cmd instead of npm.
1269
1307
  ```
1270
1308
 
@@ -1640,7 +1678,7 @@ unchanged.
1640
1678
 
1641
1679
  New explicit-tool sign-ins use `~/.local/share/ccdx/github_token` and fingerprint-bound `.account.json` metadata, with private permissions and the existing atomic paired writer. When present, this owned store takes precedence over `~/.local/share/copilot-api/github_token`; existing startup/discovery compatibility remains supported. `auth logout` requires interactive confirmation or `--yes`, writes an empty owned credential, and does not delete or revoke other apps' legacy credentials. This intentionally blocks inference's legacy fallback. New login or normal startup can perform the existing explicit discovery/sign-in process again. CLI changes notify a compatible running local service; if notification is unavailable, the CLI asks for a service restart. In-flight model requests are not replayed or forcibly stopped. A token cache invalidation preserves its running account binding, so switching accounts still requires a restart.
1642
1680
 
1643
- Model sources uses one source selector for the account controls and catalog. Selecting a tab is browsing only. GitHub offers sign-in, independent connection checks and cancellation; sign-out is under More actions. The browser opens only the fixed GitHub device authorization URL after the user chooses Open GitHub. No token or password entry field is added. Microsoft 365 retains local account discovery/selection and source controls; its corporate SSO is not replaced with a GitHub-style login. Raw codes remain under details and last-good model lists retain their previous timestamp after failures.
1681
+ Model sources uses one source selector for the selected source controls, account and catalog. Disabled sources remain under its collapsed list; there is no second list of enabled source cards. Selecting a tab is browsing only. GitHub offers sign-in, independent connection checks and cancellation; sign-out is under More actions. The browser opens only the fixed GitHub device authorization URL after the user chooses Open GitHub. No token or password entry field is added. Microsoft 365 retains local account discovery/selection and source controls; its corporate SSO is not replaced with a GitHub-style login. Raw codes remain under details and last-good model lists retain their previous timestamp after failures.
1644
1682
 
1645
1683
  `ccdx web` opens an existing compatible dashboard or starts a management-only local listener without sign-in, app configuration, app launch, prediction setup or automatic M365 startup. It does not claim normal startup integrations are active. Stop that management listener with Ctrl+C before running normal `ccdx` for application routing and optional integrations. Opening the dashboard does not initiate a GitHub Device Flow or model inference.
1646
1684
 
@@ -1878,3 +1916,35 @@ so toggling it does not shift nearby controls. The language control has a 40px
1878
1916
  minimum width, cannot flex-shrink and keeps 中文 / EN on one line. Compact toolbars
1879
1917
  wrap when required rather than compressing text; header position remains stable
1880
1918
  between modules in the same language and viewport.
1919
+
1920
+ ### Application editing and keyboard behavior (1.2.20)
1921
+
1922
+ Codex, Claude App and Claude Code keep separate page-local model/default/sync
1923
+ drafts. Switching clients, navigating within the dashboard or reading current
1924
+ settings preserves unsaved drafts. Save and Discard changes affect that client
1925
+ only; reloading the browser discards page-local drafts. Model selection restores
1926
+ focus to the corresponding checkbox/default button. Add API focuses its first
1927
+ field; Cancel restores the entry control. Narrow layouts stack source, context
1928
+ and reasoning below each model while retaining the same table semantics.
1929
+
1930
+ Reading a catalog marks only its Read models button busy and offers Cancel.
1931
+ Cancelling leaves the editor and its draft intact. No inference is sent. Source
1932
+ saves report persistence separately from subsequent metadata refresh. Background
1933
+ read failures retain existing messages; key read/save states use polite live
1934
+ announcements. Account labels and values stay paired, and request summaries use
1935
+ configured source names. Technical IDs remain available in request details.
1936
+
1937
+ ### Codex App updates and model selection
1938
+
1939
+ After an App update, completely quit and reopen the App once if the model list is
1940
+ empty, then inspect `ccdx doctor`. On macOS, doctor reads bundled CLI package
1941
+ metadata and the optional model-cache version without executing a binary or
1942
+ altering the cache. A version mismatch is a diagnostic hint; it does not prove
1943
+ that the cache caused a failed catalog. HTTP catalog `models` and app-server RPC
1944
+ `model/list.data` are different layers, not evidence by themselves of a format
1945
+ regression between client versions.
1946
+
1947
+ The Responses WebSocket protocol is not implemented by CCDX. Upgrade requests
1948
+ are refused promptly so supported native clients can fall back to HTTP/SSE.
1949
+ This is tested separately from model-directory and provider-identity behavior;
1950
+ SSE events are not relabeled as a WebSocket protocol.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.19",
3
+ "version": "1.2.21",
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",
@@ -12,6 +12,7 @@ export const CLIENT_IDS = Object.freeze(["codex", "claude_app", "claude_code"]);
12
12
  export const CLIENT_NAMES = Object.freeze({ codex: "Codex App", claude_app: "Claude App", claude_code: "Claude Code" });
13
13
  const APIS = ["messages", "responses", "chat"];
14
14
  const messages = {
15
+ ccdx_codex_catalog_cache_unavailable: "Codex model cache could not be refreshed safely. Close Codex App and try again; existing files were kept.",
15
16
  ccdx_client_source_disabled: "This client's CCDX access or selected source is disabled. Review Settings.",
16
17
  ccdx_client_credential_required: "The client's local CCDX credential is missing or outdated. Reopen the client after setup.",
17
18
  ccdx_conversation_source_changed: "This conversation was observed on another source or key. Start a new conversation.",
@@ -0,0 +1,72 @@
1
+ import { accessError } from "./access-settings.mjs";
2
+
3
+ // Network work never holds the configuration transaction. Only publication
4
+ // enters the caller's short, version-checked commit boundary.
5
+ export function createApiCatalogRefresh({ config, source, track, revision, commit, onState, now = Date.now }) {
6
+ const reads = new Map(), flights = new Map(), pending = new Set();let closed = false, batch;
7
+ const current = (id, version) => !closed && config(id)?.enabled && revision(config(id)) === version;
8
+ function cancel(id) {
9
+ const flight = flights.get(id);if (!flight) return;
10
+ flights.delete(id);flight.controller.abort();
11
+ onState(id, { state: "cancelled", checked_at: new Date(now()).toISOString() });
12
+ }
13
+ function invalidate() {
14
+ for (const [id, flight] of flights) if (!current(id, flight.revision)) { cancel(id);onState(id, null); }
15
+ for (const [id, read] of reads) if (!current(id, read.revision)) { reads.delete(id);onState(id, null); }
16
+ }
17
+ async function refresh(id, force = false) {
18
+ const selected = config(id);
19
+ if (closed || !selected?.enabled) throw accessError("ccdx_client_source_disabled", 503);
20
+ const version = revision(selected), old = flights.get(id);
21
+ if (old?.revision === version && !old.controller.signal.aborted) return old.promise;
22
+ if (old) cancel(id);
23
+ const cached = reads.get(id), age = cached ? now() - cached.at : Infinity;
24
+ if (cached?.revision === version && age >= 0 && age < (force || cached.error ? 60000 : 30 * 60000)) {
25
+ if (cached.error) throw cached.error;
26
+ await commit(id, cached.models, version, new Date(cached.at).toISOString(), () => current(id, version));
27
+ onState(id, { state: "ready", checked_at: new Date(cached.at).toISOString() });return cached.models;
28
+ }
29
+ const savedAge = now() - Date.parse(selected.checked_at);
30
+ if (!force && !cached && savedAge >= 0 && savedAge < 30 * 60000 && selected.models.every(model => model.metadata?.state && model.metadata.deployment === version)) return selected.models;
31
+ const flight = { revision: version, controller: new AbortController() };
32
+ flights.set(id, flight);
33
+ const active = () => current(id, version) && flights.get(id) === flight && !flight.controller.signal.aborted;
34
+ onState(id, { state: "checking", checked_at: new Date(now()).toISOString() });
35
+ pending.add(flight);
36
+ flight.promise = (async () => {
37
+ let finish;
38
+ try {
39
+ const provider = source(id);finish = track(provider);
40
+ const models = await provider.discover({ signal: AbortSignal.any([flight.controller.signal, AbortSignal.timeout(20000)]) });
41
+ if (!active()) throw accessError("ccdx_connections_conflict", 409);
42
+ const at = now();await commit(id, models, version, new Date(at).toISOString(), active);
43
+ if (!active()) throw accessError("ccdx_connections_conflict", 409);
44
+ reads.set(id, { revision: version, at, models });
45
+ onState(id, { state: "ready", checked_at: new Date(at).toISOString() });return models;
46
+ } catch (error) {
47
+ if (!active()) throw accessError("ccdx_connections_conflict", 409);
48
+ const code = /^ccdx_[a-z0-9_]+$/.test(error.code || "") ? error.code : "ccdx_api_catalog_unavailable";
49
+ const failure = accessError(code, [401, 403, 409].includes(error.statusCode) ? error.statusCode : 502);
50
+ if (active()) {
51
+ reads.set(id, { revision: version, at: now(), error: failure });
52
+ onState(id, { state: "stale", code, checked_at: new Date(now()).toISOString() });
53
+ }
54
+ throw failure;
55
+ } finally { finish?.();pending.delete(flight);if (flights.get(id) === flight) flights.delete(id); }
56
+ })();
57
+ return flight.promise;
58
+ }
59
+ return {
60
+ refresh, cancel, invalidate,
61
+ refreshAll(ids) {
62
+ if (closed) return Promise.resolve();
63
+ batch ||= (async () => { for (const id of ids) { if (closed) break;await refresh(id).catch(() => {}); } })().finally(() => { batch = null; });
64
+ return batch;
65
+ },
66
+ async close() {
67
+ closed = true;const jobs = [...pending].map(flight => flight.promise);
68
+ for (const flight of pending) flight.controller.abort();
69
+ await Promise.allSettled(jobs);await batch;
70
+ },
71
+ };
72
+ }
@@ -15,14 +15,23 @@ export function compileClientModels({ client, binding, source, enabled, names =
15
15
  if (!binding.enabled) return { models: [], routes: new Map(), defaultModel: null, revision: "disabled" };
16
16
  const explicit = Array.isArray(binding.deployments), selected = explicit ? binding.deployments : binding.source
17
17
  ? sourceModels(source(binding.source), client).map(model => ({ source: binding.source, model: model.id })) : [];
18
- const models = [], routes = new Map(), raw = new Map();
18
+ const models = [], routes = new Map(), raw = new Map(), catalogs = new Map(), available = [], counts = new Map();
19
19
  for (const item of selected) {
20
20
  if (!binding.allowed.includes(item.source) || !enabled(item.source)) continue;
21
- const provider = source(item.source), model = sourceModels(provider, client).find(model => model.id === item.model);
21
+ const provider = source(item.source);
22
+ if (!catalogs.has(provider)) catalogs.set(provider, new Map(sourceModels(provider, client).map(model => [model.id, model])));
23
+ const model = catalogs.get(provider).get(item.model);
22
24
  if (!model || model.policy?.state && model.policy.state !== "enabled" || model.model_picker_enabled === false) continue;
23
- const route = deploymentModelId(item.source, model.id), capability = model.capability || resolveModelCapabilities(model, { builtin: true });
24
- const entry = { ...model, capability, source_id: item.source, route_id: route,
25
- ...(explicit ? { client_id: route, display_name: `${model.id} · ${names[item.source] || item.source}` } : {}) };
25
+ available.push({ item, provider, model, route: deploymentModelId(item.source, model.id) });counts.set(model.id, (counts.get(model.id) || 0) + 1);
26
+ }
27
+ const routeIds = new Set(available.map(entry => entry.route));
28
+ for (const { item, provider, model, route } of available) {
29
+ const capability = model.capability || resolveModelCapabilities(model, { builtin: true });
30
+ const sourceName = names[item.source] || provider.name || ({ github: "GitHub Copilot", m365: "Microsoft 365" })[item.source] || item.source;
31
+ const ambiguous = counts.get(model.id) > 1;
32
+ const entry = { ...model, capability, source_id: item.source, source_name: sourceName, route_id: route,
33
+ ...(explicit ? { client_id: client === "codex" && !ambiguous && !routeIds.has(model.id) ? model.id : route,
34
+ ...(ambiguous ? { display_name: `${model.display_name || model.name || model.id} · ${sourceName}` } : {}) } : {}) };
26
35
  if (client === "claude_app" && explicit) entry.client_id = claudeDeploymentId(entry, route, { desktopEffortAliases });
27
36
  const publicId = explicit ? entry.client_id : client === "codex" ? model.id : claudeModelEntries([entry], { desktopAliases: client === "claude_app" && provider.id.startsWith("api_") })[0].name;
28
37
  entry.public_id = publicId;
@@ -43,7 +52,8 @@ export function compileClientModels({ client, binding, source, enabled, names =
43
52
  }
44
53
  }
45
54
  }
46
- const fallback = models.find(model => model.id === binding.model || model.route_id === binding.default_model) || models[0];
47
- return { models, routes, defaultModel: routes.get(binding.default_model)?.publicId || fallback?.public_id || null,
55
+ const requested = explicit ? binding.default_model : binding.model;
56
+ const chosen = routes.get(requested) || (!requested ? models[0] && routes.get(models[0].public_id) : null);
57
+ return { models, routes, defaultModel: chosen?.publicId || null, defaultUnavailable: Boolean(requested && !chosen),
48
58
  revision: models.map(model => model.route_id + ":" + model.capability.revision).join(";") };
49
59
  }
@@ -5,14 +5,14 @@ export function codexModelEntry(model, { priority = 0, name = "", template = {}
5
5
  base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
6
6
  supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
7
7
  experimental_supported_tools: [], input_modalities: values.input_modalities || ["text"], ...template,
8
- slug: model.public_id || model.id, display_name: model.display_name || model.id, description: name, visibility: "list", supported_in_api: true, priority,
8
+ 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
9
  default_reasoning_level: efforts[0] || null, supported_reasoning_levels: efforts.map(effort => ({ effort, description: effort })),
10
10
  context_window: values.context_window || template.context_window || null, max_context_window: values.context_window || template.max_context_window || null };
11
11
  }
12
12
  export function codexClientCatalog(plan) {
13
13
  return Object.assign((value, nativeCatalog) => ({ ...value, models: plan.models.map((model, priority) => {
14
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_id });
15
+ return codexModelEntry(model, { priority, template, name: model.source_name || model.source_id });
16
16
  }) }), { needsNativeCatalog: plan.models.some(model => model.source_id === "github") });
17
17
  }
18
18
 
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { parse } from "smol-toml";
3
+ import { codexTomlStatements, parseCodexToml, validateManagedConfigEdit } from "./config-toml.mjs";
4
4
  import { codexPaths } from "./codex-paths.mjs";
5
5
  import { accessSettingsPath, accessError } from "./access-settings.mjs";
6
6
  import { readBoundedFileSync } from "./bounded-file.mjs";
@@ -19,49 +19,117 @@ function retainsCodexSignIn(config, directory, env) {
19
19
  throw accessError("ccdx_codex_config_invalid", 409);
20
20
  }
21
21
  }
22
- // Only the provider, selected model and private provider table are owned.
23
- export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...options } = {}) {
22
+ function validateOwner(owner) {
23
+ if (owner && (![1, 2].includes(owner.version) || !Object.hasOwn(owner, "beforeProvider") || !Object.hasOwn(owner, "beforeSection")
24
+ || owner.version === 1 && typeof owner.section !== "string"
25
+ || owner.version === 2 && (!["openai", "gateway"].includes(owner.mode) || owner.mode === "gateway" && typeof owner.section !== "string"
26
+ || owner.mode === "openai" && owner.section !== null && typeof owner.section !== "string"))) throw accessError("ccdx_codex_config_invalid", 409);
27
+ }
28
+ export function codexBaseUrlManaged(options = {}) {
29
+ if (options.filePath && path.resolve(options.filePath) !== codexPaths(options).config) return false;
30
+ const journal = path.join(path.dirname(accessSettingsPath(options)), "codex-gateway-owner.json");
31
+ try {
32
+ const owner = JSON.parse(readBoundedFileSync(journal, { encoding: "utf8", maxBytes: 16384 }));validateOwner(owner);
33
+ return owner?.version === 2 && Object.hasOwn(owner, "base");
34
+ } catch (error) { if (error.code === "ENOENT") return false;throw accessError("ccdx_codex_config_invalid", 409); }
35
+ }
36
+
37
+ // Retain exact declarations for restoration; the scanner handles quoted keys,
38
+ // comments and multiline values without serializing unrelated TOML.
39
+ function rootDeclaration(content, key) {
40
+ const item = codexTomlStatements(content).find(item => item.kind === "value" && !item.section.length && item.keys.length === 1 && item.keys[0] === key);
41
+ if (!item) return null;
42
+ const start = content.lastIndexOf("\n", item.start - 1) + 1, newline = content.indexOf("\n", item.valueEnd), end = newline < 0 ? content.length : newline + 1;
43
+ return { start, end, text: content.slice(start, end) };
44
+ }
45
+ function replaceRoot(content, key, text) {
46
+ const item = rootDeclaration(content, key);
47
+ return item ? content.slice(0, item.start) + (text || "") + (text && !text.endsWith("\n") && item.end < content.length ? "\n" : "") + content.slice(item.end) : (text || "") + content;
48
+ }
49
+
50
+ // Retire only the complete, recognized qualified-ID cache from the old native
51
+ // route. Its bytes remain available for rollback; unknown caches are untouched.
52
+ function retireQualifiedCache(models, options) {
53
+ if (!Array.isArray(models) || !models.length) return () => {};
54
+ const aliases = new Set(models.filter(model => model.public_id !== model.route_id && /^ccdx\/model-\d+$/.test(model.route_id)).map(model => model.route_id));
55
+ if (aliases.size !== models.length) return () => {};
56
+ const file = path.join(codexPaths(options).directory, "models_cache.json"), backup = file + ".ccdx-qualified.bak";
57
+ let bytes, cache;
58
+ try { bytes = readBoundedFileSync(file, { maxBytes: 8 * 1024 * 1024 });cache = JSON.parse(bytes.toString("utf8")); }
59
+ catch (error) { if (error.code === "ENOENT" || error instanceof SyntaxError) return () => {};throw accessError("ccdx_codex_catalog_cache_unavailable", 409); }
60
+ if (!Array.isArray(cache.models) || cache.models.length !== aliases.size || !cache.models.every(model => typeof model?.slug === "string" && aliases.has(model.slug))
61
+ || new Set(cache.models.map(model => model.slug)).size !== aliases.size) return () => {};
62
+ try {
63
+ if (fs.existsSync(backup) && !readBoundedFileSync(backup, { maxBytes: 8 * 1024 * 1024 }).equals(bytes)) throw Error("cache_backup_conflict");
64
+ if (!readBoundedFileSync(file, { maxBytes: 8 * 1024 * 1024 }).equals(bytes)) throw Error("cache_changed");
65
+ fs.renameSync(file, backup);fs.chmodSync(backup, 0o600);
66
+ } catch { throw accessError("ccdx_codex_catalog_cache_unavailable", 409); }
67
+ return () => { if (!fs.existsSync(file)) fs.renameSync(backup, file); };
68
+ }
69
+
70
+ // GitHub-only traffic retains the built-in OpenAI provider. Private API traffic
71
+ // keeps its own provider and local key. Both routes share one ownership journal.
72
+ export function configureCodexApi({ baseUrl, apiKey, model, native = false, nativeModels, restore = false, ...options } = {}) {
24
73
  if (!restore) {
25
74
  let url;try { url = new URL(baseUrl); } catch { throw accessError("ccdx_codex_config_invalid"); }
26
75
  if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/v1" || url.username || url.password || url.search || url.hash
27
- || !/^[a-f0-9]{64}$/.test(apiKey)) throw accessError("ccdx_codex_config_invalid");
76
+ || !native && !/^[a-f0-9]{64}$/.test(apiKey)) throw accessError("ccdx_codex_config_invalid");
28
77
  }
29
78
  const file = codexPaths(options).config, journal = path.join(path.dirname(accessSettingsPath(options)), "codex-gateway-owner.json");
30
79
  if (restore && !fs.existsSync(journal)) return { state: "unchanged" };
31
80
  fs.mkdirSync(path.dirname(journal), { recursive: true, mode: 0o700 });fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
32
- return withFileLockSync(`${journal}.lock`, () => {
81
+ return withFileLockSync(`${file}.ccdx.lock`, () => withFileLockSync(`${journal}.lock`, () => {
33
82
  let content = "", owner = null;
34
83
  try { content = readBoundedFileSync(file, { encoding: "utf8", maxBytes: 1024 * 1024 }); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_codex_config_invalid", 409); }
35
84
  try { owner = JSON.parse(readBoundedFileSync(journal, { encoding: "utf8", maxBytes: 16384 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_codex_config_invalid", 409); }
36
- let config;try { config = parse(content); } catch { throw accessError("ccdx_codex_config_invalid", 409); }
37
- if (owner && (owner.version !== 1 || typeof owner.section !== "string" || !Object.hasOwn(owner, "beforeProvider") || !Object.hasOwn(owner, "beforeSection"))) throw accessError("ccdx_codex_config_invalid", 409);
38
- const firstTable = content.search(/^\s*\[/m), head = firstTable < 0 ? content : content.slice(0, firstTable), tail = firstTable < 0 ? "" : content.slice(firstTable);
85
+ let config;try { config = parseCodexToml(content); } catch { throw accessError("ccdx_codex_config_invalid", 409); }
86
+ validateOwner(owner);
87
+ const table = codexTomlStatements(content).find(item => item.kind === "table"), firstTable = table ? content.lastIndexOf("\n", table.start - 1) + 1 : -1;
88
+ const head = firstTable < 0 ? content : content.slice(0, firstTable), tail = firstTable < 0 ? "" : content.slice(firstTable);
39
89
  const sectionPattern = /^\[model_providers\.ccdx_gateway\]\r?\n[^]*?(?=^\[|$(?![^]))/m;
40
90
  const currentSection = tail.match(sectionPattern)?.[0] || null;
41
- if (owner && (config.model_provider !== ID || currentSection !== owner.section)) return { state: "preserved" };
91
+ const nativeOwner = owner?.mode === "openai", openaiProvider = !config.model_provider || config.model_provider === "openai";
92
+ if (owner && (currentSection !== owner.section || (nativeOwner ? !openaiProvider : config.model_provider !== ID && !(native && openaiProvider)))) return { state: "preserved" };
93
+ if (owner && Object.hasOwn(owner, "base") && rootDeclaration(head, "openai_base_url")?.text !== owner.base) return { state: "preserved" };
42
94
  const modelEdited = owner?.model !== undefined && config.model !== owner.model;
43
95
  if (restore && modelEdited) return { state: "preserved" };
44
- if (!owner && (config.model_provider && config.model_provider !== "openai" || config.model_providers?.[ID])) return { state: "preserved" };
96
+ if (!owner && (!openaiProvider || config.model_providers?.[ID])) return { state: "preserved" };
97
+ const beforeProvider = owner ? owner.beforeProvider : rootDeclaration(head, "model_provider")?.text || null;
98
+ const beforeSection = owner ? owner.beforeSection : currentSection;
45
99
  let next, nextOwner = null;
46
100
  if (restore) {
47
101
  if (!owner) return { state: "unchanged" };
48
- let root = head.replace(/^model_provider\s*=.*(?:\r?\n|$)/m, owner.beforeProvider || "");
49
- if (owner.model !== undefined) root = root.replace(/^model\s*=.*(?:\r?\n|$)/m, owner.beforeModel || "");
50
- next = root + tail.replace(sectionPattern, owner.beforeSection || "");
102
+ let root = replaceRoot(head, "model_provider", beforeProvider);
103
+ if (owner.model !== undefined) root = replaceRoot(root, "model", owner.beforeModel);
104
+ if (Object.hasOwn(owner, "base")) root = replaceRoot(root, "openai_base_url", owner.beforeBase);
105
+ next = root + (currentSection ? tail.replace(sectionPattern, beforeSection || "") : tail);
51
106
  } else {
52
- // Account identity remains native; only model traffic uses the local key.
53
- const requiresAuth = retainsCodexSignIn(config, path.dirname(file), options.env || process.env);
54
- const section = `[model_providers.${ID}]\nname = "CCDX"\nbase_url = ${JSON.stringify(baseUrl)}\nmodel_catalog_url = ${JSON.stringify(baseUrl + "/models")}\nwire_api = "responses"\nrequires_openai_auth = ${requiresAuth}\nexperimental_bearer_token = ${JSON.stringify(apiKey)}\n\n`;
55
- let root = head;
56
- if (model && !modelEdited) root = root.match(/^model\s*=/m) ? root.replace(/^model\s*=.*(?:\r?\n|$)/m, `model = ${JSON.stringify(model)}\n`) : `model = ${JSON.stringify(model)}\n` + root;
57
- next = (root.match(/^model_provider\s*=/m) ? root.replace(/^model_provider\s*=.*(?:\r?\n|$)/m, `model_provider = "${ID}"\n`) : `model_provider = "${ID}"\n` + root)
58
- + (currentSection ? tail.replace(sectionPattern, section) : tail + (tail && !tail.endsWith("\n") ? "\n" : "") + "\n" + section);
59
- nextOwner = { version: 1, beforeProvider: owner ? owner.beforeProvider : head.match(/^model_provider\s*=.*(?:\r?\n|$)/m)?.[0] || null,
60
- beforeSection: owner ? owner.beforeSection : currentSection, section,
61
- ...(modelEdited ? { model: owner.model, beforeModel: owner.beforeModel }
62
- : model ? { model, beforeModel: owner && Object.hasOwn(owner, "beforeModel") ? owner.beforeModel : head.match(/^model\s*=.*(?:\r?\n|$)/m)?.[0] || null } : {}) };
107
+ let root = head, section;
108
+ if (model && !modelEdited) root = replaceRoot(root, "model", `model = ${JSON.stringify(model)}\n`);
109
+ if (native) {
110
+ root = replaceRoot(root, "model_provider", beforeProvider);
111
+ root = replaceRoot(root, "openai_base_url", `openai_base_url = ${JSON.stringify(baseUrl)}\n`);
112
+ // Existing sessions retain their provider ID. Keep its unchanged table
113
+ // inactive so they can resume; fresh native installs create no table.
114
+ section = currentSection;
115
+ next = root + tail;
116
+ } else {
117
+ const requiresAuth = retainsCodexSignIn(config, path.dirname(file), options.env || process.env);
118
+ section = `[model_providers.${ID}]\nname = "CCDX"\nbase_url = ${JSON.stringify(baseUrl)}\nmodel_catalog_url = ${JSON.stringify(baseUrl + "/models")}\nwire_api = "responses"\nrequires_openai_auth = ${requiresAuth}\nexperimental_bearer_token = ${JSON.stringify(apiKey)}\n\n`;
119
+ root = replaceRoot(root, "model_provider", `model_provider = "${ID}"\n`);
120
+ next = root + (currentSection ? tail.replace(sectionPattern, section) : tail + (tail && !tail.endsWith("\n") ? "\n" : "") + "\n" + section);
121
+ }
122
+ nextOwner = { version: 2, mode: native ? "openai" : "gateway", beforeProvider, beforeSection, section,
123
+ ...(native || owner && Object.hasOwn(owner, "base") ? { beforeBase: owner && Object.hasOwn(owner, "beforeBase") ? owner.beforeBase : rootDeclaration(head, "openai_base_url")?.text || null,
124
+ base: native ? `openai_base_url = ${JSON.stringify(baseUrl)}\n` : owner.base } : {}),
125
+ ...(modelEdited || !model && owner?.model !== undefined ? { model: owner.model, beforeModel: owner.beforeModel }
126
+ : model ? { model, beforeModel: owner && Object.hasOwn(owner, "beforeModel") ? owner.beforeModel : rootDeclaration(head, "model")?.text || null } : {}) };
63
127
  }
64
- parse(next);if (next !== content || JSON.stringify(nextOwner) !== JSON.stringify(owner)) atomicWriteFilePairSync(file, next, journal, nextOwner ? JSON.stringify(nextOwner) + "\n" : null, { mode: 0o600 });
128
+ try { validateManagedConfigEdit(config, next, [["model"], ["model_provider"], ["model_providers", ID], ["openai_base_url"]]); }
129
+ catch { throw accessError("ccdx_codex_config_invalid", 409); }
130
+ const undoCache = native && !restore ? retireQualifiedCache(nativeModels, options) : () => {};
131
+ try { if (next !== content || JSON.stringify(nextOwner) !== JSON.stringify(owner)) atomicWriteFilePairSync(file, next, journal, nextOwner ? JSON.stringify(nextOwner) + "\n" : null, { mode: 0o600 }); }
132
+ catch (error) { undoCache();throw error; }
65
133
  return { state: modelEdited ? "preserved" : "configured", changed: next !== content };
66
- });
134
+ }));
67
135
  }