codex-copilot-dx 1.2.17 → 1.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,13 +11,13 @@ 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.17/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.17/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.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).
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
 
18
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. Model sources owns API accounts, keys and model capabilities; application pages own visible models and defaults. Settings owns 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.
19
19
 
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.17 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.17.md) and [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. 1.2.18 preserves Codex sign-in and unavailable model selections after saving bindings. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings), [1.2.18 fixes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.18.md) and [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md).
21
21
 
22
22
  ## Commands
23
23
  | Command | Purpose |
@@ -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.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.
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
@@ -85,7 +100,13 @@ company-network inputs while omitting unrelated credentials and Node hooks.
85
100
 
86
101
  `client-gateway-keys.mjs` separates caller identity from display hints and upstream
87
102
  credentials. `codex-api-config.mjs` reconciles an owned provider/model/table with
88
- paired writes. Claude uses its existing mounted relay and field journal with
103
+ paired writes. Native sign-in material/store policy keeps OpenAI authentication
104
+ enabled for account operations; the static local bearer still takes precedence
105
+ for model requests. No native credential writer is added. GitHub-only bindings
106
+ retain legacy loopback callers but expose only selected models; any mixed or
107
+ non-GitHub binding requires the private Codex key. Bound catalog reads use their
108
+ compiled facade even when the default source is GitHub, without a live refresh.
109
+ Claude uses its existing mounted relay and field journal with
89
110
  independent app/code lifecycles. M365 beta policy is not imposed on API clients;
90
111
  adding a source alone never migrates old client credentials. Configuring clients
91
112
  does not patch/restart their binaries or override managed settings.
@@ -111,6 +132,8 @@ The existing Responses route-plan boundary continues to own opaque-state checks.
111
132
 
112
133
  `dashboard/connections.js` owns settings forms; application source/review and
113
134
  account/catalog views keep their existing scopes and use the same backend graph.
135
+ Its binding draft retains selected identities independently from current catalog
136
+ availability. Missing selections stay visible and cannot be silently dropped on save.
114
137
  Full configuration is on-demand; ordinary status uses compact cached summaries.
115
138
  Disabled sources and clients have separate restore lists inside their owning
116
139
  Settings cards, hidden when empty.
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
@@ -102,6 +109,25 @@ an API alone does not migrate existing M365 client credentials. First explicit
102
109
  Claude connection management installs private client keys; reopen affected apps.
103
110
  Codex reconciliation owns only the provider/model/table and preserves user edits.
104
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.
120
+
121
+ GitHub-only explicit bindings preserve the legacy native loopback access contract,
122
+ including requests from a process that has not yet reloaded its configuration.
123
+ Their catalog comes from the selected deployments, not a second live Copilot read.
124
+ Adding any non-GitHub deployment requires the private Codex key for the entire
125
+ catalog and all bound inference requests. Unselected models remain refused.
126
+ A supplied non-Codex bearer receives a local 403, not a ChatGPT 401 refresh
127
+ challenge. Missing credentials still receive 401; neither denial reaches upstream.
128
+ Temporarily unavailable selected models remain visible in the application editor.
129
+ Saving them fails without changing prior settings; refresh the catalog or explicitly
130
+ clear the affected selection. A missing directory entry never means deselection.
105
131
 
106
132
  A manual Codex provider includes an authenticated `model_catalog_url` on the same
107
133
  listener. Supported native selectors list configured custom names. Unknown names
@@ -144,13 +170,24 @@ model substitution, cross-source retry or automatic protocol conversion.
144
170
 
145
171
  Each custom model accepts an optional `capabilities` object with positive token
146
172
  limits (`context_window`, `max_input_tokens`, `max_output_tokens`), reasoning flags,
147
- `reasoning_efforts`, optional reasoning budget bounds/format, `input_modalities`,
173
+ `reasoning_efforts`, optional reasoning budget bounds/format, `thinking_modes`, `input_modalities`,
148
174
  boolean tools/parallel tools/streaming/structured output and a `web_search` array
149
175
  of supported native protocols. Empty arrays mean an explicit empty set; in the
150
176
  editor enter `[]`. Blank fields follow the current deployment catalog. Known
151
177
  numeric limits, flags and enums are strictly validated; arbitrary JSON is rejected.
152
178
 
153
179
  Discovery retains recognized structured fields with per-deployment timestamps.
180
+ The existing common catalog fields and Anthropic ModelInfo declarations are
181
+ supported. Anthropic `max_input_tokens`/`max_tokens`, thinking types, effort
182
+ levels, image input, structured output and native search are interpreted as
183
+ Messages capabilities. They do not automatically apply to Responses or Chat.
184
+ Effort and thinking modes remain distinct; declaring a server-side search tool
185
+ does not prove support for client tool calls. The current upstream's declarations
186
+ are authoritative for that deployment, not a model-name database or the original
187
+ vendor's published limits. See the [Anthropic Models API](https://platform.claude.com/docs/en/api/http/models/list).
188
+ Model details show values by interface, then optional manual overrides. ID-only
189
+ catalogs say that upstream did not provide capabilities; unrecognized capability
190
+ formats have a separate state. Parsed values are saved, not raw upstream JSON.
154
191
  Manual fields, including false/empty arrays, take priority over API declarations.
155
192
  ID-only results keep missing fields unknown. A failed refresh preserves saved
156
193
  metadata and records a bounded error; a changed endpoint/key invalidates prior
@@ -1227,7 +1264,7 @@ Unknown support prevents an explicitly requested exception from starting.
1227
1264
  For an older updater that still requires Git, install the Release tarball directly:
1228
1265
 
1229
1266
  ```sh
1230
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.17/codex-copilot-dx-1.2.17.tgz
1267
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.19/codex-copilot-dx-1.2.19.tgz
1231
1268
  # Windows PowerShell: use npm.cmd instead of npm.
1232
1269
  ```
1233
1270
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.17",
3
+ "version": "1.2.19",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -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
package/src/adapter.mjs CHANGED
@@ -315,7 +315,7 @@ export function createAdapterHandler(options = {}) {
315
315
  if (req.method === "GET" && pathname === "/v1/models") {
316
316
  const clientVersion = modelClientVersion(req.url);
317
317
  const selectedRegistry = target?.registry || codexModelRegistry;
318
- const selectedListModels = target && target.id !== "github" ? target.client.listModels : listModelsFn;
318
+ const selectedListModels = target && (target.id !== "github" || options.providerRuntime.hasModelBindings?.()) ? target.client.listModels : listModelsFn;
319
319
  const modelOptions = { codexModelCatalog, clientVersion, providerCatalog: target?.codexCatalog, restrictToUpstream: Boolean(target && target.id !== "github") };
320
320
  const abort = createRequestAbort(req, res);
321
321
  // Keep live discovery and explicit auth failures authoritative, but do
@@ -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,12 +1,14 @@
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 }) {
@@ -21,21 +23,13 @@ export function compileClientModels({ client, binding, source, enabled, names =
21
23
  const route = deploymentModelId(item.source, model.id), capability = model.capability || resolveModelCapabilities(model, { builtin: true });
22
24
  const entry = { ...model, capability, source_id: item.source, route_id: route,
23
25
  ...(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
- }
26
+ if (client === "claude_app" && explicit) entry.client_id = claudeDeploymentId(entry, route, { desktopEffortAliases });
31
27
  const publicId = explicit ? entry.client_id : client === "codex" ? model.id : claudeModelEntries([entry], { desktopAliases: client === "claude_app" && provider.id.startsWith("api_") })[0].name;
32
28
  entry.public_id = publicId;
33
29
  const record = { provider, model: entry, source: item.source, upstreamModel: model.id, publicId };
34
30
  if (routes.has(publicId)) throw Object.assign(new Error("Model routes collide"), { code: "ccdx_model_route_collision", statusCode: 503 });
35
31
  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
- }
32
+ if (client === "claude_app" && explicit) for (const alias of claudeRouteAliases(entry, route, true).slice(2)) routes.set(alias, record);
39
33
  models.push(entry);
40
34
  raw.set(model.id, raw.has(model.id) ? null : record);
41
35
  }
@@ -44,8 +38,7 @@ export function compileClientModels({ client, binding, source, enabled, names =
44
38
  for (const [id, record] of raw) if (record && !routes.has(id)) {
45
39
  routes.set(id, record);
46
40
  if (client !== "codex") {
47
- for (const options of [{ desktopAliases: false }, { desktopAliases: true }]) {
48
- const old = claudeModelEntries([{ ...record.model, client_id: undefined }], options)[0].name;
41
+ for (const old of claudeRouteAliases(record.model, record.model.route_id, false)) {
49
42
  if (!routes.has(old)) routes.set(old, record);
50
43
  }
51
44
  }
@@ -54,22 +47,3 @@ export function compileClientModels({ client, binding, source, enabled, names =
54
47
  return { models, routes, defaultModel: routes.get(binding.default_model)?.publicId || fallback?.public_id || null,
55
48
  revision: models.map(model => model.route_id + ":" + model.capability.revision).join(";") };
56
49
  }
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
+ }
@@ -8,6 +8,17 @@ import { atomicWriteFilePairSync } from "./atomic-file.mjs";
8
8
  import { withFileLockSync } from "./lock.mjs";
9
9
 
10
10
  const ID = "ccdx_gateway";
11
+ function retainsCodexSignIn(config, directory, env) {
12
+ if (["keyring", "auto"].includes(config.cli_auth_credentials_store) || config.forced_login_method
13
+ || config.forced_chatgpt_workspace_id || ["CODEX_ACCESS_TOKEN", "CODEX_API_KEY", "OPENAI_API_KEY"].some(key => env[key])) return true;
14
+ try {
15
+ const auth = JSON.parse(readBoundedFileSync(path.join(directory, "auth.json"), { encoding: "utf8", maxBytes: 1024 * 1024 }));
16
+ return Boolean(auth?.auth_mode || auth?.tokens || auth?.OPENAI_API_KEY);
17
+ } catch (error) {
18
+ if (error.code === "ENOENT") return false;
19
+ throw accessError("ccdx_codex_config_invalid", 409);
20
+ }
21
+ }
11
22
  // Only the provider, selected model and private provider table are owned.
12
23
  export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...options } = {}) {
13
24
  if (!restore) {
@@ -27,7 +38,9 @@ export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...
27
38
  const firstTable = content.search(/^\s*\[/m), head = firstTable < 0 ? content : content.slice(0, firstTable), tail = firstTable < 0 ? "" : content.slice(firstTable);
28
39
  const sectionPattern = /^\[model_providers\.ccdx_gateway\]\r?\n[^]*?(?=^\[|$(?![^]))/m;
29
40
  const currentSection = tail.match(sectionPattern)?.[0] || null;
30
- if (owner && (config.model_provider !== ID || currentSection !== owner.section || owner.model !== undefined && config.model !== owner.model)) return { state: "preserved" };
41
+ if (owner && (config.model_provider !== ID || currentSection !== owner.section)) return { state: "preserved" };
42
+ const modelEdited = owner?.model !== undefined && config.model !== owner.model;
43
+ if (restore && modelEdited) return { state: "preserved" };
31
44
  if (!owner && (config.model_provider && config.model_provider !== "openai" || config.model_providers?.[ID])) return { state: "preserved" };
32
45
  let next, nextOwner = null;
33
46
  if (restore) {
@@ -36,16 +49,19 @@ export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...
36
49
  if (owner.model !== undefined) root = root.replace(/^model\s*=.*(?:\r?\n|$)/m, owner.beforeModel || "");
37
50
  next = root + tail.replace(sectionPattern, owner.beforeSection || "");
38
51
  } else {
39
- const section = `[model_providers.${ID}]\nname = "CCDX"\nbase_url = ${JSON.stringify(baseUrl)}\nmodel_catalog_url = ${JSON.stringify(baseUrl + "/models")}\nwire_api = "responses"\nexperimental_bearer_token = ${JSON.stringify(apiKey)}\n\n`;
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`;
40
55
  let root = head;
41
- if (model) root = root.match(/^model\s*=/m) ? root.replace(/^model\s*=.*(?:\r?\n|$)/m, `model = ${JSON.stringify(model)}\n`) : `model = ${JSON.stringify(model)}\n` + root;
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;
42
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)
43
58
  + (currentSection ? tail.replace(sectionPattern, section) : tail + (tail && !tail.endsWith("\n") ? "\n" : "") + "\n" + section);
44
59
  nextOwner = { version: 1, beforeProvider: owner ? owner.beforeProvider : head.match(/^model_provider\s*=.*(?:\r?\n|$)/m)?.[0] || null,
45
60
  beforeSection: owner ? owner.beforeSection : currentSection, section,
46
- ...(model ? { model, beforeModel: owner && Object.hasOwn(owner, "beforeModel") ? owner.beforeModel : head.match(/^model\s*=.*(?:\r?\n|$)/m)?.[0] || null } : {}) };
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 } : {}) };
47
63
  }
48
64
  parse(next);if (next !== content || JSON.stringify(nextOwner) !== JSON.stringify(owner)) atomicWriteFilePairSync(file, next, journal, nextOwner ? JSON.stringify(nextOwner) + "\n" : null, { mode: 0o600 });
49
- return { state: "configured", changed: next !== content };
65
+ return { state: modelEdited ? "preserved" : "configured", changed: next !== content };
50
66
  });
51
67
  }
@@ -10,7 +10,8 @@ import { configureCodexApi } from "./codex-api-config.mjs";
10
10
  import { autoReviewReasoningEfforts } from "./models.mjs";
11
11
  import { createRequestAdmission } from "./request-admission.mjs";
12
12
  import { createConversationSourceGuard } from "./conversation-source-guard.mjs";
13
- import { compileClientModels, sourceModels, codexClientCatalog } from "./client-model-plan.mjs";
13
+ import { compileClientModels, sourceModels } from "./client-model-plan.mjs";
14
+ import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.mjs";
14
15
  import { currentRequestContext } from "./request-context.mjs";
15
16
  import { claudeSharedCapabilityPlan, syncClaudeCapabilities, inspectClaudeCapabilitySupport, inspectClaudeCapabilityConfiguration } from "./claude-capability-config.mjs";
16
17
  import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from "./model-capabilities.mjs";
@@ -18,12 +19,13 @@ import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from
18
19
  const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
19
20
  export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
20
21
  secretStore, createApi = createApiProvider, configureClaude = configureClaudeClients, restoreClaude = restoreClaudeClients,
21
- configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, log = () => {} } = {}) {
22
+ configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, now = Date.now, log = () => {} } = {}) {
22
23
  const options = { home, env, platform }, secrets = secretStore || createApiSecretStore(options);
23
24
  const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
24
25
  let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
25
26
  const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
26
27
  const retiredSecrets = new Map(), cleanups = new Set(), plans = new Map(), discoveries = new Map();
28
+ const catalogReads = new Map(), stopping = new AbortController();let refreshFlight;
27
29
  const capabilitySupport = inspectClaudeCapabilitySupport(options);
28
30
  let sharedSync = null, syncFlight = null, syncAgain = false;
29
31
  function cleanSecrets(id) {
@@ -38,14 +40,24 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
38
40
  const identities = () => keys ||= readClientGatewayKeys(options);
39
41
  const enabled = id => id?.startsWith("api_") ? settings.apis.find(api => api.id === id)?.enabled === true : settings.providers[id] === true;
40
42
  const binding = id => managed ? settings.clients[id] : { ...settings.clients[id], source: id === "codex" ? legacy.selection().codex : legacy.snapshot().m365.enabled ? "m365" : null };
43
+ // GitHub-only selections retain the existing native loopback access contract.
44
+ // Any other deployment still requires the private per-client credential.
45
+ const codexRequiresKey = () => !Array.isArray(binding("codex").deployments)
46
+ || !binding("codex").deployments.length || binding("codex").deployments.some(item => item.source !== "github");
47
+ function requireCodexKey(req) {
48
+ if (gatewayClient(req.headers, identities()) === "codex") return;
49
+ // An old native process may still send its ChatGPT bearer. A local access
50
+ // denial must not trigger recovery/replacement of that unrelated sign-in.
51
+ throw accessError("ccdx_client_credential_required", req.headers?.authorization ? 403 : 401);
52
+ }
41
53
  const permitted = (id, source) => binding(id)?.enabled && binding(id).allowed.includes(source) && enabled(source);
42
54
  function getSource(id) {
43
55
  if (!id?.startsWith("api_")) return legacy.source(id);
44
56
  const config = settings.apis.find(value => value.id === id);if (!config) return null;
45
- const previous = instances.get(id);if (previous?.config === config) return previous.source;
46
- const signature = JSON.stringify(config);
57
+ const previous = instances.get(id), revision = deploymentRevision(config, env);if (previous?.config === config && previous.revision === revision) return previous.source;
58
+ const signature = JSON.stringify(config) + revision;
47
59
  if (previous?.signature === signature) return previous.source;
48
- const source = createApi({ config, secrets, env, platform });instances.set(id, { signature, source, config });sourceSecrets.set(source, config.secret_ref);
60
+ const source = createApi({ config, secrets, env: { ...env }, platform });instances.set(id, { signature, source, config, revision });sourceSecrets.set(source, config.secret_ref);
49
61
  if (previous) retire(previous.source);return source;
50
62
  }
51
63
  function plan(id) {
@@ -85,7 +97,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
85
97
  }, options));managed = true;
86
98
  for (const [id, item] of instances) {
87
99
  const current = settings.apis.find(api => api.id === id);
88
- if (!current?.enabled || JSON.stringify(current) !== item.signature) { instances.delete(id);retire(item.source); }else item.config = current;
100
+ if (!current?.enabled || JSON.stringify(current) + deploymentRevision(current, env) !== item.signature) { instances.delete(id);retire(item.source); }else item.config = current;
89
101
  }
90
102
  }
91
103
  function summary(api) {
@@ -148,10 +160,53 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
148
160
  if (!body || typeof body !== "object" || Array.isArray(body)) return;
149
161
  if (managed && (binding(client).history_isolation || source?.id.startsWith("api_"))) guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client]);
150
162
  }
163
+ async function applyCatalog(id, models, revision, checkedAt) {
164
+ const next = editable(), current = next.apis.find(api => api.id === id);
165
+ if (!current?.enabled || deploymentRevision(current, env) !== revision) throw accessError("ccdx_connections_conflict", 409);
166
+ const byId = new Map(models.map(model => [model.id, model]));
167
+ for (const model of current.models) if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
168
+ current.checked_at = checkedAt;
169
+ if (JSON.stringify(current) !== JSON.stringify(settings.apis.find(api => api.id === id))) { save(next);await syncClients(); }
170
+ discoveries.set(id, { state: "ready", checked_at: checkedAt });
171
+ }
172
+ async function refreshApi(id, force = false) {
173
+ const config = settings.apis.find(api => api.id === id && api.enabled);
174
+ if (!config) throw accessError("ccdx_client_source_disabled", 503);
175
+ const revision = deploymentRevision(config, env), cached = catalogReads.get(id), age = cached ? now() - cached.at : Infinity;
176
+ if (cached?.revision === revision && age >= 0 && age < (force || cached.error ? 60000 : 30 * 60000)) {
177
+ if (cached.error) throw cached.error;await applyCatalog(id, cached.models, revision, new Date(cached.at).toISOString());return cached.models;
178
+ }
179
+ const savedAge = now() - Date.parse(config.checked_at);
180
+ if (!force && !cached && savedAge >= 0 && savedAge < 30 * 60000 && config.models.every(model => model.metadata?.state && model.metadata.deployment === revision)) return config.models;
181
+ const source = getSource(id), finish = track(source);
182
+ try {
183
+ const models = await source.discover({ signal: AbortSignal.any([stopping.signal, AbortSignal.timeout(20000)]) });
184
+ if (closed) throw accessError("ccdx_connections_closed", 503);
185
+ await applyCatalog(id, models, revision, new Date(now()).toISOString());
186
+ catalogReads.set(id, { revision, at: now(), models });
187
+ return models;
188
+ } catch (error) {
189
+ const code = /^ccdx_[a-z0-9_]+$/.test(error.code || "") ? error.code : "ccdx_api_catalog_unavailable";
190
+ const failure = accessError(code, [401, 403].includes(error.statusCode) ? error.statusCode : 502);
191
+ catalogReads.set(id, { revision, at: now(), error: failure });
192
+ discoveries.set(id, { state: "stale", code, checked_at: new Date(now()).toISOString() });throw failure;
193
+ } finally { finish(); }
194
+ }
195
+ function enqueue(work) { const job = serial.then(work);serial = job.catch(() => {});return job; }
196
+ function refreshApis() {
197
+ if (closed || !managed) return Promise.resolve();
198
+ refreshFlight ||= (async () => {
199
+ for (const api of settings.apis) {
200
+ if (closed) break;if (!api.enabled) continue;
201
+ await enqueue(() => closed ? undefined : refreshApi(api.id)).catch(() => {});
202
+ }
203
+ })().finally(() => { refreshFlight = null; });
204
+ return refreshFlight;
205
+ }
151
206
  async function change(input) {
152
207
  if (closed) throw accessError("ccdx_connections_closed", 503);
153
208
  if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "model", "auto_review_model", "auto_review_effort", "deployments", "default_model", "auto_sync"])) throw accessError("ccdx_connections_action_invalid");
154
- const next = editable();let freshRef, previousRef;
209
+ const next = editable();let freshRef, previousRef, savedApi;
155
210
  if (input.operation === "save_api") {
156
211
  const existing = next.apis.find(api => api.id === input.id);
157
212
  if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
@@ -172,7 +227,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
172
227
  }
173
228
  if (existing) { previousRef = existing.secret_ref;next.apis[next.apis.indexOf(existing)] = config; } else next.apis.push(config);
174
229
  checkedAccessSettings(next);
175
- try { if (freshRef) await secrets.set(freshRef, input.key);save(next); } catch (error) { if (freshRef) await secrets.remove(freshRef).catch(() => {});throw error; }
230
+ try { if (freshRef) await secrets.set(freshRef, input.key);save(next);savedApi = id; } catch (error) { if (freshRef) await secrets.remove(freshRef).catch(() => {});throw error; }
176
231
  } else if (["client", "preview_client"].includes(input.operation)) {
177
232
  if (!CLIENT_IDS.includes(input.id) || typeof input.enabled !== "boolean" || !Array.isArray(input.allowed)
178
233
  || input.source !== null && input.source !== undefined && !input.allowed.includes(input.source)) throw accessError("ccdx_connections_action_invalid");
@@ -211,7 +266,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
211
266
  const previous = c.source === "m365" ? legacy.selection().m365 : null;
212
267
  c.model = input.model || previous?.model || target.models("gpt")[0].id;c.auto_review_model = input.auto_review_model || previous?.auto_review_model || c.model;
213
268
  if (![c.model, c.auto_review_model].every(id => target.models("gpt").some(model => model.id === id))) throw accessError("ccdx_api_model_unavailable");
214
- const efforts = api ? api.models.find(model => model.id === c.auto_review_model)?.reasoning_efforts || []
269
+ const efforts = api ? sourceModels(target, "codex").find(model => model.id === c.auto_review_model)?.capability.values.reasoning_efforts || []
215
270
  : autoReviewReasoningEfforts(target.models("gpt").find(model => model.id === c.auto_review_model));
216
271
  if (c.auto_review_effort !== undefined && c.auto_review_effort !== null && !efforts.includes(c.auto_review_effort)) throw accessError("ccdx_api_effort_unavailable");
217
272
  }
@@ -261,20 +316,12 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
261
316
  }
262
317
  }
263
318
  } else if (input.operation === "discover") {
264
- if (!settings.apis.some(api => api.id === input.id && api.enabled)) throw accessError("ccdx_client_source_disabled", 503);
265
- try {
266
- const models = await getSource(input.id).discover({ signal: AbortSignal.timeout(20000) });
267
- const byId = new Map(models.map(model => [model.id, model]));
268
- const config = next.apis.find(api => api.id === input.id);
269
- for (const model of config.models) if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
270
- config.checked_at = new Date().toISOString();save(next);
271
- discoveries.set(input.id, { state: "ready", checked_at: config.checked_at });await syncClients();
272
- return { ...snapshot(), discovered: models };
273
- } catch (error) { discoveries.set(input.id, { state: "stale", code: error.code || "ccdx_api_catalog_unavailable", checked_at: new Date().toISOString() });throw error; }
319
+ const models = await refreshApi(input.id, true);return { ...snapshot(), discovered: models };
274
320
  } else throw accessError("ccdx_connections_action_invalid");
275
321
  await syncClients();
276
322
  if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
277
323
  if (previousRef && (freshRef || input.config?.key_env)) { if (!retiredSecrets.has(input.id)) retiredSecrets.set(input.id, new Set());retiredSecrets.get(input.id).add(previousRef);cleanSecrets(input.id); }
324
+ if (savedApi && enabled(savedApi)) await refreshApi(savedApi).catch(() => {});
278
325
  return snapshot();
279
326
  }
280
327
  return {
@@ -282,9 +329,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
282
329
  source: getSource,
283
330
  connections: snapshot,
284
331
  syncClients,
285
- manageConnections(input) { if (!input) return Promise.resolve(snapshot());const job = serial.then(() => change(input));serial = job.catch(() => {});return job; },
286
- async start() { const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();return result; },
287
- refresh() { return !managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(); },
332
+ manageConnections(input) { if (!input) return Promise.resolve(snapshot());return enqueue(() => change(input)); },
333
+ async start() { const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();void refreshApis();return result; },
334
+ async refresh() { const result = await Promise.allSettled([!managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(), refreshApis()]);if (result[0].status === "rejected") throw result[0].reason; },
288
335
  selection() { return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null }; },
289
336
  providerPreference(id) {
290
337
  const c = settings.clients.codex;
@@ -311,18 +358,18 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
311
358
  const c = binding("codex"), compiled = plan("codex");
312
359
  const source = requireSource("codex", Array.isArray(c.deployments) ? compiled.routes.get(compiled.defaultModel)?.source : c.source);
313
360
  if (Array.isArray(c.deployments) && req?.method === "GET") {
314
- if (gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
361
+ if (codexRequiresKey()) requireCodexKey(req);
315
362
  return { ...source, registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
316
363
  client: { ...source.client, listModels: async () => ({ status: 200, body: JSON.stringify({ data: compiled.models.map(model => ({ ...model, id: model.public_id })) }) }) },
317
- codexCatalog: codexClientCatalog(compiled, getSource) };
364
+ codexCatalog: codexClientCatalog(compiled) };
318
365
  }
319
- if (source?.id.startsWith("api_") && req && gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
320
- return source;
366
+ if (source?.id.startsWith("api_") && req) requireCodexKey(req);
367
+ return req?.method === "GET" && source?.configuredModels && source.id.startsWith("api_") ? { ...source, codexCatalog: codexSourceCatalog(source) } : source;
321
368
  },
322
369
  hasModelBindings(client = "codex") { return managed && Array.isArray(binding(client).deployments); },
323
370
  resolveCodex(body, req) {
324
371
  if (!managed || !Array.isArray(binding("codex").deployments)) return null;
325
- if (gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
372
+ if (codexRequiresKey()) requireCodexKey(req);
326
373
  const requested = body.model === "codex-auto-review" ? binding("codex").auto_review_model || plan("codex").defaultModel : body.model;
327
374
  if (body.model === "codex-auto-review") {
328
375
  delete body.service_tier;
@@ -419,6 +466,6 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
419
466
  if (managed && input.action === "switch") { const next = editable();if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;next.clients.codex.source = input.provider;next.clients.codex.deployments = null;next.clients.codex.default_model = null;for (const key of ["model", "auto_review_model", "auto_review_effort"]) delete next.clients.codex[key];if (input.provider === "m365") Object.assign(next.clients.codex, legacy.selection().m365);save(next);await syncClients(); }
420
467
  return result;
421
468
  },
422
- async close() { closed = true;await serial;await syncFlight;for (const { source } of instances.values()) source.close();for (const source of retired) source.close();active.clear();for (const id of retiredSecrets.keys()) cleanSecrets(id);await Promise.allSettled([...cleanups]);secrets.close();await legacy.close(); },
469
+ async close() { closed = true;stopping.abort();await refreshFlight;await serial;await syncFlight;for (const { source } of instances.values()) source.close();for (const source of retired) source.close();active.clear();for (const id of retiredSecrets.keys()) cleanSecrets(id);await Promise.allSettled([...cleanups]);secrets.close();await legacy.close(); },
423
470
  };
424
471
  }
@@ -83,19 +83,29 @@
83
83
  catch (error) { if (input.operation === "client") words(el("connection-client-note"), error.message);else message(error.message); }
84
84
  finally { busy = false;view?.removeAttribute("aria-busy"); }
85
85
  }
86
- const resolved = model => ({ ...(model.metadata?.deployment === source(editing)?.deployment_revision ? model.metadata.values : {}), ...(model.context_window === undefined ? {} : { context_window: model.context_window }),
87
- ...(model.reasoning_efforts === undefined ? {} : { reasoning_efforts: model.reasoning_efforts }), ...(model.capabilities || {}) });
86
+ const resolved = (model, protocol = model.protocols.includes("messages") ? "messages" : model.protocols[0]) => {
87
+ const metadata = model.metadata?.deployment === source(editing)?.deployment_revision ? model.metadata : null;
88
+ const values = { ...metadata?.values, ...metadata?.protocols?.[protocol], ...(model.context_window === undefined ? {} : { context_window: model.context_window }),
89
+ ...(model.reasoning_efforts === undefined ? {} : { reasoning_efforts: model.reasoning_efforts }), ...(model.capabilities || {}) };
90
+ if (values.reasoning_format && values.reasoning_format !== protocol) for (const key of Object.keys(values).filter(key => key.startsWith("reasoning"))) delete values[key];
91
+ if (values.reasoning === false) delete values.reasoning_efforts;
92
+ return values;
93
+ };
88
94
  const count = value => !value ? format("cap_unknown") : value >= 1000000 ? `${Number((value / 1000000).toFixed(2))}M` : value >= 1000 ? `${Number((value / 1000).toFixed(1))}K` : String(value);
89
95
  const reasoningText = values => values.reasoning === false ? format("cap_unsupported") : values.reasoning_efforts?.length ? values.reasoning_efforts.join(" / ") : values.reasoning === true ? format("cap_supported") : format("cap_unknown");
90
96
  const searchText = values => values.web_search === undefined ? format("cap_unknown") : values.web_search.length ? values.web_search.map(protocol => protocol === "messages" ? "Messages" : protocol === "responses" ? "Responses" : "Chat").join(" / ") : format("cap_unsupported");
91
97
  function modelDetail(model) {
92
98
  const detail = el("connection-model-detail");detail.hidden = false;detail.replaceChildren();
93
99
  const heading = node("div", undefined, "panel-heading");heading.append(node("h3", model.id), button("close", () => { detail.hidden = true; }));detail.append(heading);
94
- const note = node("p", undefined, "hint");words(note, "cap_metadata_scope");detail.append(note);
95
- const fields = node("div", undefined, "connection-fields"), values = resolved(model);
100
+ const protocol = choice(model.protocols.map(id => ({ id, name: id === "messages" ? "Messages" : id === "responses" ? "Responses" : "Chat" })), model.protocols.includes("messages") ? "messages" : model.protocols[0], false);
101
+ protocol.setAttribute("aria-label", format("cap_api"));detail.append(protocol);
102
+ const status = node("p", undefined, "hint"), table = node("table"), body = node("tbody");table.append(body);detail.append(status, table);
103
+ const advanced = node("details"), summary = node("summary");words(summary, "cap_manual");advanced.append(summary);detail.append(advanced);
104
+ const note = node("p", undefined, "hint");words(note, "cap_metadata_scope");advanced.append(note);
105
+ const fields = node("div", undefined, "connection-fields");
96
106
  const numeric = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max"];
97
107
  const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output"];
98
- const arrays = ["reasoning_efforts", "input_modalities", "web_search"];
108
+ const arrays = ["reasoning_efforts", "thinking_modes", "input_modalities", "web_search"];
99
109
  for (const key of [...numeric, ...flags, ...arrays, "reasoning_format"]) {
100
110
  const label = node("label"), title = node("span");words(title, "cap_field_" + key);label.append(title);
101
111
  let input;
@@ -107,10 +117,22 @@
107
117
  input.dataset.capability = key;
108
118
  const manual = model.capabilities?.[key] ?? (key === "context_window" ? model.context_window : key === "reasoning_efforts" ? model.reasoning_efforts : undefined);
109
119
  input.value = manual === undefined ? "" : Array.isArray(manual) ? manual.length ? manual.join(", ") : "[]" : String(manual);
110
- if (input.tagName === "INPUT") input.placeholder = values[key] === undefined ? format("cap_unknown") : Array.isArray(values[key]) ? values[key].join(", ") : String(values[key]);
111
- const evidence = node("span", undefined, "hint");words(evidence, manual !== undefined ? "cap_manual" : model.metadata?.deployment === source(editing)?.deployment_revision && model.metadata?.values[key] !== undefined ? "cap_catalog" : "cap_unknown");label.append(input, evidence);fields.append(label);
120
+ const evidence = node("span", undefined, "hint");words(evidence, manual !== undefined ? "cap_manual" : "cap_follow_catalog");label.append(input, evidence);fields.append(label);
112
121
  }
113
- detail.append(fields);
122
+ function showCapabilities() {
123
+ const values = resolved(model, protocol.value), fresh = model.metadata?.deployment === source(editing)?.deployment_revision;
124
+ words(status, fresh ? "cap_catalog_" + (model.metadata.state || "reported") : "cap_unknown");
125
+ if (fresh && model.metadata.checked_at) status.append(" · ", new Date(model.metadata.checked_at).toLocaleString());
126
+ body.replaceChildren();
127
+ for (const key of ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_efforts", "reasoning_adaptive", "tools", "input_modalities", "web_search"]) {
128
+ const row = node("tr"), label = node("th");words(label, ({ reasoning_efforts: "cap_reasoning", input_modalities: "cap_input_types", web_search: "cap_search" })[key] || "cap_field_" + key);
129
+ const value = values[key], text = key === "reasoning_efforts" ? reasoningText(values) : key === "web_search" ? searchText(values)
130
+ : value === undefined ? format("cap_unknown") : typeof value === "boolean" ? format(value ? "cap_supported" : "cap_unsupported") : Array.isArray(value) ? value.join(" / ") || format("cap_unsupported") : count(value);
131
+ row.append(label, node("td", text));body.append(row);
132
+ }
133
+ for (const input of fields.querySelectorAll("input[data-capability]")) { const value = values[input.dataset.capability];input.placeholder = value === undefined ? format("cap_unknown") : Array.isArray(value) ? value.join(", ") : String(value); }
134
+ }
135
+ protocol.addEventListener("change", showCapabilities);showCapabilities();advanced.append(fields);
114
136
  const save = button("cap_apply_details", () => {
115
137
  const override = {};
116
138
  for (const input of fields.querySelectorAll("[data-capability]")) {
@@ -118,7 +140,7 @@
118
140
  override[key] = numeric.includes(key) ? Number(text) : flags.includes(key) ? text === "true" : arrays.includes(key) ? text === "[]" ? [] : text.split(/[,,]\s*/).filter(Boolean) : text;
119
141
  }
120
142
  model.capabilities = override;delete model.context_window;delete model.reasoning_efforts;modelRows();detail.hidden = true;message("cap_details_draft");
121
- });detail.append(save);detail.scrollIntoView({ block: "nearest", behavior: "auto" });
143
+ });advanced.append(save);detail.scrollIntoView({ block: "nearest", behavior: "auto" });
122
144
  }
123
145
  function syncPreview(preview) {
124
146
  const c = client(editingClient), result = el("connection-sync-result");result.hidden = false;result.replaceChildren();
@@ -221,17 +243,20 @@
221
243
  function bindingRows() {
222
244
  el("connection-client-cancel").disabled = !bindingDirty;
223
245
  const body = el("connection-bindings"), c = client(editingClient);body.replaceChildren();
224
- for (const item of c.model_plan?.available || []) {
246
+ const available = c.model_plan?.available || [], availableKeys = new Set(available.map(item => bindingKey(item.source, item.id)));
247
+ const missing = [...bindingSelection].filter(key => !availableKeys.has(key)).map(key => { const [source, id] = key.split("\0");return { source, id, unavailable: true }; });
248
+ for (const item of [...available, ...missing]) {
225
249
  const key = bindingKey(item.source, item.id), row = node("tr"), name = node("td"), capability = item.capability?.values || {};
226
250
  const selection = check("binding-model", key, bindingSelection.has(key), item.id);
227
251
  selection.firstChild.addEventListener("change", event => {
228
252
  bindingDirty = true;if (event.target.checked) { bindingSelection.add(key);bindingDefault ||= routeId(item); }
229
- else { bindingSelection.delete(key);if (bindingDefault === routeId(item)) bindingDefault = (c.model_plan.available || []).find(entry => bindingSelection.has(bindingKey(entry.source, entry.id)))?.route_id || null; }
253
+ else { bindingSelection.delete(key);if (bindingDefault === routeId(item) || !available.some(entry => routeId(entry) === bindingDefault)) bindingDefault = available.find(entry => bindingSelection.has(bindingKey(entry.source, entry.id)))?.route_id || null; }
230
254
  bindingRows();
231
255
  });name.append(selection);
232
256
  const action = button(bindingDefault === routeId(item) && bindingSelection.has(key) ? "cap_default" : "cap_set_default", () => { bindingDirty = true;bindingSelection.add(key);bindingDefault = routeId(item);bindingRows(); });
233
257
  action.setAttribute("aria-pressed", String(bindingDefault === routeId(item) && bindingSelection.has(key)));
234
- const cell = node("td");cell.append(action);row.append(name, node("td", source(item.source)?.name || item.source), node("td", count(capability.context_window)), node("td", reasoningText(capability)), cell);body.append(row);
258
+ const cell = node("td");if (item.unavailable) words(cell, "cap_model_unavailable");else cell.append(action);
259
+ row.append(name, node("td", source(item.source)?.name || item.source), node("td", count(capability.context_window)), node("td", reasoningText(capability)), cell);body.append(row);
235
260
  }
236
261
  if (!body.children.length) { const row = node("tr"), cell = node("td");cell.colSpan = 5;words(cell, "cap_no_models");const link = node("a");link.href = "#models";words(link, "model_services");cell.append(" ", link);row.append(cell);body.append(row); }
237
262
  }
@@ -244,7 +269,7 @@
244
269
  el("connection-client-cancel").addEventListener("click", () => mountClient(true));
245
270
  function bindingInput(operation) {
246
271
  const c = client(editingClient);return { operation, id: c.id, enabled: true, allowed: c.allowed,
247
- deployments: (c.model_plan?.available || []).filter(item => bindingSelection.has(bindingKey(item.source, item.id))).map(item => ({ source: item.source, model: item.id })),
272
+ deployments: [...bindingSelection].map(key => { const [source, model] = key.split("\0");return { source, model }; }),
248
273
  default_model: bindingDefault, auto_sync: el("connection-auto-sync").checked };
249
274
  }
250
275
  clientForm.addEventListener("submit", event => { event.preventDefault();void change(bindingInput("client")); });
@@ -24,7 +24,12 @@
24
24
  "cap_follow_catalog": ["Use catalog value", "跟随目录"],
25
25
  "cap_manual": ["Manual override", "手动设置"],
26
26
  "cap_catalog": ["Declared by this API", "此 API 目录声明"],
27
- "cap_metadata_scope": ["Blank uses this API’s catalog. Missing fields remain unknown.", "留空时跟随此 API 目录,缺失字段保持待确认。"],
27
+ "cap_metadata_scope": ["Overrides apply to this model's configured APIs. Leave blank to use upstream values.", "手动值适用于此模型的已选接口;留空跟随上游。"],
28
+ "cap_api": ["API", "接口"],
29
+ "cap_input_types": ["Input types", "输入类型"],
30
+ "cap_catalog_reported": ["Read from upstream", "已从上游读取"],
31
+ "cap_catalog_missing": ["Upstream did not provide capabilities", "上游未提供能力资料"],
32
+ "cap_catalog_unrecognized": ["Upstream capability format not recognized", "暂未识别上游能力格式"],
28
33
  "cap_apply_details": ["Apply to draft", "应用到草稿"],
29
34
  "cap_details_draft": ["Details updated. Save the source to apply.", "能力已加入草稿,请保存来源。"],
30
35
  "cap_preview_scope": ["Save to apply. Restart Claude after its settings change.", "保存后同步;Claude 配置更新后需重启。"],
@@ -51,6 +56,7 @@
51
56
  "cap_field_reasoning_budget_max": ["Maximum reasoning budget", "最大推理预算"],
52
57
  "cap_field_reasoning_efforts": ["Reasoning levels (comma separated)", "推理等级(逗号分隔)"],
53
58
  "cap_field_reasoning_format": ["Reasoning API", "推理参数接口"],
59
+ "cap_field_thinking_modes": ["Thinking modes", "思考模式"],
54
60
  "cap_field_input_modalities": ["Input types (text, image, …)", "输入类型(text、image 等)"],
55
61
  "cap_field_tools": ["Tool calls", "工具调用"],
56
62
  "cap_field_parallel_tools": ["Parallel tool calls", "并行工具调用"],
@@ -125,7 +131,8 @@
125
131
  "ccdx_api_name_exists": ["This source name is already used. Choose another name.", "来源名称已存在,请换一个名称。"],
126
132
  "ccdx_api_model_reserved": ["codex-auto-review is reserved by CCDX. Enter the real upstream model ID.", "codex-auto-review 为内部名称,请填真实模型 ID。"],
127
133
  "ccdx_connections_limit": ["Connection settings exceed the 8 MiB limit.", "接入配置超过 8 MiB 上限。"],
128
- "ccdx_api_model_unavailable": ["Choose a configured model with the required API.", "请选择支持对应接口的已配置模型。"],
134
+ "ccdx_api_model_unavailable": ["Selected model unavailable. Refresh or clear its selection.", "所选模型暂不可用,请刷新或取消选择。"],
135
+ "cap_model_unavailable": ["Unavailable", "暂不可用"],
129
136
  "ccdx_api_protocol_required": ["Claude needs Messages; Codex needs Responses.", "Claude 需 Messages;Codex 需 Responses。"],
130
137
  "ccdx_api_effort_unavailable": ["Choose a reasoning level advertised by this model, or follow the client.", "请选择模型支持的推理档位,或跟随客户端。"],
131
138
  "ccdx_source_in_use": ["Change the current source or pause its clients first.", "请先更换来源,或暂停相关客户端。"],
@@ -4,14 +4,14 @@ export const MODEL_PROTOCOLS = Object.freeze(["messages", "responses", "chat"]);
4
4
  export const REASONING_EFFORTS = Object.freeze(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
5
5
  const limits = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max"];
6
6
  const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output"];
7
- export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "input_modalities", "web_search"]);
7
+ export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "thinking_modes", "input_modalities", "web_search"]);
8
8
  const object = value => value && typeof value === "object" && !Array.isArray(value);
9
9
  export function validCapabilities(value) {
10
10
  return object(value) && Object.entries(value).every(([key, item]) => {
11
11
  if (limits.includes(key)) return Number.isSafeInteger(item) && item > 0 && item <= 100000000;
12
12
  if (flags.includes(key)) return typeof item === "boolean";
13
13
  if (key === "reasoning_format") return MODEL_PROTOCOLS.includes(item);
14
- const choices = key === "reasoning_efforts" ? REASONING_EFFORTS : key === "input_modalities" ? ["text", "image", "audio", "video", "file"] : key === "web_search" ? MODEL_PROTOCOLS : null;
14
+ const choices = key === "reasoning_efforts" ? REASONING_EFFORTS : key === "thinking_modes" ? ["disabled", "enabled", "adaptive", "between_tools"] : key === "input_modalities" ? ["text", "image", "audio", "video", "file"] : key === "web_search" ? MODEL_PROTOCOLS : null;
15
15
  return choices && Array.isArray(item) && item.length <= choices.length && new Set(item).size === item.length && item.every(v => choices.includes(v));
16
16
  }) && !(value.max_input_tokens && value.context_window && value.max_input_tokens > value.context_window)
17
17
  && !(value.reasoning_budget_min && value.reasoning_budget_max && value.reasoning_budget_min > value.reasoning_budget_max);
@@ -40,7 +40,7 @@ export function catalogCapabilities(model) {
40
40
  reasoning_efforts: first(model.reasoning_efforts, supports.reasoning_effort),
41
41
  input_modalities: first(model.input_modalities, caps.input_modalities),
42
42
  tools: supports.tools, parallel_tools: supports.parallel_tool_calls, streaming: supports.streaming,
43
- structured_output: supports.structured_output, web_search: first(model.web_search, caps.web_search),
43
+ structured_output: supports.structured_output, web_search: first(model.web_search, caps.web_search), thinking_modes: first(model.thinking_modes, caps.thinking_modes),
44
44
  ...Object.fromEntries(["reasoning_required", "reasoning_adaptive", "reasoning_budget_min", "reasoning_budget_max", "reasoning_format"].map(key => [key, first(model[key], caps[key])])),
45
45
  };
46
46
  for (const [key, value] of Object.entries(candidate)) if (value !== undefined && validCapabilities({ [key]: value })) values[key] = value;
@@ -49,17 +49,22 @@ export function catalogCapabilities(model) {
49
49
  return values;
50
50
  }
51
51
 
52
- export function resolveModelCapabilities(model, { revision, checkedAt = null, builtin = false } = {}) {
53
- const fields = {}, declared = builtin ? catalogCapabilities(model) : model.metadata?.deployment === revision ? model.metadata.values : {};
52
+ export function resolveModelCapabilities(model, { revision, checkedAt = null, builtin = false, protocol } = {}) {
53
+ const metadata = model.metadata?.deployment === revision ? model.metadata : null;
54
+ const fields = {}, declared = builtin ? catalogCapabilities(model) : { ...metadata?.values, ...metadata?.protocols?.[protocol] };
54
55
  const put = (values, source, time) => { for (const [key, value] of Object.entries(values || {})) fields[key] = { value, source, checked_at: time }; };
55
56
  put(declared, "catalog", builtin ? checkedAt : model.metadata?.checked_at || null);
56
57
  put({ ...(model.context_window === undefined ? {} : { context_window: model.context_window }),
57
58
  ...(model.reasoning_efforts === undefined ? {} : { reasoning_efforts: model.reasoning_efforts }) }, "manual", null);
58
59
  put(model.capabilities, "manual", null);
59
60
  const values = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.value]));
61
+ if (protocol && values.reasoning_format && values.reasoning_format !== protocol) {
62
+ for (const key of ["reasoning", "reasoning_efforts", "reasoning_required", "reasoning_adaptive", "reasoning_budget_min", "reasoning_budget_max", "reasoning_format", "thinking_modes"]) delete values[key];
63
+ }
60
64
  if (values.reasoning === false) { delete values.reasoning_efforts;delete values.reasoning_adaptive;delete values.reasoning_required; }
61
65
  const revisionId = createHash("sha256").update(JSON.stringify([revision, values])).digest("hex").slice(0, 16);
62
- return { values, fields, revision: revisionId, stale: Boolean(model.metadata && model.metadata.deployment !== revision) };
66
+ return { values, fields, revision: revisionId, stale: Boolean(model.metadata && model.metadata.deployment !== revision),
67
+ ...(metadata?.state ? { catalog_state: metadata.state } : {}) };
63
68
  }
64
69
 
65
70
  export function claudeEffortsExpressible(values = {}) {
@@ -81,6 +86,9 @@ export function constrainModelRequest(body, capability, protocol) {
81
86
  if (values.reasoning === false && body.thinking && body.thinking.type !== "disabled") {
82
87
  throw Object.assign(new Error("Reasoning is disabled for this model."), { code: "ccdx_api_reasoning_unavailable", statusCode: 400 });
83
88
  }
89
+ if (protocol === "messages" && body.thinking?.type && values.thinking_modes && !values.thinking_modes.includes(body.thinking.type)) {
90
+ throw Object.assign(new Error("This model does not declare the selected thinking mode."), { code: "ccdx_api_thinking_unavailable", statusCode: 400 });
91
+ }
84
92
  const budget = body.thinking?.budget_tokens;
85
93
  if (Number.isFinite(budget) && (values.reasoning_budget_min && budget < values.reasoning_budget_min || values.reasoning_budget_max && budget > values.reasoning_budget_max
86
94
  || applied.includes("output_limit") && Number.isFinite(result.max_tokens) && budget >= result.max_tokens)) {
@@ -4,7 +4,7 @@ export const isProviderId = value => typeof value === "string" && /^[a-z][a-z0-9
4
4
  && !["constructor", "prototype"].includes(value);
5
5
 
6
6
  export function modelReasoningEfforts(model) {
7
- const values = model?.capabilities?.supports?.reasoning_effort;
7
+ const values = model?.capability ? model.capability.values.reasoning === false ? [] : model.capability.values.reasoning_efforts : model?.capabilities?.supports?.reasoning_effort;
8
8
  return Array.isArray(values) ? [...new Set(values.filter(value => typeof value === "string" && /^[a-z][a-z0-9_-]{0,15}$/.test(value)))].slice(0, 16) : null;
9
9
  }
10
10
 
@@ -14,9 +14,9 @@ export function publicModelCatalog(models, { clients = () => [], selectable = ()
14
14
  endpoints: [["responses", ["/responses", "/v1/responses"]], ["chat", ["/chat/completions", "/v1/chat/completions"]],
15
15
  ["messages", ["/v1/messages"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
16
16
  preview: model.preview === true, selectable: selectable(model), clients: clients(model),
17
- reasoning_efforts: modelReasoningEfforts(model), auto_review_efforts: autoReviewReasoningEfforts(model),
18
- context_window: Number.isSafeInteger(model.capabilities?.limits?.max_context_window_tokens)
19
- && model.capabilities.limits.max_context_window_tokens > 0 ? model.capabilities.limits.max_context_window_tokens : null,
17
+ reasoning_efforts: modelReasoningEfforts(model), auto_review_efforts: model.capability ? modelReasoningEfforts(model) || [] : autoReviewReasoningEfforts(model),
18
+ context_window: model.capability?.values.context_window ?? (Number.isSafeInteger(model.capabilities?.limits?.max_context_window_tokens)
19
+ && model.capabilities.limits.max_context_window_tokens > 0 ? model.capabilities.limits.max_context_window_tokens : null),
20
20
  state: model.policy?.state && model.policy.state !== "enabled" ? "restricted" : model.model_picker_enabled === false ? "hidden" : "listed",
21
21
  }));
22
22
  }
@@ -0,0 +1,36 @@
1
+ import { catalogCapabilities, validCapabilities } from "../model-capabilities.mjs";
2
+
3
+ // Interpret the catalog's declared schema, never the model's name. Anthropic
4
+ // fields describe Messages; a gateway exposing other APIs must declare those
5
+ // separately. No inference request is used to fill missing information.
6
+ export function apiModelMetadata(model, { deployment, checked_at }) {
7
+ const values = catalogCapabilities(model), caps = model.capabilities || {}, messages = {};
8
+ const anthropic = model.type === "model" && Object.hasOwn(model, "max_tokens") || typeof caps.thinking?.supported === "boolean" || typeof caps.effort?.supported === "boolean";
9
+ if (anthropic) {
10
+ const put = (key, value) => { if (value !== undefined && validCapabilities({ [key]: value })) messages[key] = value; };
11
+ put("context_window", model.max_input_tokens);
12
+ put("max_input_tokens", model.max_input_tokens);
13
+ put("max_output_tokens", model.max_tokens);
14
+ put("reasoning", caps.effort?.supported === true ? true : caps.thinking?.supported);
15
+ if (caps.thinking?.supported === false) put("thinking_modes", ["disabled"]);
16
+ else if (caps.thinking?.supported === true && caps.thinking.types) put("thinking_modes", ["disabled", "enabled", "adaptive", "between_tools"].filter(mode => caps.thinking.types[mode]?.supported === true));
17
+ put("reasoning_adaptive", caps.thinking?.types?.adaptive?.supported);
18
+ if (caps.effort?.supported === false) put("reasoning_efforts", []);
19
+ else if (caps.effort?.supported === true) {
20
+ const efforts = ["low", "medium", "high", "xhigh", "max"].filter(level => caps.effort[level]?.supported === true);
21
+ if (efforts.length) put("reasoning_efforts", efforts);
22
+ }
23
+ if (messages.reasoning_efforts?.length || messages.reasoning !== undefined) put("reasoning_format", "messages");
24
+ put("structured_output", caps.structured_outputs?.supported);
25
+ if (typeof caps.server_tools?.web_search?.supported === "boolean") put("web_search", caps.server_tools.web_search.supported ? ["messages"] : []);
26
+ // Image/PDF flags do not establish support for arbitrary files or audio.
27
+ if (caps.image_input?.supported === true) put("input_modalities", ["text", "image"]);
28
+ // Native input/output limits must not leak to another gateway API.
29
+ delete values.max_input_tokens;
30
+ }
31
+ const protocols = Object.keys(messages).length ? { messages } : {};
32
+ const reported = Object.keys(values).length || Object.keys(protocols).length;
33
+ const described = Object.keys(caps).length || ["max_tokens", "max_input_tokens", "max_output_tokens", "context_window", "reasoning_efforts"].some(key => Object.hasOwn(model, key));
34
+ return { values, ...(Object.keys(protocols).length ? { protocols } : {}), deployment, checked_at,
35
+ state: reported ? "reported" : described ? "unrecognized" : "missing" };
36
+ }
@@ -7,6 +7,7 @@ import { createProxyAgent } from "../proxy-tunnel.mjs";
7
7
  import { apiUrl, accessError } from "../access-settings.mjs";
8
8
  import { privateHelperEnvironment } from "../private-helper-environment.mjs";
9
9
  import { transportErrorDetails } from "../operation-error.mjs";
10
+ import { apiTargetAllowed } from "../api-target.mjs";
10
11
 
11
12
  export async function createApiNetwork({ targets, env = process.env, platform = process.platform, signal,
12
13
  requestImpl = https.request, exec = promisify(execFile), startWindowsNetwork } = {}) {
@@ -30,7 +31,7 @@ export async function createApiNetwork({ targets, env = process.env, platform =
30
31
  fetch(raw, init = {}) {
31
32
  return new Promise((resolve, reject) => {
32
33
  let url;try { url = new URL(raw); } catch { reject(accessError("ccdx_api_url_invalid"));return; }
33
- if (closed || retiring || !urls.has(url.href) || !["GET", "POST"].includes(init.method || "GET")) { reject(accessError("ccdx_api_url_invalid"));return; }
34
+ if (closed || retiring || !apiTargetAllowed(url.href, [...urls], init.method || "GET") || !["GET", "POST"].includes(init.method || "GET")) { reject(accessError("ccdx_api_url_invalid"));return; }
34
35
  if (init.signal?.aborted) { reject(init.signal.reason);return; }
35
36
  active++;
36
37
  let req, incoming, socket, phase = "request", handedOff = false, released = false;
@@ -52,7 +53,7 @@ export async function createApiNetwork({ targets, env = process.env, platform =
52
53
  };
53
54
  const abort = () => { req?.destroy(init.signal.reason || accessError("ccdx_api_cancelled"));incoming?.destroy(); };
54
55
  try {
55
- req = requestImpl({ hostname: worker ? url.hostname : url.hostname.replace(/^\[|\]$/g, ""), port: Number(url.port || 443), protocol: "https:", path: url.pathname,
56
+ req = requestImpl({ hostname: worker ? url.hostname : url.hostname.replace(/^\[|\]$/g, ""), port: Number(url.port || 443), protocol: "https:", path: url.pathname + url.search,
56
57
  method: init.method || "GET", headers: { ...Object.fromEntries(new Headers(init.headers)), "accept-encoding": "identity" }, agent, rejectUnauthorized: true }, res => {
57
58
  phase = "response";incoming = res;
58
59
  const finished = () => { cleanup();release(); };
@@ -10,16 +10,17 @@ import { markUpstreamHeaders } from "../stream-performance.mjs";
10
10
  import { createApiNetwork } from "./api-network.mjs";
11
11
  import { checkedApiKey } from "../api-secrets.mjs";
12
12
  import { transportErrorDetails } from "../operation-error.mjs";
13
- import { catalogCapabilities, resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
14
- import { codexModelEntry } from "../client-model-plan.mjs";
13
+ import { resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
14
+ import { apiModelMetadata } from "./api-model-metadata.mjs";
15
15
  import { markRequestObservation } from "../stream-performance.mjs";
16
16
 
17
17
  const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
18
18
  export function apiCatalog(config, env = process.env) {
19
- return config.models.map(model => { const capability = resolveModelCapabilities(model, { revision: deploymentRevision(config, env) });return ({ id: model.id, name: model.id, publisher: "Unknown",
19
+ const revision = deploymentRevision(config, env);
20
+ return config.models.map(model => { const protocol_capabilities = Object.fromEntries(model.protocols.map(protocol => [protocol, resolveModelCapabilities(model, { revision, protocol })]));
21
+ const capability = protocol_capabilities[model.protocols.includes("messages") ? "messages" : model.protocols[0]];return ({ id: model.id, name: model.id, publisher: "Unknown",
20
22
  supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
21
- capability, capabilities: { limits: { max_context_window_tokens: capability.values.context_window, max_output_tokens: capability.values.max_output_tokens },
22
- supports: { reasoning_effort: capability.values.reasoning_efforts || [] } } }); });
23
+ capability, protocol_capabilities }); });
23
24
  }
24
25
  export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork } = {}) {
25
26
  const catalog = apiCatalog(config, env);
@@ -60,7 +61,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
60
61
  for (const name of ["anthropic-version", "anthropic-beta"]) { const value = options.headers?.[name];if (typeof value === "string" && value.length < 8192 && !/[\r\n]/.test(value)) headers[name] = value; }
61
62
  }
62
63
  if (body && !options.countTokens) {
63
- const capability = catalog.find(model => model.id === body.model)?.capability;
64
+ const capability = catalog.find(model => model.id === body.model)?.protocol_capabilities[api];
64
65
  const constrained = constrainModelRequest(body, capability, api);
65
66
  if (constrained.body !== body) { body = constrained.body;options = { ...options, bodyText: undefined }; }
66
67
  markRequestObservation({ capability_revision: capability?.revision, capability_constraints: constrained.applied.join(",") || "none" });
@@ -107,26 +108,33 @@ export function createApiProvider({ config, secrets, env = process.env, platform
107
108
  },
108
109
  };
109
110
  return {
110
- id: config.id, client, registry, configuredModels: true, defaultReviewEffort: null, profileId: (protocol = "responses") => profiles[protocol] || profile, models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : paths.responses)),
111
- codexCatalog(models) {
112
- return { ...models, models: catalog.filter(model => model.supported_endpoints.includes(paths.responses)).map((model, priority) => codexModelEntry(model, { priority, name: config.name })) };
113
- },
111
+ id: config.id, name: config.name, client, registry, configuredModels: true, defaultReviewEffort: null, profileId: (protocol = "responses") => profiles[protocol] || profile,
112
+ models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : paths.responses))
113
+ .map(model => ({ ...model, capability: model.protocol_capabilities[family === "claude" ? "messages" : "responses"] })),
114
114
  catalog: () => catalog,
115
115
  publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
116
116
  advertised: catalog.length, models: publicModelCatalog(catalog, { selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
117
117
  clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
118
- capability: catalog.find(entry => entry.id === model.id)?.capability, auto_review_efforts: [...(catalog.find(entry => entry.id === model.id)?.capability.values.reasoning_efforts || [])] })) }; },
118
+ capability: catalog.find(entry => entry.id === model.id)?.capability, auto_review_efforts: [...(catalog.find(entry => entry.id === model.id)?.protocol_capabilities.responses?.values.reasoning_efforts || [])] })) }; },
119
119
  async discover({ signal } = {}) {
120
- const response = await request(modelsUrl, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
120
+ const models = [], ids = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
121
+ for (let page = 0; page < 25; page++) {
122
+ const response = await request(url, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
121
123
  if (!response.ok) { await response.body?.cancel();throw accessError(`ccdx_api_catalog_http_${response.status}`, response.status === 401 || response.status === 403 ? response.status : 502); }
122
- const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES, label: "API model catalog", signal });
124
+ const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES - bytes, label: "API model catalog", signal });bytes += Buffer.byteLength(text);
123
125
  let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
124
- if (!Array.isArray(value.data) || value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
125
- const ids = new Set();
126
- for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || ids.has(model.id)) throw accessError("ccdx_api_catalog_invalid", 502);ids.add(model.id); }
126
+ if (!Array.isArray(value.data) || models.length + value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
127
+ for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || model.id.includes("..") || model.id.includes("//") || ids.has(model.id)) throw accessError("ccdx_api_catalog_invalid", 502);ids.add(model.id); }
127
128
  // A catalog listing is not evidence that every model supports every API.
128
- return value.data.map(model => ({ id: model.id, ...(Object.keys(catalogCapabilities(model)).length ? { metadata: { values: catalogCapabilities(model), checked_at: new Date().toISOString(), deployment: deploymentRevision(config, env) } } : {}), protocols: Array.isArray(model.supported_endpoints)
129
- ? Object.entries(paths).filter(([, endpoint]) => model.supported_endpoints.includes(endpoint) || model.supported_endpoints.includes(endpoint.slice(3))).map(([api]) => api).filter(api => config.endpoints[api]) : [] }));
129
+ models.push(...value.data.map(model => ({ id: model.id, metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
130
+ ? Object.entries(paths).filter(([, endpoint]) => model.supported_endpoints.includes(endpoint) || model.supported_endpoints.includes(endpoint.slice(3))).map(([api]) => api).filter(api => config.endpoints[api]) : [] })));
131
+ if (value.has_more !== true) return models;
132
+ // Follow only the native cursor on the configured origin, never an
133
+ // upstream next-page URL that could disclose this source's credential.
134
+ if (!value.data.length || value.last_id !== value.data.at(-1).id || bytes >= MAX_UPSTREAM_MODEL_CATALOG_BYTES) throw accessError("ccdx_api_catalog_invalid", 502);
135
+ const next = new URL(modelsUrl);next.searchParams.set("after_id", value.last_id);url = next.href;
136
+ }
137
+ throw accessError("ccdx_api_catalog_limit", 502);
130
138
  },
131
139
  selectModel(_body, { upstreamModel }) { selected(upstreamModel, "responses");return { upstreamModel, forceResponses: true }; },
132
140
  route(_body, { upstreamModel, surface }) { return createRoutePlan({ disposition: "relay", origin: config.id, profile, protocol: "openai-responses", model: upstreamModel, surface }); },
@@ -72,7 +72,7 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
72
72
  if(!allowedHosts.includes(host)||!String(options.path).startsWith("/")||target !== "api" && String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
73
73
  if(target === "m365" && !String(options.path).startsWith("/api/v1/llmapi/")) throw failure("proxy_target_invalid");
74
74
  const requestUrl = `https://${host}${options.port && Number(options.port) !== 443 ? `:${options.port}` : ""}${options.path}`;
75
- if(target === "api" && !apiTargets.includes(requestUrl)) throw failure("proxy_target_invalid");
75
+ if(target === "api" && !apiTargetAllowed(requestUrl, apiTargets, options.method || "GET")) throw failure("proxy_target_invalid");
76
76
  const headers=[];
77
77
  for(const [name,value]of Object.entries(options.headers||{})){
78
78
  if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(name))throw failure("proxy_headers_invalid");
@@ -125,3 +125,4 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
125
125
  };
126
126
  return {script,requestImpl,healthy:()=>!stopped,close(){closing=true;stop(failure("proxy_worker_closed"));}};
127
127
  }
128
+ import { apiTargetAllowed } from "./api-target.mjs";
@@ -74,11 +74,17 @@ public static class CCDXPredictionNetwork {
74
74
  }
75
75
  } finally { if(request!=IntPtr.Zero)WinHttpCloseHandle(request);if(connection!=IntPtr.Zero)WinHttpCloseHandle(connection); }
76
76
  }
77
+ static bool ApiTargetAllowed(Uri uri, string method) {
78
+ if(apiTargets.Contains(uri.AbsoluteUri))return true;
79
+ if(method!="GET" || !uri.AbsolutePath.EndsWith("/models",StringComparison.Ordinal) || !uri.Query.StartsWith("?after_id=",StringComparison.Ordinal) || uri.Query.IndexOf('&')>=0)return false;
80
+ string cursor=Uri.UnescapeDataString(uri.Query.Substring(10));
81
+ return System.Text.RegularExpressions.Regex.IsMatch(cursor,"^[A-Za-z0-9_][A-Za-z0-9_./:@+\\-]{0,159}$") && !cursor.Contains("..") && !cursor.Contains("//") && apiTargets.Contains(uri.GetLeftPart(UriPartial.Path));
82
+ }
77
83
  static void Request(Dictionary<string,object> data, int id, Work work) {
78
84
  IntPtr connection=IntPtr.Zero;
79
85
  try {
80
86
  var uri=new Uri((string)data["url"]);
81
- if(uri.Scheme!="https" || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0 || (target=="api" ? !apiTargets.Contains(uri.AbsoluteUri) : (uri.Port!=443 || (target=="m365" ? (uri.Host!="df.loki.delve.office.com" || !uri.AbsolutePath.StartsWith("/api/v1/llmapi/",StringComparison.Ordinal)) : (uri.Host!="chatgpt.com"&&uri.Host!="ab.chatgpt.com"))))) throw new IOException("winhttp_target_invalid");
87
+ if(uri.Scheme!="https" || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0 || (target=="api" ? !ApiTargetAllowed(uri,(string)data["method"]) : (uri.Port!=443 || (target=="m365" ? (uri.Host!="df.loki.delve.office.com" || !uri.AbsolutePath.StartsWith("/api/v1/llmapi/",StringComparison.Ordinal)) : (uri.Host!="chatgpt.com"&&uri.Host!="ab.chatgpt.com"))))) throw new IOException("winhttp_target_invalid");
82
88
  var method=(string)data["method"];
83
89
  if(method!="GET"&&method!="POST"&&method!="HEAD"&&method!="PUT"&&method!="DELETE"&&method!="OPTIONS"&&method!="PATCH")throw new IOException("winhttp_method_invalid");
84
90
  var headers=(string)data["headers"];