codex-copilot-dx 1.2.18 → 1.2.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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.18/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.18/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.20/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.20/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
 
@@ -54,9 +54,9 @@ Requests shows live app/source/model flow above existing summaries and finished
54
54
 
55
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.
56
56
 
57
- Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving makes no upstream call. 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.
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 distinguish API declarations, manual values and unknown fields. Context, maximum input/output, reasoning levels, input types, tools and protocol-specific native search are deployment-specific; missing metadata is not inferred from 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).
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.20 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.20.md) cover default-model protection, nonblocking catalog reads and independent client drafts, retaining the native sign-in safeguards.
60
60
 
61
61
  ## Microsoft 365 access
62
62
 
@@ -29,8 +29,11 @@ objects with the live graph. The built-in registry does not load external code.
29
29
  strict manual values, per-field evidence and deployment revisions. It reads no
30
30
  credentials or client files. Explicit manual values override the current API's
31
31
  structured declarations; absent or generation-mismatched fields remain unknown.
32
- `client-model-plan.mjs` compiles immutable authorized catalogs, source-qualified
33
- routes and client metadata. Same-named models never collapse into one deployment.
32
+ `client-model-plan.mjs` compiles immutable authorized catalogs and source-qualified
33
+ routes. `clients/codex-models.mjs` projects native Codex catalogs and
34
+ `clients/claude-models.mjs` owns desktop compatibility aliases. These adapters do
35
+ not read upstream credentials, and API providers do not import client projections
36
+ or configuration writers. Same-named models never collapse into one deployment.
34
37
  Legacy null bindings retain their original single-source catalog; explicit arrays
35
38
  expose only selected models. A v1 file is backed up byte-for-byte before the first
36
39
  atomic v2 write. Source grants are not silently promoted to model grants.
@@ -56,11 +59,23 @@ are public data, not fabricated capabilities. Output constraints are recorded as
56
59
  bounded revision/constraint labels in existing request context observations.
57
60
 
58
61
  `providers/api.mjs` owns configured native clients, model capabilities,
59
- configuration/key history identity and explicit bounded discovery. It uses no
62
+ configuration/key history identity and bounded discovery. Its protocol-specific
63
+ capability snapshots feed both request validation and application projections.
64
+ `providers/api-model-metadata.mjs` interprets declared common/Anthropic catalog
65
+ schemas without a model-name registry. Native thinking and effort stay distinct;
66
+ Messages declarations do not leak into other protocols. `connection-runtime.mjs`
67
+ serializes automatic refresh on save/start/existing refresh ticks, coalesces
68
+ refresh batches and retains last-good data on failure. Normal reads use a
69
+ 30-minute cache; explicit reads/failures have a one-minute minimum interval.
70
+ Catalog-only changes preserve grants, source identity and running requests;
71
+ endpoint/credential changes create a new private revision. Environment credentials
72
+ are captured per provider instance so an active request cannot adopt another key.
73
+ It uses no
60
74
  Copilot/M365 retry or request-body policy. Its lazy transport is retained per
61
75
  configuration, not rebuilt or serialized against the whole catalog per request.
62
76
  `providers/api-network.mjs` preserves enterprise routing/TLS and pins exact HTTPS
63
- targets. The WinHTTP API mode checks its allowlist in JS and C#; prediction/M365
77
+ targets, with a GET-only validated catalog cursor exception. The WinHTTP API mode
78
+ checks the same allowlist/cursor boundary in JS and C#; prediction/M365
64
79
  retain their original host restrictions. A failure before response headers marks
65
80
  the transport unhealthy. The next request replaces it without replaying the
66
81
  failed call; retirement waits for unrelated active responses to drain. Shutdown
@@ -633,3 +648,31 @@ Language controls have intrinsic width and no-wrap/no-shrink. Shared button-link
633
648
  styling keeps the M365 navigation link semantically a link while matching the
634
649
  existing GitHub shortcut; wording describes navigation rather than a silent check.
635
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.
package/docs/REFERENCE.md CHANGED
@@ -42,11 +42,18 @@ Up to 16 uniquely named manual APIs and 500 unique models per API are supported.
42
42
  IDs are not filtered by a GPT/Claude prefix. Each model declares Messages,
43
43
  Responses and/or Chat Completions; optional stored `context_window` and
44
44
  `reasoning_efforts` metadata remain explicit. Chat-only records are catalog
45
- information, not converted into another client protocol. Saving makes no catalog
46
- or inference call. **Read models** performs one explicit catalog read, with a
47
- 20-second deadline and 8 MiB body bound. An ID-only result has unknown protocol
48
- support until reviewed. Opening normal views reads saved models rather than
49
- probing every API. `ccdx models` labels manual models as configured, not live.
45
+ information, not converted into another client protocol. Saving automatically
46
+ reads the catalog; failure does not undo saved configuration. Startup and the
47
+ existing periodic model-refresh cycle refresh enabled APIs serially, using a
48
+ 30-minute success cache and a one-minute failure cooldown. **Read models** can
49
+ refresh sooner, but shares a one-minute cache with recent reads. Directory GETs
50
+ use a 20-second total deadline, 8 MiB total body bound, 500 models and at most 25
51
+ pages. Native `has_more`/`last_id` pagination uses only a validated `after_id`
52
+ cursor on the configured catalog URL; arbitrary next URLs are never followed.
53
+ An ID-only result has unknown protocol support until reviewed. Ordinary page
54
+ reads use saved data; no discovery sends inference. `ccdx models` labels manual
55
+ models as configured, not live. New catalog entries are candidates, never
56
+ automatically granted to a client. An absent entry does not delete a saved model.
50
57
 
51
58
  For manual Messages APIs, CCDX writes Claude App's model configuration
52
59
  automatically. Standard Claude IDs keep their existing identity; other IDs use
@@ -148,6 +155,22 @@ Claude observation covers all Messages sources; M365 counts keep their own scope
148
155
 
149
156
  ## Model capabilities and Claude synchronization
150
157
 
158
+ An explicitly selected default keeps its identity when its catalog entry becomes
159
+ unavailable. CCDX does not substitute the first model or rewrite that client's
160
+ existing configuration. Other authorized models remain in the catalog and can be
161
+ requested explicitly; an unavailable model produces a model error rather than a
162
+ sign-in challenge. The application page retains the unavailable selection and
163
+ asks for a valid default before saving. Catalog recovery restores the same route.
164
+
165
+ API saves complete independently of metadata reads. Catalog network work runs
166
+ outside the configuration transaction; only a version-checked result commit
167
+ holds that queue. Same-source, same-deployment reads join the active request.
168
+ Changing its endpoint/key, disabling the source, cancelling the read or stopping
169
+ the service prevents obsolete results from publishing. Failed reads retain saved
170
+ metadata and selections. Capability commits synchronize only affected clients;
171
+ shared Claude settings still respect both consumers and manual ownership.
172
+
173
+
151
174
  Model sources owns source credentials, native interface declarations and model details.
152
175
  Codex/Claude own the selected deployment set, default and automatic synchronization.
153
176
  Claude App and Claude Code have separate segments and local keys. Settings retains
@@ -163,13 +186,24 @@ model substitution, cross-source retry or automatic protocol conversion.
163
186
 
164
187
  Each custom model accepts an optional `capabilities` object with positive token
165
188
  limits (`context_window`, `max_input_tokens`, `max_output_tokens`), reasoning flags,
166
- `reasoning_efforts`, optional reasoning budget bounds/format, `input_modalities`,
189
+ `reasoning_efforts`, optional reasoning budget bounds/format, `thinking_modes`, `input_modalities`,
167
190
  boolean tools/parallel tools/streaming/structured output and a `web_search` array
168
191
  of supported native protocols. Empty arrays mean an explicit empty set; in the
169
192
  editor enter `[]`. Blank fields follow the current deployment catalog. Known
170
193
  numeric limits, flags and enums are strictly validated; arbitrary JSON is rejected.
171
194
 
172
195
  Discovery retains recognized structured fields with per-deployment timestamps.
196
+ The existing common catalog fields and Anthropic ModelInfo declarations are
197
+ supported. Anthropic `max_input_tokens`/`max_tokens`, thinking types, effort
198
+ levels, image input, structured output and native search are interpreted as
199
+ Messages capabilities. They do not automatically apply to Responses or Chat.
200
+ Effort and thinking modes remain distinct; declaring a server-side search tool
201
+ does not prove support for client tool calls. The current upstream's declarations
202
+ are authoritative for that deployment, not a model-name database or the original
203
+ vendor's published limits. See the [Anthropic Models API](https://platform.claude.com/docs/en/api/http/models/list).
204
+ Model details show values by interface, then optional manual overrides. ID-only
205
+ catalogs say that upstream did not provide capabilities; unrecognized capability
206
+ formats have a separate state. Parsed values are saved, not raw upstream JSON.
173
207
  Manual fields, including false/empty arrays, take priority over API declarations.
174
208
  ID-only results keep missing fields unknown. A failed refresh preserves saved
175
209
  metadata and records a bounded error; a changed endpoint/key invalidates prior
@@ -1246,7 +1280,7 @@ Unknown support prevents an explicitly requested exception from starting.
1246
1280
  For an older updater that still requires Git, install the Release tarball directly:
1247
1281
 
1248
1282
  ```sh
1249
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.18/codex-copilot-dx-1.2.18.tgz
1283
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.20/codex-copilot-dx-1.2.20.tgz
1250
1284
  # Windows PowerShell: use npm.cmd instead of npm.
1251
1285
  ```
1252
1286
 
@@ -1622,7 +1656,7 @@ unchanged.
1622
1656
 
1623
1657
  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.
1624
1658
 
1625
- 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.
1659
+ 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.
1626
1660
 
1627
1661
  `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.
1628
1662
 
@@ -1860,3 +1894,20 @@ so toggling it does not shift nearby controls. The language control has a 40px
1860
1894
  minimum width, cannot flex-shrink and keeps 中文 / EN on one line. Compact toolbars
1861
1895
  wrap when required rather than compressing text; header position remains stable
1862
1896
  between modules in the same language and viewport.
1897
+
1898
+ ### Application editing and keyboard behavior (1.2.20)
1899
+
1900
+ Codex, Claude App and Claude Code keep separate page-local model/default/sync
1901
+ drafts. Switching clients, navigating within the dashboard or reading current
1902
+ settings preserves unsaved drafts. Save and Discard changes affect that client
1903
+ only; reloading the browser discards page-local drafts. Model selection restores
1904
+ focus to the corresponding checkbox/default button. Add API focuses its first
1905
+ field; Cancel restores the entry control. Narrow layouts stack source, context
1906
+ and reasoning below each model while retaining the same table semantics.
1907
+
1908
+ Reading a catalog marks only its Read models button busy and offers Cancel.
1909
+ Cancelling leaves the editor and its draft intact. No inference is sent. Source
1910
+ saves report persistence separately from subsequent metadata refresh. Background
1911
+ read failures retain existing messages; key read/save states use polite live
1912
+ announcements. Account labels and values stay paired, and request summaries use
1913
+ configured source names. Technical IDs remain available in request details.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.18",
3
+ "version": "1.2.20",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -51,7 +51,9 @@ export function checkedApi(value) {
51
51
  || !Array.isArray(model.protocols) || !model.protocols.length || new Set(model.protocols).size !== model.protocols.length
52
52
  || model.protocols.some(api => !value.endpoints[api])
53
53
  || model.capabilities !== undefined && !validCapabilities(model.capabilities)
54
- || model.metadata !== undefined && (!fields(model.metadata, ["values", "checked_at", "deployment"]) || !validCapabilities(model.metadata.values)
54
+ || model.metadata !== undefined && (!fields(model.metadata, ["values", "protocols", "state", "checked_at", "deployment"]) || !validCapabilities(model.metadata.values)
55
+ || model.metadata.protocols !== undefined && (!fields(model.metadata.protocols, APIS) || Object.values(model.metadata.protocols).some(value => !validCapabilities(value)))
56
+ || model.metadata.state !== undefined && !["reported", "missing", "unrecognized"].includes(model.metadata.state)
55
57
  || !/^[a-f0-9]{32}$/.test(model.metadata.deployment || "") || !Number.isFinite(Date.parse(model.metadata.checked_at)))
56
58
  || model.context_window !== undefined && (!Number.isSafeInteger(model.context_window) || model.context_window < 1)
57
59
  || model.reasoning_efforts !== undefined && (!Array.isArray(model.reasoning_efforts) || model.reasoning_efforts.length > 8
@@ -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
+ }
@@ -0,0 +1,10 @@
1
+ // Pagination is the only query accepted by custom-source transports. Never
2
+ // follow an arbitrary next URL or allow catalog queries on inference endpoints.
3
+ export function apiTargetAllowed(raw, targets, method = "GET") {
4
+ let url;try { url = new URL(raw); } catch { return false; }
5
+ if (targets.includes(url.href)) return true;
6
+ if (method !== "GET" || url.hash || !url.pathname.endsWith("/models") || [...url.searchParams.keys()].join() !== "after_id") return false;
7
+ const cursor = url.searchParams.get("after_id");
8
+ if (!/^[\w][\w./:@+-]{0,159}$/.test(cursor || "") || cursor.includes("..") || cursor.includes("//")) return false;
9
+ url.search = "";return targets.includes(url.href);
10
+ }
@@ -1,41 +1,37 @@
1
- import { deploymentModelId, resolveModelCapabilities, claudeEffortsExpressible } from "./model-capabilities.mjs";
1
+ import { deploymentModelId, resolveModelCapabilities } from "./model-capabilities.mjs";
2
2
  import { claudeModelEntries } from "./claude-models.mjs";
3
+ import { claudeDeploymentId, claudeRouteAliases } from "./clients/claude-models.mjs";
3
4
 
4
5
  const endpoints = { codex: ["/responses", "/v1/responses"], claude_app: ["/v1/messages"], claude_code: ["/v1/messages"] };
5
6
  export function sourceModels(source, client) {
6
7
  if (!source) return [];
7
8
  const models = source.models?.(client === "codex" ? "gpt" : "claude") || source.registry?.models?.data || [];
8
9
  return models.filter(model => model.supported_endpoints?.some(endpoint => endpoints[client].includes(endpoint)
9
- || client === "codex" && source.id === "github" && ["/chat/completions", "/v1/chat/completions"].includes(endpoint)));
10
+ || client === "codex" && source.id === "github" && ["/chat/completions", "/v1/chat/completions"].includes(endpoint)))
11
+ .map(model => model.protocol_capabilities ? { ...model, capability: model.protocol_capabilities[client === "codex" ? "responses" : "messages"] } : model);
10
12
  }
11
13
 
12
14
  export function compileClientModels({ client, binding, source, enabled, names = {}, desktopEffortAliases = false }) {
13
15
  if (!binding.enabled) return { models: [], routes: new Map(), defaultModel: null, revision: "disabled" };
14
16
  const explicit = Array.isArray(binding.deployments), selected = explicit ? binding.deployments : binding.source
15
17
  ? sourceModels(source(binding.source), client).map(model => ({ source: binding.source, model: model.id })) : [];
16
- const models = [], routes = new Map(), raw = new Map();
18
+ const models = [], routes = new Map(), raw = new Map(), catalogs = new Map();
17
19
  for (const item of selected) {
18
20
  if (!binding.allowed.includes(item.source) || !enabled(item.source)) continue;
19
- 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);
20
24
  if (!model || model.policy?.state && model.policy.state !== "enabled" || model.model_picker_enabled === false) continue;
21
25
  const route = deploymentModelId(item.source, model.id), capability = model.capability || resolveModelCapabilities(model, { builtin: true });
22
26
  const entry = { ...model, capability, source_id: item.source, route_id: route,
23
27
  ...(explicit ? { client_id: route, display_name: `${model.id} · ${names[item.source] || item.source}` } : {}) };
24
- if (client === "claude_app" && explicit) {
25
- const number = route.slice("ccdx/model-".length);
26
- const efforts = capability.values.reasoning === false ? [] : capability.values.reasoning_efforts || [];
27
- const native = /^claude-(?:opus|sonnet|haiku)-\d[\d.-]*(?:-latest)?$/.test(model.id);
28
- entry.client_id = native ? `ccdx-${number}.anthropic.${model.id.replace(/(\d)\.(\d)/g, "$1-$2")}`
29
- : desktopEffortAliases && claudeEffortsExpressible(capability.values) ? `mythos-ccdx-${number}` : `ccdx/claude-compatible-${number}`;
30
- }
28
+ if (client === "claude_app" && explicit) entry.client_id = claudeDeploymentId(entry, route, { desktopEffortAliases });
31
29
  const publicId = explicit ? entry.client_id : client === "codex" ? model.id : claudeModelEntries([entry], { desktopAliases: client === "claude_app" && provider.id.startsWith("api_") })[0].name;
32
30
  entry.public_id = publicId;
33
31
  const record = { provider, model: entry, source: item.source, upstreamModel: model.id, publicId };
34
32
  if (routes.has(publicId)) throw Object.assign(new Error("Model routes collide"), { code: "ccdx_model_route_collision", statusCode: 503 });
35
33
  routes.set(publicId, record);routes.set(route, record);
36
- if (client === "claude_app" && explicit) {
37
- const number = route.slice("ccdx/model-".length);routes.set(`mythos-ccdx-${number}`, record);routes.set(`ccdx/claude-compatible-${number}`, record);
38
- }
34
+ if (client === "claude_app" && explicit) for (const alias of claudeRouteAliases(entry, route, true).slice(2)) routes.set(alias, record);
39
35
  models.push(entry);
40
36
  raw.set(model.id, raw.has(model.id) ? null : record);
41
37
  }
@@ -44,32 +40,13 @@ export function compileClientModels({ client, binding, source, enabled, names =
44
40
  for (const [id, record] of raw) if (record && !routes.has(id)) {
45
41
  routes.set(id, record);
46
42
  if (client !== "codex") {
47
- for (const options of [{ desktopAliases: false }, { desktopAliases: true }]) {
48
- const old = claudeModelEntries([{ ...record.model, client_id: undefined }], options)[0].name;
43
+ for (const old of claudeRouteAliases(record.model, record.model.route_id, false)) {
49
44
  if (!routes.has(old)) routes.set(old, record);
50
45
  }
51
46
  }
52
47
  }
53
- const fallback = models.find(model => model.id === binding.model || model.route_id === binding.default_model) || models[0];
54
- return { models, routes, defaultModel: routes.get(binding.default_model)?.publicId || fallback?.public_id || null,
48
+ const requested = explicit ? binding.default_model : binding.model;
49
+ const chosen = routes.get(requested) || (!requested ? models[0] && routes.get(models[0].public_id) : null);
50
+ return { models, routes, defaultModel: chosen?.publicId || null, defaultUnavailable: Boolean(requested && !chosen),
55
51
  revision: models.map(model => model.route_id + ":" + model.capability.revision).join(";") };
56
52
  }
57
-
58
- // Client metadata is a projection, never a source of deployment capabilities.
59
- export function codexModelEntry(model, { priority = 0, name = "", template = {} } = {}) {
60
- const values = model.capability?.values || {}, efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
61
- return { shell_type: "unified_exec", availability_nux: null, upgrade: null, additional_speed_tiers: [], service_tiers: [],
62
- base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
63
- supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
64
- experimental_supported_tools: [], input_modalities: values.input_modalities || ["text"], ...template,
65
- slug: model.public_id || model.id, display_name: model.display_name || model.id, description: name, visibility: "list", supported_in_api: true, priority,
66
- default_reasoning_level: efforts[0] || null, supported_reasoning_levels: efforts.map(effort => ({ effort, description: effort })),
67
- context_window: values.context_window || template.context_window || null, max_context_window: values.context_window || template.max_context_window || null };
68
- }
69
- export function codexClientCatalog(plan, source) {
70
- return Object.assign((value, nativeCatalog) => ({ ...value, models: plan.models.map((model, priority) => {
71
- const template = model.source_id === "github" ? nativeCatalog?.models?.find(entry => entry.slug === model.id)
72
- : source(model.source_id).codexCatalog?.({ models: [] })?.models?.find(entry => entry.slug === model.id);
73
- return codexModelEntry(model, { priority, template, name: model.source_id });
74
- }) }), { needsNativeCatalog: plan.models.some(model => model.source_id === "github") });
75
- }
@@ -0,0 +1,20 @@
1
+ import { claudeModelEntries } from "../claude-models.mjs";
2
+ import { claudeEffortsExpressible } from "../model-capabilities.mjs";
3
+
4
+ export function claudeDeploymentId(model, route, { desktopEffortAliases = false } = {}) {
5
+ const number = route.slice("ccdx/model-".length);
6
+ const native = /^claude-(?:opus|sonnet|haiku)-\d[\d.-]*(?:-latest)?$/.test(model.id);
7
+ // This host alias is used only when its contiguous effort menu is supported.
8
+ // Both spellings remain accepted routes when capability evidence changes.
9
+ return native ? `ccdx-${number}.anthropic.${model.id.replace(/(\d)\.(\d)/g, "$1-$2")}`
10
+ : desktopEffortAliases && claudeEffortsExpressible(model.capability?.values) ? `mythos-ccdx-${number}` : `ccdx/claude-compatible-${number}`;
11
+ }
12
+
13
+ export function claudeRouteAliases(model, route, desktop) {
14
+ const aliases = [{ desktopAliases: false }, { desktopAliases: true }].map(options => claudeModelEntries([{ ...model, client_id: undefined }], options)[0].name);
15
+ if (desktop) {
16
+ const number = route.slice("ccdx/model-".length);
17
+ aliases.push(`mythos-ccdx-${number}`, `ccdx/claude-compatible-${number}`);
18
+ }
19
+ return aliases;
20
+ }
@@ -0,0 +1,22 @@
1
+ // Codex's native catalog is an application projection, not provider metadata.
2
+ export function codexModelEntry(model, { priority = 0, name = "", template = {} } = {}) {
3
+ const values = model.capability?.values || {}, efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
4
+ return { shell_type: "unified_exec", availability_nux: null, upgrade: null, additional_speed_tiers: [], service_tiers: [],
5
+ base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
6
+ supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
7
+ experimental_supported_tools: [], input_modalities: values.input_modalities || ["text"], ...template,
8
+ slug: model.public_id || model.id, display_name: model.display_name || model.id, description: name, visibility: "list", supported_in_api: true, priority,
9
+ default_reasoning_level: efforts[0] || null, supported_reasoning_levels: efforts.map(effort => ({ effort, description: effort })),
10
+ context_window: values.context_window || template.context_window || null, max_context_window: values.context_window || template.max_context_window || null };
11
+ }
12
+ export function codexClientCatalog(plan) {
13
+ return Object.assign((value, nativeCatalog) => ({ ...value, models: plan.models.map((model, priority) => {
14
+ const template = model.source_id === "github" ? nativeCatalog?.models?.find(entry => entry.slug === model.id) : undefined;
15
+ return codexModelEntry(model, { priority, template, name: model.source_id });
16
+ }) }), { needsNativeCatalog: plan.models.some(model => model.source_id === "github") });
17
+ }
18
+
19
+ export function codexSourceCatalog(source) {
20
+ return value => ({ ...value, models: source.models("gpt").map((model, priority) =>
21
+ codexModelEntry({ ...model, capability: model.protocol_capabilities?.responses || model.capability }, { priority, name: source.name || source.id })) });
22
+ }