codex-copilot-dx 1.2.13 → 1.2.15

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.13/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.13/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.15/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.15/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. Settings owns API/client access, independent web/terminal colors (classic green, Klein blue or Soft pink), startup and updates. Accounts and model catalogs stay with Model sources; client-specific tools stay with their application. CLI remains English; WebUI supports English/Chinese. An interactive terminal shows bounded startup checks, source/client state, a usage table with approximate cache hit rate, notices and animation. Plain/NO_COLOR/narrow output remains supported; `--verbose` retains request detail.
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.13 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.13.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. See the [control reference](docs/REFERENCE.md#control-console-and-online-settings), [1.2.15 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.15.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 |
@@ -56,7 +56,7 @@ Run `ccdx web` without GitHub sign-in. In **Settings → Model sources → Add A
56
56
 
57
57
  Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving does not probe models or select routes. Disabled sources/clients leave normal views and can be restored from **Disabled**, retaining grants/configuration without selecting a source. Closing client access does not quit its app. In-use sources require explicit replacements or pauses; pinned API requests finish on their original source. Existing user/managed app settings remain protected.
58
58
 
59
- There is no automatic fallback, cross-source replay or Chat-only protocol conversion. Configured models are not verified online entitlement; unknown models have conservative metadata. No runtime dependency or enterprise policy exception is added. See the [complete API, credential and client reference](docs/REFERENCE.md#manual-apis-and-client-access).
59
+ There is no automatic fallback, cross-source replay or Chat-only protocol conversion. Failed transports recover on a later request while active responses finish. Configured models do not prove online access or client compatibility: Claude App may reject non-Anthropic model IDs despite Messages support. Unknown capabilities remain conservative. No runtime dependency or enterprise policy exception is added. See the [complete API, credential and client reference](docs/REFERENCE.md#manual-apis-and-client-access).
60
60
 
61
61
  ## Microsoft 365 access
62
62
 
@@ -31,8 +31,22 @@ Copilot/M365 retry or request-body policy. Its lazy transport is retained per
31
31
  configuration, not rebuilt or serialized against the whole catalog per request.
32
32
  `providers/api-network.mjs` preserves enterprise routing/TLS and pins exact HTTPS
33
33
  targets. The WinHTTP API mode checks its allowlist in JS and C#; prediction/M365
34
- retain their original host restrictions. A failed worker can be replaced only
35
- for a later request, without replaying the failed request.
34
+ retain their original host restrictions. A failure before response headers marks
35
+ the transport unhealthy. The next request replaces it without replaying the
36
+ failed call; retirement waits for unrelated active responses to drain. Shutdown
37
+ still closes all current/retiring transports. HTTP error statuses and intentional
38
+ cancellation do not invalidate the transport. Node response streams are pulled
39
+ on demand to avoid eager delivery into an already-cancelled Web stream.
40
+ `operation-error.mjs` projects fixed transport phases, a local error-code
41
+ allowlist and socket-reuse evidence. API errors preserve their private cause,
42
+ but client diagnostics/logs expose only those bounded fields, not raw causes,
43
+ addresses, credentials, headers or prompts.
44
+
45
+ The API editor separates catalog candidates from selected models. Only selected
46
+ models enter the strict saved graph, with a required native protocol; unused
47
+ ID-only catalog entries cannot invalidate a save. Client grants remain separate
48
+ from route availability: manual sources need configured models for the client's
49
+ protocol before they are offered as its current source.
36
50
 
37
51
  `api-secrets.mjs` owns OS-protected credentials and a private-pipe cache; no
38
52
  command argument contains an upstream key. Failed metadata commits remove their
package/docs/REFERENCE.md CHANGED
@@ -7,9 +7,13 @@ Claude gateway and an explicitly selected Codex backup.
7
7
  ## Manual APIs and client access
8
8
 
9
9
  `ccdx web` starts management without GitHub sign-in or automatic App launch.
10
- Use **Settings → Model sources → Add API**, save the HTTPS address/key, declare
11
- models and their native interfaces, allow clients, then choose each current
12
- source under **Settings → Clients**. Only Codex on GitHub needs the default
10
+ Use **Settings → Model sources → Add API**, save the HTTPS API base address/key
11
+ (including a required prefix such as `/v1`), then reopen **Manage → Read models**.
12
+ Select the models to use and their supported interfaces, save, then choose each
13
+ client's current source under **Settings → Clients**. Unselected catalog entries
14
+ are not saved. A selected model needs at least one interface; choosing an
15
+ interface also selects its model. Manual ID entry is an optional collapsed path
16
+ for models absent from the catalog. Only Codex on GitHub needs the default
13
17
  GitHub sign-in path. To use Claude alone, disable Codex access. Stop the
14
18
  management-only process before normal `ccdx` startup for the live terminal.
15
19
 
@@ -24,8 +28,15 @@ key. Display hints do not authorize requests. API addresses require HTTPS, no
24
28
  userinfo/query/fragment, and endpoint overrides on the base address's origin.
25
29
  Redirects are refused. Existing proxy/bypass/private-CA rules remain; unsupported
26
30
  dynamic macOS routing fails without a direct fallback. Windows delegates system
27
- routing to a target-pinned WinHTTP worker. Failed calls are not replayed; a dead
28
- worker can be recreated for a later request.
31
+ routing to a target-pinned WinHTTP worker. Failed calls are not replayed. A
32
+ transport failure before response headers marks that transport unhealthy; a
33
+ later request creates a new transport and rereads the existing routing policy.
34
+ Other responses already using the old transport finish before it is released.
35
+ HTTP denials and deliberate cancellation do not trigger this recovery.
36
+ Network failures retain `ccdx_api_network_unavailable` and include a bounded
37
+ `error.diagnostic`: a recognized local error `code`, observed `phase`, and
38
+ `reused_socket` (boolean or unknown). Unknown codes/phases remain `unknown`.
39
+ Diagnostics omit raw error text, endpoints, headers, keys and request content.
29
40
 
30
41
  Up to 16 uniquely named manual APIs and 500 unique models per API are supported. Model IDs are limited to 160 characters; `codex-auto-review` remains an internal alias. Custom model
31
42
  IDs are not filtered by a GPT/Claude prefix. Each model declares Messages,
@@ -37,6 +48,11 @@ or inference call. **Read models** performs one explicit catalog read, with a
37
48
  support until reviewed. Opening normal views reads saved models rather than
38
49
  probing every API. `ccdx models` labels manual models as configured, not live.
39
50
 
51
+ These are CCDX's routing rules, not a guarantee that every installed client
52
+ accepts arbitrary model names. Some Claude App versions reject non-Anthropic
53
+ model route IDs even when their upstream supports Messages. A saved connection
54
+ or successful model-list read does not prove an App conversation works.
55
+
40
56
  `connections.json` beside user settings (respecting `XDG_CONFIG_HOME`) stores a
41
57
  strict version-one graph of provider switches, API metadata and each client's
42
58
  allowed/current sources. It stores only credential references or an environment
@@ -1123,7 +1139,7 @@ Unknown support prevents an explicitly requested exception from starting.
1123
1139
  For an older updater that still requires Git, install the Release tarball directly:
1124
1140
 
1125
1141
  ```sh
1126
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.13/codex-copilot-dx-1.2.13.tgz
1142
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.15/codex-copilot-dx-1.2.15.tgz
1127
1143
  # Windows PowerShell: use npm.cmd instead of npm.
1128
1144
  ```
1129
1145
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.13",
3
+ "version": "1.2.15",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -12,7 +12,7 @@ import { createStreamPerformanceMetrics, isMessagesOutputDelta } from "./stream-
12
12
  import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
13
13
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
14
14
  import { decodedBodyLimitPreference } from "./user-settings.mjs";
15
- import { operationErrorDetails } from "./operation-error.mjs";
15
+ import { operationErrorDetails, transportErrorDetails } from "./operation-error.mjs";
16
16
  import { requestApplication } from "./request-application.mjs";
17
17
 
18
18
  function send(res, code, value) {
@@ -151,10 +151,15 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
151
151
  const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
152
152
  failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
153
153
  const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
154
- log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}`);
154
+ const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
155
+ log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
155
156
  tracker?.setErrorOrigin(terminalOrigin);
156
157
  if (outcome === "cancelled") return;
157
- if (!res.headersSent) send(res, statusCode, apiError(error.code || abort.reason || "ccdx_gateway_error", message));
158
+ if (!res.headersSent) {
159
+ const value = apiError(error.code || abort.reason || "ccdx_gateway_error", message);
160
+ if (diagnostic) value.error.diagnostic = diagnostic;
161
+ send(res, statusCode, value);
162
+ }
158
163
  else if (!res.destroyed && !res.writableEnded) res.end(`event: error\ndata: ${JSON.stringify(apiError("ccdx_gateway_error", message))}\n\n`);
159
164
  } finally {
160
165
  release();abort.cleanup();
@@ -1,12 +1,14 @@
1
1
  (() => {
2
2
  const el = id => document.getElementById(id), root = el("connection-sources");if (!root) return;
3
3
  const words = (node, key, args) => globalThis.ccdxLanguage.set(node, key, args), format = key => globalThis.ccdxLanguage.format(key);
4
- let data = null, editing = null, editingClient = null, disabling = null, models = [], busy = false, generation = 0;
4
+ let data = null, editing = null, editingClient = null, disabling = null, models = [], selectedModels = new Set(), busy = false, generation = 0;
5
5
  const apiForm = el("connection-api-form"), clientForm = el("connection-client-form");
6
6
  const node = (tag, text, className) => { const item = document.createElement(tag);if (text !== undefined) item.textContent = text;if (className) item.className = className;return item; };
7
7
  const source = id => data.providers.find(item => item.id === id), client = id => data.clients.find(item => item.id === id);
8
8
  const compatible = (provider, id) => provider.protocols.includes(id === "codex" ? "responses" : "messages");
9
- const message = key => words(el("connection-note"), key);
9
+ const selectableSource = (provider, id) => compatible(provider, id)
10
+ && (provider.builtin || provider.models?.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages")));
11
+ const message = (key, values) => words(el("connection-note"), key, values);
10
12
  function button(key, action) { const item = node("button");item.type = "button";words(item, key);item.addEventListener("click", action);return item; }
11
13
  function check(name, value, checked, text) { const label = node("label"), input = node("input");input.type = "checkbox";input.name = name;input.value = value;input.checked = checked;label.append(input, node("span", text));return label; }
12
14
  async function api(input) {
@@ -81,12 +83,19 @@
81
83
  function modelRows() {
82
84
  const body = el("connection-models");body.replaceChildren();
83
85
  for (const model of models) {
84
- const tr = node("tr"), name = node("td", model.id), apis = node("td"), actions = node("td"), group = node("div", undefined, "connection-checks");
86
+ const tr = node("tr"), name = node("td"), apis = node("td"), actions = node("td"), group = node("div", undefined, "connection-checks");
87
+ tr.dataset.model = model.id;
88
+ const selection = check("selected-model", model.id, selectedModels.has(model.id), model.id);
89
+ selection.firstChild.addEventListener("change", e => { if (e.target.checked) selectedModels.add(model.id);else selectedModels.delete(model.id); });name.append(selection);
85
90
  for (const protocol of ["messages", "responses", "chat"]) {
86
91
  const label = check("model-api", protocol, model.protocols.includes(protocol), protocol === "chat" ? "Chat" : protocol === "messages" ? "Messages" : "Responses");
87
- label.firstChild.addEventListener("change", e => { model.protocols = [...new Set([...model.protocols.filter(api => api !== protocol), ...(e.target.checked ? [protocol] : [])])]; });group.append(label);
92
+ label.firstChild.disabled = !apiForm.querySelector(`[name="protocol"][value="${protocol}"]`).checked;
93
+ label.firstChild.addEventListener("change", e => {
94
+ model.protocols = [...new Set([...model.protocols.filter(api => api !== protocol), ...(e.target.checked ? [protocol] : [])])];
95
+ if (e.target.checked) { selectedModels.add(model.id);selection.firstChild.checked = true; }
96
+ });group.append(label);
88
97
  }
89
- apis.append(group);actions.append(button("api_remove_model", () => { models = models.filter(item => item !== model);modelRows(); }));tr.append(name, apis, actions);body.append(tr);
98
+ apis.append(group);actions.append(button("api_remove_model", () => { models = models.filter(item => item !== model);selectedModels.delete(model.id);modelRows(); }));tr.append(name, apis, actions);body.append(tr);
90
99
  }
91
100
  }
92
101
  function setEndpoints(base, endpoints) { for (const [api, path] of [["messages", "messages"], ["responses", "responses"], ["chat", "chat/completions"]]) apiForm.elements[api + "_url"].value = endpoints?.[api] || base.replace(/\/+$/, "") + "/" + path; }
@@ -99,23 +108,33 @@
99
108
  for (const input of apiForm.querySelectorAll('[name="protocol"]')) input.checked = provider ? provider.protocols.includes(input.value) : input.value !== "chat";
100
109
  setEndpoints(provider?.base_url || "", provider?.endpoints);
101
110
  const allowed = el("connection-allowed-clients");allowed.replaceChildren(...data.clients.filter(c => c.enabled).map(c => check("allowed", c.id, c.allowed.includes(editing), c.name)));
102
- models = structuredClone(provider?.models || []);modelRows();el("connection-discover").disabled = !editing;el("connection-model-id").value = "";
111
+ models = structuredClone(provider?.models || []);selectedModels = new Set(models.map(model => model.id));modelRows();el("connection-manual-model").open = false;el("connection-discover").disabled = !editing;el("connection-model-id").value = "";
103
112
  }
104
113
  apiForm.elements.base.addEventListener("change", () => setEndpoints(apiForm.elements.base.value));
114
+ for (const input of apiForm.querySelectorAll('[name="protocol"]')) input.addEventListener("change", () => {
115
+ const available = new Set([...apiForm.querySelectorAll('[name="protocol"]:checked')].map(item => item.value));
116
+ for (const model of models) model.protocols = model.protocols.filter(api => available.has(api));modelRows();
117
+ });
105
118
  function keyMode() { const external = Boolean(apiForm.elements.key_env.value.trim());apiForm.elements.key.disabled = external;apiForm.elements.key.required = !external && !editing;if (external) apiForm.elements.key.value = ""; }
106
119
  apiForm.elements.key_env.addEventListener("input", keyMode);
107
120
  apiForm.addEventListener("submit", e => {
108
121
  e.preventDefault();if (busy || !apiForm.reportValidity()) return;
122
+ const chosenModels = models.filter(model => selectedModels.has(model.id));
123
+ const invalid = chosenModels.find(model => !model.protocols.length);
124
+ if (invalid) {
125
+ message("api_model_protocol_required", { model: invalid.id });
126
+ [...el("connection-models").children].find(row => row.dataset.model === invalid.id)?.querySelector('input[name="model-api"]:not(:disabled)')?.focus();return;
127
+ }
109
128
  const endpoints = Object.fromEntries([...apiForm.querySelectorAll('[name="protocol"]:checked')].map(input => [input.value, apiForm.elements[input.value + "_url"].value.trim()]));
110
129
  const key = apiForm.elements.key.value;apiForm.elements.key.value = "";
111
130
  void change({ operation: "save_api", ...(editing ? { id: editing } : {}), key,
112
- config: { name: apiForm.elements.name.value.trim(), base_url: apiForm.elements.base.value.trim().replace(/\/+$/, ""), endpoints, auth_header: apiForm.elements.auth_header.value, models,
131
+ config: { name: apiForm.elements.name.value.trim(), base_url: apiForm.elements.base.value.trim().replace(/\/+$/, ""), endpoints, auth_header: apiForm.elements.auth_header.value, models: chosenModels,
113
132
  ...(apiForm.elements.key_env.value.trim() ? { key_env: apiForm.elements.key_env.value.trim() } : {}) },
114
133
  allowed: [...apiForm.querySelectorAll('[name="allowed"]:checked')].map(input => input.value).concat(data.clients.filter(c => !c.enabled && c.allowed.includes(editing)).map(c => c.id)) });
115
134
  });
116
135
  el("connection-model-add").addEventListener("click", () => {
117
136
  const id = el("connection-model-id").value.trim();if (!id || models.some(model => model.id === id) || models.length >= 500) return;
118
- models.push({ id, protocols: [] });el("connection-model-id").value = "";modelRows();
137
+ models.push({ id, protocols: [] });selectedModels.add(id);el("connection-model-id").value = "";modelRows();
119
138
  });
120
139
  el("connection-discover").addEventListener("click", () => void change({ operation: "discover", id: editing }, result => {
121
140
  const known = new Map(models.map(model => [model.id, model]));for (const model of result.discovered || []) if (!known.has(model.id)) known.set(model.id, model);
@@ -129,14 +148,14 @@
129
148
  }
130
149
  function clientSources() {
131
150
  const allowed = new Set([...el("connection-client-allowed").querySelectorAll("input:checked")].map(input => input.value));
132
- const before = el("connection-current").value, replacement = choice(data.providers.filter(p => p.enabled && allowed.has(p.id) && compatible(p, editingClient)), before);
151
+ const before = el("connection-current").value, replacement = choice(data.providers.filter(p => p.enabled && allowed.has(p.id) && selectableSource(p, editingClient)), before);
133
152
  el("connection-current").replaceChildren(...replacement.childNodes);if ([...el("connection-current").options].some(option => option.value === before)) el("connection-current").value = before;clientModels();
134
153
  }
135
154
  function editClient(c) {
136
155
  editingClient = c.id;panels("client");el("connection-client-title").textContent = c.name;
137
156
  const allowed = el("connection-client-allowed");allowed.replaceChildren(...data.providers.filter(p => p.enabled && compatible(p, c.id)).map(p => check("source", p.id, c.allowed.includes(p.id), p.name)));
138
157
  allowed.querySelectorAll("input").forEach(input => input.addEventListener("change", clientSources));
139
- const select = choice(data.providers.filter(p => p.enabled && c.allowed.includes(p.id) && compatible(p, c.id)), c.source);
158
+ const select = choice(data.providers.filter(p => p.enabled && c.allowed.includes(p.id) && selectableSource(p, c.id)), c.source);
140
159
  el("connection-current").replaceChildren(...select.childNodes);el("connection-current").value = c.source || "";clientModels();
141
160
  }
142
161
  el("connection-current").addEventListener("change", clientModels);
@@ -148,7 +167,7 @@
148
167
  const affected = data.clients.filter(c => c.enabled && c.source === provider.id);
149
168
  if (!affected.length) { void change({ operation: "provider", id: provider.id, enabled: false });return; }
150
169
  disabling = provider.id;panels("disable");const area = el("connection-replacements");area.replaceChildren();
151
- for (const c of affected) { const label = node("label", c.name), select = choice(data.providers.filter(p => p.id !== provider.id && p.enabled && c.allowed.includes(p.id) && compatible(p, c.id)));select.name = c.id;label.append(select);area.append(label); }
170
+ for (const c of affected) { const label = node("label", c.name), select = choice(data.providers.filter(p => p.id !== provider.id && p.enabled && c.allowed.includes(p.id) && selectableSource(p, c.id)));select.name = c.id;label.append(select);area.append(label); }
152
171
  }
153
172
  el("connection-disable-form").addEventListener("submit", e => { e.preventDefault();void change({ operation: "provider", id: disabling, enabled: false,
154
173
  replacements: Object.fromEntries([...el("connection-replacements").querySelectorAll("select")].map(select => [select.name, select.value || null])) }); });
@@ -313,7 +313,7 @@
313
313
  </div></details>
314
314
  <fieldset><legend data-i18n="api_allowed_clients">Allowed clients</legend><div class="connection-checks" id="connection-allowed-clients"></div></fieldset>
315
315
  <fieldset><legend data-i18n="model_catalog">Model list</legend><div class="section-actions"><button type="button" id="connection-discover" data-i18n="api_read_models">Read models</button><span class="hint" data-i18n="api_discovery_save_first">Save the API first. No chat request is sent.</span></div>
316
- <div class="section-actions"><input type="text" id="connection-model-id" spellcheck="false" autocomplete="off" aria-label="Model ID" placeholder="Model ID"><button type="button" id="connection-model-add" data-i18n="api_add_model">Add model</button></div>
316
+ <details class="tool-details" id="connection-manual-model"><summary data-i18n="api_manual_model">Add a model manually</summary><div class="section-actions"><input type="text" id="connection-model-id" spellcheck="false" autocomplete="off" aria-label="Model ID" placeholder="Model ID"><button type="button" id="connection-model-add" data-i18n="api_add_model">Add model</button></div></details>
317
317
  <p class="hint" data-i18n="api_model_protocol_hint">Choose the APIs each model supports.</p><div class="table-wrap"><table><thead><tr><th data-i18n="model">Model</th><th data-i18n="api_protocols">Available APIs</th><th></th></tr></thead><tbody id="connection-models"></tbody></table></div>
318
318
  </fieldset>
319
319
  <div class="section-actions"><button type="submit" data-i18n="api_save">Save</button></div>
@@ -16,7 +16,9 @@
16
16
  "api_read_models": ["Read models", "读取模型"],
17
17
  "api_discovery_save_first": ["Save the API first. No chat request is sent.", "先保存来源;只读取模型目录。"],
18
18
  "api_add_model": ["Add model", "添加模型"],
19
- "api_model_protocol_hint": ["Choose the APIs each model supports.", "为每个模型选择实际支持的接口。"],
19
+ "api_manual_model": ["Add a model manually", "手工添加模型"],
20
+ "api_model_protocol_hint": ["Select the models to use and their supported APIs.", "勾选要使用的模型,再选择其支持的接口。"],
21
+ "api_model_protocol_required": ["Choose an API for {model}, or deselect it.", "请为 {model} 选择接口,或取消勾选该模型。"],
20
22
  "api_remove_model": ["Remove", "移除"],
21
23
  "api_save": ["Save", "保存"],
22
24
  "api_current_source": ["Current source", "当前来源"],
@@ -77,6 +79,7 @@
77
79
  "ccdx_conversation_state_invalid": ["Conversation source records are unreadable. The existing file was kept.", "会话来源记录无法读取,原文件已保留。"],
78
80
  "ccdx_api_catalog_invalid": ["The model list was invalid. Existing settings were kept.", "模型列表无效,已有配置已保留。"],
79
81
  "ccdx_api_catalog_http_401": ["Model access was rejected (HTTP 401). Check the key.", "模型访问被拒绝(401),请检查 Key。"],
82
+ "ccdx_api_catalog_http_404": ["No model catalog here (404). Check the API prefix, such as /v1.", "模型目录不存在(404),请检查 API 前缀,如 /v1。"],
80
83
  "ccdx_api_catalog_http_403": ["Model access was denied (HTTP 403). Check permissions.", "模型访问被拒绝(403),请检查权限。"],
81
84
  "ccdx_api_network_unavailable": ["Could not reach the API. Proxy and TLS rules were kept.", "无法连接 API,代理和证书规则已保留。"],
82
85
  "ccdx_api_limit": ["Up to 16 manual APIs are supported.", "最多可添加 16 个手工 API。"],
@@ -73,6 +73,9 @@ h1 { margin: 0; font-size: clamp(20px, 3vw, 27px); font-weight: 650; letter-spac
73
73
  #connection-editor legend, #connection-client-editor legend { padding: 0; margin-bottom: 9px; color: var(--text); }
74
74
  #connection-models td { white-space: normal; overflow-wrap: anywhere; }
75
75
  #connection-models td:first-child { min-width: 140px; }
76
+ #connection-models td:first-child label { display: inline-flex; align-items: center; gap: 8px; }
77
+ #connection-models td:first-child input { flex: none; accent-color: var(--accent); }
78
+ #connection-models td:last-child button { white-space: nowrap; }
76
79
  .connection-disabled { padding: 8px 0 18px; color: var(--heading); }
77
80
  .connection-disabled .connection-row { padding: 13px 0; }
78
81
  @media (max-width: 650px) { .connection-fields { grid-template-columns: minmax(0, 1fr); } .connection-actions { gap: 9px; } .connection-row { gap: 10px; } }
@@ -1,5 +1,22 @@
1
1
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
2
2
 
3
+ const TRANSPORT_CODES = new Set([
4
+ "ECONNRESET", "ECONNREFUSED", "ECONNABORTED", "EPIPE", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "EPERM", "EACCES",
5
+ "EPROTO", "ERR_SSL_WRONG_VERSION_NUMBER", "ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR", "ERR_TLS_CERT_ALTNAME_INVALID", "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
6
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "SELF_SIGNED_CERT_IN_CHAIN", "DEPTH_ZERO_SELF_SIGNED_CERT", "CERT_HAS_EXPIRED", "CERT_NOT_YET_VALID",
7
+ "ERR_INVALID_ARG_TYPE", "ERR_INVALID_CHAR", "ERR_INVALID_PROTOCOL", "ERR_HTTP_INVALID_HEADER_VALUE", "ERR_HTTP_CONTENT_LENGTH_MISMATCH", "ERR_STREAM_PREMATURE_CLOSE",
8
+ "HPE_INVALID_CONSTANT", "HPE_INVALID_STATUS", "HPE_INVALID_HEADER_TOKEN", "HPE_UNEXPECTED_CONTENT_LENGTH", "HPE_INVALID_CONTENT_LENGTH", "HPE_INVALID_CHUNK_SIZE", "HPE_HEADER_OVERFLOW",
9
+ ]);
10
+ const TRANSPORT_PHASES = new Set(["request", "dns", "connect", "tls", "response", "unknown"]);
11
+
12
+ // Project only local error codes and fixed phases, never raw errors, URLs or headers.
13
+ export function transportErrorDetails(error) {
14
+ const value = error?.transport;
15
+ const code = [value?.code, error?.code, error?.cause?.code].find(code => TRANSPORT_CODES.has(code)) || "unknown";
16
+ return { code, phase: TRANSPORT_PHASES.has(value?.phase) ? value.phase : "unknown",
17
+ reused_socket: typeof value?.reused_socket === "boolean" ? value.reused_socket : null };
18
+ }
19
+
3
20
  export function operationError(code, message, { status = null, retryAt = null } = {}) {
4
21
  return Object.assign(new Error(message), { code, status, retryAt });
5
22
  }
@@ -6,6 +6,7 @@ import { resolveNetworkRoute, networkProxyFor, bypassNetworkProxy } from "../net
6
6
  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
+ import { transportErrorDetails } from "../operation-error.mjs";
9
10
 
10
11
  export async function createApiNetwork({ targets, env = process.env, platform = process.platform, signal,
11
12
  requestImpl = https.request, exec = promisify(execFile), startWindowsNetwork } = {}) {
@@ -22,30 +23,65 @@ export async function createApiNetwork({ targets, env = process.env, platform =
22
23
  requestImpl = worker.requestImpl;
23
24
  }
24
25
  }
25
- const agent = worker ? undefined : createProxyAgent(plan);let closed = false;
26
+ const agent = worker ? undefined : createProxyAgent(plan);let closed = false, broken = false, retiring = false, active = 0, finishRetiring;
27
+ const close = () => { if (closed) return;closed = true;agent?.destroy();worker?.close();finishRetiring?.(); };
26
28
  return {
27
- healthy: () => !closed && (!worker || worker.healthy()),
29
+ healthy: () => !closed && !broken && !retiring && (!worker || worker.healthy()),
28
30
  fetch(raw, init = {}) {
29
31
  return new Promise((resolve, reject) => {
30
32
  let url;try { url = new URL(raw); } catch { reject(accessError("ccdx_api_url_invalid"));return; }
31
- if (closed || !urls.has(url.href) || !["GET", "POST"].includes(init.method || "GET")) { 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; }
32
34
  if (init.signal?.aborted) { reject(init.signal.reason);return; }
33
- let req, incoming;
34
- const cleanup = () => init.signal?.removeEventListener("abort", abort);
35
+ active++;
36
+ let req, incoming, socket, phase = "request", handedOff = false, released = false;
37
+ const release = () => { if (released) return;released = true;active--;if (retiring && !active) close(); };
38
+ const lookup = error => { phase = error ? "dns" : "connect"; };
39
+ const connected = () => { phase = "tls"; };
40
+ const secure = () => { phase = "request"; };
41
+ const cleanup = () => {
42
+ init.signal?.removeEventListener("abort", abort);
43
+ socket?.off("lookup", lookup);socket?.off("connect", connected);socket?.off("secureConnect", secure);
44
+ };
45
+ const failed = error => {
46
+ if (!handedOff && !init.signal?.aborted) broken = true;
47
+ cleanup();
48
+ const failure = new Error("API transport failed", { cause: error });
49
+ failure.transport = { ...transportErrorDetails(error), phase, reused_socket: typeof req?.reusedSocket === "boolean" ? req.reusedSocket : null };
50
+ release();
51
+ reject(failure);
52
+ };
35
53
  const abort = () => { req?.destroy(init.signal.reason || accessError("ccdx_api_cancelled"));incoming?.destroy(); };
36
54
  try {
37
55
  req = requestImpl({ hostname: worker ? url.hostname : url.hostname.replace(/^\[|\]$/g, ""), port: Number(url.port || 443), protocol: "https:", path: url.pathname,
38
56
  method: init.method || "GET", headers: { ...Object.fromEntries(new Headers(init.headers)), "accept-encoding": "identity" }, agent, rejectUnauthorized: true }, res => {
39
- incoming = res;res.once("end", cleanup);res.once("close", cleanup);res.on("error", reject);
57
+ phase = "response";incoming = res;
58
+ const finished = () => { cleanup();release(); };
59
+ res.once("end", finished);res.once("close", finished);res.on("error", failed);
40
60
  const headers = new Headers();for (const [key, value] of Object.entries(res.headers)) for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(key, String(item));
41
- try { const empty = [204, 205, 304].includes(res.statusCode);if (empty) res.resume();resolve(new Response(empty ? null : Readable.toWeb(res), { status: res.statusCode, headers })); }
42
- catch (error) { cleanup();res.destroy();reject(error); }
61
+ try {
62
+ const empty = [204, 205, 304].includes(res.statusCode);if (empty) res.resume();
63
+ // Pull only when the consumer reads; eager Node 22 delivery can enqueue after cancellation.
64
+ const response = new Response(empty ? null : Readable.toWeb(res, { strategy: { highWaterMark: 0 } }), { status: res.statusCode, headers });
65
+ handedOff = true;resolve(response);
66
+ }
67
+ catch (error) { failed(error);res.destroy(); }
43
68
  });
44
- req.on("error", error => { cleanup();reject(error); });init.signal?.addEventListener("abort", abort, { once: true });
69
+ req.once("socket", value => {
70
+ socket = value;
71
+ if (!value.connecting || req.reusedSocket) return;
72
+ phase = "connect";value.once("lookup", lookup);value.once("connect", connected);value.once("secureConnect", secure);
73
+ });
74
+ req.on("error", failed);init.signal?.addEventListener("abort", abort, { once: true });
45
75
  if (init.signal?.aborted) { abort();return; }req.end(init.body);
46
- } catch (error) { cleanup();req?.destroy();reject(error); }
76
+ } catch (error) { failed(error);req?.destroy(); }
47
77
  });
48
78
  },
49
- close() { closed = true;agent?.destroy();worker?.close(); },
79
+ retire() {
80
+ retiring = true;
81
+ if (closed) return Promise.resolve();
82
+ if (!active) { close();return Promise.resolve(); }
83
+ return new Promise(resolve => { finishRetiring = resolve; });
84
+ },
85
+ close,
50
86
  };
51
87
  }
@@ -9,6 +9,7 @@ import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../ht
9
9
  import { markUpstreamHeaders } from "../stream-performance.mjs";
10
10
  import { createApiNetwork } from "./api-network.mjs";
11
11
  import { checkedApiKey } from "../api-secrets.mjs";
12
+ import { transportErrorDetails } from "../operation-error.mjs";
12
13
 
13
14
  const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
14
15
  export function apiCatalog(config) {
@@ -28,11 +29,16 @@ export function createApiProvider({ config, secrets, env = process.env, platform
28
29
  if (config.endpoints.messages) targets.push(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens");
29
30
  if (config.endpoints.responses) targets.push(config.endpoints.responses.replace(/\/+$/, "") + "/compact");
30
31
  let network, flight, closed = false;
32
+ const retiring = new Set();
31
33
  const registry = { models: { data: catalog.filter(model => model.supported_endpoints.includes(paths.responses)) }, source: "configured", generation };
32
34
  const getNetwork = async signal => {
33
35
  if (closed) throw accessError("ccdx_api_closed", 503);
34
36
  if (network && (network.healthy?.() ?? true)) return network;
35
- network?.close();network = null;
37
+ const previous = network;network = null;
38
+ if (previous?.retire) {
39
+ retiring.add(previous);
40
+ void Promise.resolve(previous.retire()).then(() => retiring.delete(previous), () => { previous.close();retiring.delete(previous); });
41
+ } else previous?.close();
36
42
  flight ||= networkFactory({ targets, env, platform, signal }).then(value => { if (closed) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }).finally(() => { flight = null; });
37
43
  return flight;
38
44
  };
@@ -63,7 +69,14 @@ export function createApiProvider({ config, secrets, env = process.env, platform
63
69
  return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: code } }), { status: result.status, headers: safeHeaders });
64
70
  }
65
71
  return result;
66
- } catch (error) { if (options.signal?.aborted) throw error;throw accessError(error.code === "ccdx_api_redirect_refused" ? error.code : "ccdx_api_network_unavailable", 502); }
72
+ } catch (error) {
73
+ if (options.signal?.aborted) throw error;
74
+ if (error.code === "ccdx_api_redirect_refused") throw error;
75
+ const failure = accessError("ccdx_api_network_unavailable", 502);
76
+ Object.defineProperty(failure, "cause", { value: error });
77
+ failure.transport = transportErrorDetails(error);failure.jsonBody.error.diagnostic = failure.transport;
78
+ throw failure;
79
+ }
67
80
  }
68
81
  const client = {
69
82
  listModels: async () => ({ status: 200, body: JSON.stringify(registry.models) }),
@@ -124,6 +137,6 @@ export function createApiProvider({ config, secrets, env = process.env, platform
124
137
  if (!resp.ok) { await resp.body?.cancel();const code = `ccdx_api_http_${resp.status}`;return { resp: new Response(JSON.stringify({ error: { code, message: code } }), { status: resp.status, headers: { "Content-Type": "application/json" } }), reqContext: context, errorText: code, usedRetryPolicies: new Set() }; }
125
138
  return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
126
139
  } },
127
- close() { closed = true;network?.close(); },
140
+ close() { closed = true;network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
128
141
  };
129
142
  }