codex-copilot-dx 1.2.18 → 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,7 +11,7 @@ npm install -g codex-copilot-dx@latest
11
11
  ccdx
12
12
  ```
13
13
 
14
- No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.18/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.18/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
14
+ No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.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
 
@@ -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
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
@@ -163,13 +170,24 @@ model substitution, cross-source retry or automatic protocol conversion.
163
170
 
164
171
  Each custom model accepts an optional `capabilities` object with positive token
165
172
  limits (`context_window`, `max_input_tokens`, `max_output_tokens`), reasoning flags,
166
- `reasoning_efforts`, optional reasoning budget bounds/format, `input_modalities`,
173
+ `reasoning_efforts`, optional reasoning budget bounds/format, `thinking_modes`, `input_modalities`,
167
174
  boolean tools/parallel tools/streaming/structured output and a `web_search` array
168
175
  of supported native protocols. Empty arrays mean an explicit empty set; in the
169
176
  editor enter `[]`. Blank fields follow the current deployment catalog. Known
170
177
  numeric limits, flags and enums are strictly validated; arbitrary JSON is rejected.
171
178
 
172
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.
173
191
  Manual fields, including false/empty arrays, take priority over API declarations.
174
192
  ID-only results keep missing fields unknown. A failed refresh preserves saved
175
193
  metadata and records a bounded error; a changed endpoint/key invalidates prior
@@ -1246,7 +1264,7 @@ Unknown support prevents an explicitly requested exception from starting.
1246
1264
  For an older updater that still requires Git, install the Release tarball directly:
1247
1265
 
1248
1266
  ```sh
1249
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.18/codex-copilot-dx-1.2.18.tgz
1267
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.19/codex-copilot-dx-1.2.19.tgz
1250
1268
  # Windows PowerShell: use npm.cmd instead of npm.
1251
1269
  ```
1252
1270
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.18",
3
+ "version": "1.2.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
@@ -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
+ }
@@ -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) {
@@ -52,10 +54,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
52
54
  function getSource(id) {
53
55
  if (!id?.startsWith("api_")) return legacy.source(id);
54
56
  const config = settings.apis.find(value => value.id === id);if (!config) return null;
55
- const previous = instances.get(id);if (previous?.config === config) return previous.source;
56
- 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;
57
59
  if (previous?.signature === signature) return previous.source;
58
- 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);
59
61
  if (previous) retire(previous.source);return source;
60
62
  }
61
63
  function plan(id) {
@@ -95,7 +97,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
95
97
  }, options));managed = true;
96
98
  for (const [id, item] of instances) {
97
99
  const current = settings.apis.find(api => api.id === id);
98
- 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;
99
101
  }
100
102
  }
101
103
  function summary(api) {
@@ -158,10 +160,53 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
158
160
  if (!body || typeof body !== "object" || Array.isArray(body)) return;
159
161
  if (managed && (binding(client).history_isolation || source?.id.startsWith("api_"))) guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client]);
160
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
+ }
161
206
  async function change(input) {
162
207
  if (closed) throw accessError("ccdx_connections_closed", 503);
163
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");
164
- const next = editable();let freshRef, previousRef;
209
+ const next = editable();let freshRef, previousRef, savedApi;
165
210
  if (input.operation === "save_api") {
166
211
  const existing = next.apis.find(api => api.id === input.id);
167
212
  if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
@@ -182,7 +227,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
182
227
  }
183
228
  if (existing) { previousRef = existing.secret_ref;next.apis[next.apis.indexOf(existing)] = config; } else next.apis.push(config);
184
229
  checkedAccessSettings(next);
185
- 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; }
186
231
  } else if (["client", "preview_client"].includes(input.operation)) {
187
232
  if (!CLIENT_IDS.includes(input.id) || typeof input.enabled !== "boolean" || !Array.isArray(input.allowed)
188
233
  || input.source !== null && input.source !== undefined && !input.allowed.includes(input.source)) throw accessError("ccdx_connections_action_invalid");
@@ -221,7 +266,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
221
266
  const previous = c.source === "m365" ? legacy.selection().m365 : null;
222
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;
223
268
  if (![c.model, c.auto_review_model].every(id => target.models("gpt").some(model => model.id === id))) throw accessError("ccdx_api_model_unavailable");
224
- 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 || []
225
270
  : autoReviewReasoningEfforts(target.models("gpt").find(model => model.id === c.auto_review_model));
226
271
  if (c.auto_review_effort !== undefined && c.auto_review_effort !== null && !efforts.includes(c.auto_review_effort)) throw accessError("ccdx_api_effort_unavailable");
227
272
  }
@@ -271,20 +316,12 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
271
316
  }
272
317
  }
273
318
  } else if (input.operation === "discover") {
274
- if (!settings.apis.some(api => api.id === input.id && api.enabled)) throw accessError("ccdx_client_source_disabled", 503);
275
- try {
276
- const models = await getSource(input.id).discover({ signal: AbortSignal.timeout(20000) });
277
- const byId = new Map(models.map(model => [model.id, model]));
278
- const config = next.apis.find(api => api.id === input.id);
279
- for (const model of config.models) if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
280
- config.checked_at = new Date().toISOString();save(next);
281
- discoveries.set(input.id, { state: "ready", checked_at: config.checked_at });await syncClients();
282
- return { ...snapshot(), discovered: models };
283
- } 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 };
284
320
  } else throw accessError("ccdx_connections_action_invalid");
285
321
  await syncClients();
286
322
  if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
287
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(() => {});
288
325
  return snapshot();
289
326
  }
290
327
  return {
@@ -292,9 +329,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
292
329
  source: getSource,
293
330
  connections: snapshot,
294
331
  syncClients,
295
- manageConnections(input) { if (!input) return Promise.resolve(snapshot());const job = serial.then(() => change(input));serial = job.catch(() => {});return job; },
296
- async start() { const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();return result; },
297
- 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; },
298
335
  selection() { return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null }; },
299
336
  providerPreference(id) {
300
337
  const c = settings.clients.codex;
@@ -324,10 +361,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
324
361
  if (codexRequiresKey()) requireCodexKey(req);
325
362
  return { ...source, registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
326
363
  client: { ...source.client, listModels: async () => ({ status: 200, body: JSON.stringify({ data: compiled.models.map(model => ({ ...model, id: model.public_id })) }) }) },
327
- codexCatalog: codexClientCatalog(compiled, getSource) };
364
+ codexCatalog: codexClientCatalog(compiled) };
328
365
  }
329
366
  if (source?.id.startsWith("api_") && req) requireCodexKey(req);
330
- return source;
367
+ return req?.method === "GET" && source?.configuredModels && source.id.startsWith("api_") ? { ...source, codexCatalog: codexSourceCatalog(source) } : source;
331
368
  },
332
369
  hasModelBindings(client = "codex") { return managed && Array.isArray(binding(client).deployments); },
333
370
  resolveCodex(body, req) {
@@ -429,6 +466,6 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
429
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(); }
430
467
  return result;
431
468
  },
432
- 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(); },
433
470
  };
434
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();
@@ -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", "并行工具调用"],
@@ -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"];