codex-copilot-dx 1.2.14 → 1.2.16

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.14/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.14/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.16/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.16/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.14 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.14.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.16 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.16.md) and [copy inventory](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/UX_COPY.md).
21
21
 
22
22
  ## Commands
23
23
  | Command | Purpose |
@@ -54,9 +54,9 @@ Requests shows live app/source/model flow above existing summaries and finished
54
54
 
55
55
  Run `ccdx web` without GitHub sign-in. In **Settings → Model sources → Add API**, enter the HTTPS address/key and declare each model's real interfaces. Save, allow clients, then choose their **Current source** under **Clients**. Claude App/Code use Messages; Codex uses Responses, all on port 2026. Reopen clients for first setup and start a new conversation after source/key changes. To use Claude alone, close Codex access. 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 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.
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 inside their respective Settings cards, 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. For custom Messages APIs, CCDX automatically writes stable Claude App compatibility routes and real model display names. Upstream requests use real IDs; no manual aliases are needed. This addresses model-name filtering, not every model's tool or thinking compatibility.
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 complete client compatibility. 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,16 @@ 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.
36
44
 
37
45
  The API editor separates catalog candidates from selected models. Only selected
38
46
  models enter the strict saved graph, with a required native protocol; unused
@@ -54,6 +62,20 @@ independent app/code lifecycles. M365 beta policy is not imposed on API clients;
54
62
  adding a source alone never migrates old client credentials. Configuring clients
55
63
  does not patch/restart their binaries or override managed settings.
56
64
 
65
+ `claude-models.mjs` owns deterministic desktop compatibility routes for manual
66
+ Messages sources. The same mapping feeds the App field writer, authenticated
67
+ App catalog and gateway resolver; Code/Codex and M365 do not adopt these aliases.
68
+ Standard Claude IDs retain their native family identity. Other model routes use
69
+ opaque digits with the real ID as `labelOverride`, without asserting Anthropic
70
+ capabilities. The gateway canonicalizes the request before history validation
71
+ and upstream dispatch, then projects the requested alias only into the returned
72
+ JSON model field or SSE message-start model field. Bounded SSE observation
73
+ retains other frames and applies client backpressure without a separate tee.
74
+ Usage and performance continue to identify the upstream model. A route cannot
75
+ authorize a model outside its source's Messages catalog.
76
+ For this same manual App boundary, system-role text is collected into the native
77
+ top-level system field in order; conversation blocks and their order are retained.
78
+
57
79
  `conversation-source-guard.mjs` retains bounded HMAC correlations for observed
58
80
  managed histories. Known source/key conflicts fail before forwarding. It does
59
81
  not establish provenance for an unseen history or implement dynamic affinity.
@@ -62,6 +84,8 @@ The existing Responses route-plan boundary continues to own opaque-state checks.
62
84
  `dashboard/connections.js` owns settings forms; application source/review and
63
85
  account/catalog views keep their existing scopes and use the same backend graph.
64
86
  Full configuration is on-demand; ordinary status uses compact cached summaries.
87
+ Disabled sources and clients have separate restore lists inside their owning
88
+ Settings cards, hidden when empty.
65
89
  Shared Messages observation includes all sources, while M365-specific status
66
90
  projects M365 counts. Bounds cover two built-ins plus 16 APIs without unbounded
67
91
  labels, request histories, body logging or a new refresh loop.
package/docs/REFERENCE.md CHANGED
@@ -28,8 +28,15 @@ key. Display hints do not authorize requests. API addresses require HTTPS, no
28
28
  userinfo/query/fragment, and endpoint overrides on the base address's origin.
29
29
  Redirects are refused. Existing proxy/bypass/private-CA rules remain; unsupported
30
30
  dynamic macOS routing fails without a direct fallback. Windows delegates system
31
- routing to a target-pinned WinHTTP worker. Failed calls are not replayed; a dead
32
- 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.
33
40
 
34
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
35
42
  IDs are not filtered by a GPT/Claude prefix. Each model declares Messages,
@@ -41,6 +48,34 @@ or inference call. **Read models** performs one explicit catalog read, with a
41
48
  support until reviewed. Opening normal views reads saved models rather than
42
49
  probing every API. `ccdx models` labels manual models as configured, not live.
43
50
 
51
+ For manual Messages APIs, CCDX writes Claude App's model configuration
52
+ automatically. Standard Claude IDs keep their existing identity; other IDs use
53
+ a stable `ccdx/claude-compatible-<digits>` route with `labelOverride` set to the
54
+ real model ID. Reordering or adding models does not renumber existing routes.
55
+ The App's model catalog advertises the same routes and real display names.
56
+ Users do not need to add aliases manually. Owned configuration migrates through
57
+ the existing field journal; custom or managed settings remain protected.
58
+
59
+ Only the authenticated Claude App binding enables this translation. The gateway
60
+ resolves routes against that source's allowed Messages models, sends real IDs
61
+ upstream for Messages and token counting, and returns the requested route in
62
+ JSON messages or SSE `message_start.message.model`. Other SSE frames, tool data
63
+ and signatures are retained. Alias SSE framing is bounded by the existing event
64
+ limit and follows client backpressure. Usage and request diagnostics keep real
65
+ model IDs. Codex, Claude Code, M365 routes, source/key history boundaries and
66
+ declared model capabilities retain their existing behavior.
67
+
68
+ Some App requests include `system` messages as well as a top-level `system`
69
+ field, including system notes after user content. For manual App connections,
70
+ CCDX appends their text blocks to the top-level field in system-message order,
71
+ retaining system priority, block metadata and the order/content of conversation
72
+ messages. Non-text system content fails locally. Other clients and providers
73
+ keep their existing payload paths.
74
+
75
+ Compatibility routes address Claude App's model-name filter. A saved connection,
76
+ successful model-list read or connection check does not prove complete App
77
+ conversation, tool or thinking support for every upstream model.
78
+
44
79
  `connections.json` beside user settings (respecting `XDG_CONFIG_HOME`) stores a
45
80
  strict version-one graph of provider switches, API metadata and each client's
46
81
  allowed/current sources. It stores only credential references or an environment
@@ -53,7 +88,9 @@ Private helpers omit unrelated credentials and Node hooks. API error bodies are
53
88
  replaced with stable codes; valid Retry-After metadata is retained.
54
89
 
55
90
  `client-gateway-keys.json` holds local credentials separately. Disabled sources
56
- and clients leave normal lists/navigation and remain in collapsed **Disabled**.
91
+ and clients leave normal lists/navigation. Settings keeps **Disabled sources**
92
+ inside **Model sources**, and **Disabled clients** inside **Clients**. Each
93
+ collapsed list appears only when it has entries and provides **Enable again**.
57
94
  Closing a client stops CCDX access, not the app. Disabling an in-use source
58
95
  requires explicit replacements or pauses. Pinned API streams finish on their
59
96
  original provider; retired transports/keys are released afterwards. Legacy M365
@@ -1127,7 +1164,7 @@ Unknown support prevents an explicitly requested exception from starting.
1127
1164
  For an older updater that still requires Git, install the Release tarball directly:
1128
1165
 
1129
1166
  ```sh
1130
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.14/codex-copilot-dx-1.2.14.tgz
1167
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.16/codex-copilot-dx-1.2.16.tgz
1131
1168
  # Windows PowerShell: use npm.cmd instead of npm.
1132
1169
  ```
1133
1170
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.14",
3
+ "version": "1.2.16",
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",
@@ -154,7 +154,7 @@ function reconcile(operations, { restore = false, ...options } = {}) {
154
154
  });
155
155
  }
156
156
 
157
- export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, ...options } = {}) {
157
+ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, desktopAliases = false, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, ...options } = {}) {
158
158
  const entries = claudeModelEntries(models);
159
159
  const paths = claudeClientPaths(options), ids = entries.map(model => model.name), operations = [], result = {};
160
160
  const endpoint = new URL(baseUrl);
@@ -216,7 +216,12 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
216
216
  const name = typeof entry === "string" ? entry : entry?.name;
217
217
  return [typeof name === "string" ? claudeClientModelId(name) : "", index];
218
218
  }));
219
- const orderedEntries = [...entries].sort((left, right) => (order.get(left.name) ?? Infinity) - (order.get(right.name) ?? Infinity));
219
+ const desktopEntries = desktopAliases ? claudeModelEntries(models, { desktopAliases }) : entries;
220
+ for (let index = 0; index < models.length; index++) {
221
+ const old = order.get(claudeClientModelId(models[index].id));
222
+ if (old !== undefined && !order.has(desktopEntries[index].name)) order.set(desktopEntries[index].name, old);
223
+ }
224
+ const orderedEntries = [...desktopEntries].sort((left, right) => (order.get(left.name) ?? Infinity) - (order.get(right.name) ?? Infinity));
220
225
  add(paths.profile, ["inferenceModels"], JSON.stringify(orderedEntries));
221
226
  add(paths.profile, ["inferenceCustomHeaders"], JSON.stringify({ "X-CCDX-Client": "claude-app" }));
222
227
  add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: profileName }, M365_CLAUDE_PROFILE_ID);
@@ -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) {
@@ -20,21 +20,51 @@ function send(res, code, value) {
20
20
  res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
21
21
  }
22
22
  const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
23
+ function desktopMessages(body) {
24
+ const messages = [], instructions = [];
25
+ const blocks = content => {
26
+ if (typeof content === "string") return [{ type: "text", text: content }];
27
+ if (Array.isArray(content) && content.every(block => block?.type === "text" && typeof block.text === "string")) return content;
28
+ throw Object.assign(new Error("System instructions must contain text"), { code: "ccdx_messages_system_invalid", statusCode: 400 });
29
+ };
30
+ for (const message of body.messages) {
31
+ if (message?.role === "system") instructions.push(...blocks(message.content));
32
+ else messages.push(message);
33
+ }
34
+ return instructions.length ? { ...body, system: [...(body.system === undefined ? [] : blocks(body.system)), ...instructions], messages } : body;
35
+ }
23
36
  function authenticated(headers, key) {
24
37
  const candidates = [headers["x-api-key"], typeof headers.authorization === "string" ? /^Bearer (.+)$/i.exec(headers.authorization)?.[1] : null];
25
38
  const expected = Buffer.from(key);
26
39
  return candidates.some(value => typeof value === "string" && Buffer.byteLength(value) === expected.length && timingSafeEqual(Buffer.from(value), expected));
27
40
  }
28
41
 
29
- // Observe bounded SSE frames while retaining the original wire bytes for the
30
- // client. A slow client controls upstream reads; there is no independent tee.
31
- export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024) {
32
- const decoder = new TextDecoder();let fragments = [], lineBytes = 0, data = [], frameBytes = 0;
42
+ // Observe bounded SSE frames. Alias clients rewrite only message_start.model;
43
+ // other frames retain their wire text. Client backpressure controls upstream reads.
44
+ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clientModel = null) {
45
+ const decoder = new TextDecoder("utf-8", { fatal: Boolean(clientModel) });let fragments = [], lineBytes = 0, data = [], frameBytes = 0, wire = [], wireBytes = 0, output = [];
33
46
  const frame = () => {
34
- if (data.length) { let value;try { value = JSON.parse(data.join("\n")); } catch { throw new Error("Invalid Claude stream event"); }onEvent(value); }
47
+ let value;
48
+ if (data.length) { try { value = JSON.parse(data.join("\n")); } catch { throw new Error("Invalid Claude stream event"); }onEvent(value); }
49
+ if (clientModel && wire.length) {
50
+ if (value?.type === "message_start" && value.message && typeof value.message === "object" && !Array.isArray(value.message)) {
51
+ const replacement = JSON.stringify({ ...value, message: { ...value.message, model: clientModel } });let replaced = false;
52
+ wire = wire.map(line => {
53
+ if (!line.startsWith("data:")) return line;
54
+ if (replaced) return "";replaced = true;
55
+ return `data: ${replacement}${line.endsWith("\r\n") ? "\r\n" : line.endsWith("\n") ? "\n" : ""}`;
56
+ });
57
+ }
58
+ output.push(Buffer.from(wire.join("")));wire = [];wireBytes = 0;
59
+ }
35
60
  data = [];frameBytes = 0;
36
61
  };
37
- const line = value => {
62
+ const line = (value, newline = true) => {
63
+ if (clientModel) {
64
+ wireBytes += Buffer.byteLength(value) + (newline ? 1 : 0);
65
+ if (wireBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");
66
+ wire.push(value + (newline ? "\n" : ""));
67
+ }
38
68
  if (value.endsWith("\r")) value = value.slice(0, -1);
39
69
  if (!value) frame();
40
70
  else if (value.startsWith("data:")) {
@@ -47,17 +77,17 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024) {
47
77
  while (start < text.length) {
48
78
  const newline = text.indexOf("\n", start), end = newline < 0 ? text.length : newline, part = text.slice(start, end);
49
79
  lineBytes += Buffer.byteLength(part);
50
- if (lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
80
+ if (lineBytes > maxBytes || clientModel && wireBytes + lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
51
81
  fragments.push(part);
52
82
  if (newline < 0) break;
53
83
  line(fragments.join(""));fragments = [];lineBytes = 0;start = newline + 1;
54
84
  }
55
85
  }
56
- return { write(chunk) { consume(decoder.decode(chunk, { stream: true })); },
57
- finish() { consume(decoder.decode());if (fragments.length) line(fragments.join(""));frame(); } };
86
+ return { write(chunk) { output = [];consume(decoder.decode(chunk, { stream: true }));return output; },
87
+ finish() { output = [];consume(decoder.decode());if (fragments.length) line(fragments.join(""), false);frame();return output; } };
58
88
  }
59
89
 
60
- export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
90
+ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
61
91
  record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
62
92
  if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
63
93
  const config = loadRuntimeConfig(env), performance = sharedPerformance || createStreamPerformanceMetrics({ routeNames: ["messages"] });
@@ -71,7 +101,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
71
101
  if (req.method === "GET" && pathname === "/v1/models") {
72
102
  try {
73
103
  const entries = provider.models("claude");
74
- const models = claudeModelEntries(entries).map((entry, index) => ({ id: entry.name, type: "model", display_name: typeof entries[index].name === "string" && entries[index].name || entry.name }));
104
+ const models = claudeModelEntries(entries, { desktopAliases }).map((entry, index) => ({ id: entry.name, type: "model", display_name: entry.labelOverride || typeof entries[index].name === "string" && entries[index].name || entry.name }));
75
105
  send(res, 200, { data: models, has_more: false, first_id: models[0]?.id || null, last_id: models.at(-1)?.id || null });
76
106
  } catch (error) { send(res, 503, apiError(error.code || "ccdx_catalog_unavailable", "Claude model discovery is unavailable; refresh the provider catalog.")); }
77
107
  return;
@@ -85,7 +115,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
85
115
  const tracker = countTokens ? null : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
86
116
  tracker?.setProvider(provider.id);
87
117
  const abort = createRequestAbort(req, res);
88
- let release = () => {}, outcome = "failed", model = null, configuredModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
118
+ let release = () => {}, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
89
119
  let terminalOrigin = "client_validation", failureStatus = null;
90
120
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
91
121
  await runWithRequestContext({ requestId, provider: provider.id, route: "messages", streamPerformance: tracker }, async () => {
@@ -96,8 +126,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
96
126
  if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
97
127
  send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
98
128
  }
99
- model = body.model;stats.last_model = model;streamed = !countTokens && body.stream === true;
100
- configuredModel = provider.configuredModels ? resolveClaudeModel(provider.models("claude"), model)?.id : null;
129
+ if (desktopAliases) body = desktopMessages(body);
130
+ model = body.model;streamed = !countTokens && body.stream === true;
131
+ configuredModel = provider.configuredModels || desktopAliases ? resolveClaudeModel(provider.models("claude"), model, { desktopAliases })?.id : null;
132
+ if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
133
+ if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
134
+ stats.last_model = model;
101
135
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
102
136
  validateConversation?.(body, req.headers);
103
137
  terminalOrigin = "transport";
@@ -118,7 +152,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
118
152
  model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
119
153
  sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
120
154
  } else if (countTokens && upstream.ok) outcome = "completed";
121
- if (!res.destroyed && !res.writableEnded) { res.writeHead(upstream.status, headers);res.end(raw); }
155
+ const outgoing = clientModel && !countTokens && upstream.ok && value?.type === "message" ? JSON.stringify({ ...value, model: clientModel }) : raw;
156
+ if (!res.destroyed && !res.writableEnded) { res.writeHead(upstream.status, headers);res.end(outgoing); }
122
157
  } else {
123
158
  if (!/^text\/event-stream(?:\s*;|$)/i.test(upstream.headers.get("content-type") || "")) throw new Error("Expected a Claude event stream");
124
159
  abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
@@ -130,17 +165,19 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
130
165
  if (event.type === "content_block_delta" && isMessagesOutputDelta(event.delta)) tracker?.firstOutput();
131
166
  if (event.type === "message_delta") { usage = { ...usage, ...event.usage };stopReason = event.delta?.stop_reason || stopReason; }
132
167
  if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
133
- }, config.maxSseBufferBytes);
168
+ }, config.maxSseBufferBytes, clientModel);
134
169
  const reader = upstream.body.getReader();
135
170
  try {
136
171
  while (true) {
137
172
  const { value, done } = await reader.read();if (done) break;
138
173
  tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
139
- observer.write(value);
140
- if (!await writeOrDrain(res, value, { signal: abort.signal })) break;
174
+ const frames = observer.write(value);
175
+ let writable = true;
176
+ for (const chunk of clientModel ? frames : [value]) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) { writable = false;break; }
177
+ if (!writable) break;
141
178
  if (sawStop || failedEvent) break;
142
179
  }
143
- observer.finish();
180
+ for (const chunk of observer.finish()) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
144
181
  if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
145
182
  if (!res.writableEnded) res.end();
146
183
  } finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
@@ -151,10 +188,15 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
151
188
  const statusCode = detail.status || (abort.reason ? abortErrorStatusCode(abort.reason) : 502);
152
189
  failureStatus = statusCode;terminalOrigin = outcome === "cancelled" ? "client_disconnect" : statusCode < 500 && statusCode !== 429 ? "client_validation" : "transport";
153
190
  const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
154
- log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}`);
191
+ const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
192
+ log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
155
193
  tracker?.setErrorOrigin(terminalOrigin);
156
194
  if (outcome === "cancelled") return;
157
- if (!res.headersSent) send(res, statusCode, apiError(error.code || abort.reason || "ccdx_gateway_error", message));
195
+ if (!res.headersSent) {
196
+ const value = apiError(error.code || abort.reason || "ccdx_gateway_error", message);
197
+ if (diagnostic) value.error.diagnostic = diagnostic;
198
+ send(res, statusCode, value);
199
+ }
158
200
  else if (!res.destroyed && !res.writableEnded) res.end(`event: error\ndata: ${JSON.stringify(apiError("ccdx_gateway_error", message))}\n\n`);
159
201
  } finally {
160
202
  release();abort.cleanup();
@@ -164,7 +206,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
164
206
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
165
207
  tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode });
166
208
  const client = req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude";
167
- try { void Promise.resolve(record(buildMessagesUsageRecord({ model, responseId, usage, mode: streamed ? "stream" : "json", client, provider: provider.id }))).catch(() => {}); } catch {}
209
+ try { void Promise.resolve(record(buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json", client, provider: provider.id }))).catch(() => {}); } catch {}
168
210
  }
169
211
  }
170
212
  });
@@ -1,4 +1,5 @@
1
1
  import { modelReasoningEfforts } from "./provider-metadata.mjs";
2
+ import { createHash } from "node:crypto";
2
3
 
3
4
  const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
4
5
 
@@ -8,19 +9,27 @@ export function claudeClientModelId(id) {
8
9
  return id.replace(/^(claude-(?:opus|sonnet|haiku)-\d+)\.(\d+)$/, "$1-$2");
9
10
  }
10
11
 
11
- export function claudeModelEntries(models) {
12
- const ids = new Set();
12
+ function desktopModelId(id) {
13
+ // Keep native Claude identities, including their family/capability detection.
14
+ if (/^claude-(?:(?:opus|sonnet|haiku)-\d[\d.-]*|\d[\d.-]*-(?:opus|sonnet|haiku)(?:-\d{8})?)(?:-latest)?$/.test(id)) return claudeClientModelId(id);
15
+ // Digits avoid accidentally embedding a vendor name in an opaque route ID.
16
+ const digest = createHash("sha256").update(id).digest("hex").slice(0, 24);
17
+ return `ccdx/claude-compatible-${BigInt(`0x${digest}`).toString(10)}`;
18
+ }
19
+
20
+ export function claudeModelEntries(models, { desktopAliases = false } = {}) {
21
+ const ids = new Set(), upstreamIds = new Set(models.map(model => model.id));
13
22
  return models.map(model => {
14
- const name = claudeClientModelId(model.id);
15
- if (ids.has(name)) throw Object.assign(new Error("Claude model aliases collide; refresh the provider catalog"), { code: "claude_model_alias_collision", statusCode: 503 });
23
+ const name = desktopAliases ? desktopModelId(model.id) : claudeClientModelId(model.id);
24
+ if (ids.has(name) || name !== model.id && upstreamIds.has(name)) throw Object.assign(new Error("Claude model aliases collide; refresh the provider catalog"), { code: "claude_model_alias_collision", statusCode: 503 });
16
25
  ids.add(name);
17
26
  const advertised = modelReasoningEfforts(model);
18
27
  const maxEffort = EFFORTS.filter(value => advertised?.includes(value)).at(-1);
19
- return { name, ...(maxEffort ? { maxEffort } : {}) };
28
+ return { name, ...(desktopAliases && name !== claudeClientModelId(model.id) ? { labelOverride: model.id } : {}), ...(maxEffort ? { maxEffort } : {}) };
20
29
  });
21
30
  }
22
31
 
23
- export function resolveClaudeModel(models, id) {
24
- claudeModelEntries(models); // Refuse ambiguous catalogs, including exact-ID collisions.
25
- return models.find(model => model.id === id || claudeClientModelId(model.id) === id);
32
+ export function resolveClaudeModel(models, id, options) {
33
+ const entries = claudeModelEntries(models, options); // Refuse ambiguous catalogs, including exact-ID collisions.
34
+ return models.find((model, index) => model.id === id || entries[index].name === id);
26
35
  }
@@ -93,7 +93,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
93
93
  if (!source?.models?.("claude").length) { setup[id] = "unavailable";continue; }
94
94
  if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
95
95
  if (id === "claude_code" && source.id !== "m365") restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
96
- const result = configureClaude({ ...options, client: id, profileName: "CCDX", disableExperimentalBetas: source.id === "m365", desktopManaged: id === "claude_app" ? desktopManaged : false,
96
+ const result = configureClaude({ ...options, client: id, profileName: "CCDX", desktopAliases: id === "claude_app" && source.id.startsWith("api_"), disableExperimentalBetas: source.id === "m365", desktopManaged: id === "claude_app" ? desktopManaged : false,
97
97
  baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: identities()[id], models: source.models("claude") });
98
98
  setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
99
99
  } catch { setup[id] = "configuration_unavailable"; }
@@ -238,6 +238,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
238
238
  const source = requireSource(id, binding(id).source);let byClient = handlers.get(source);
239
239
  if (!byClient) { byClient = new Map();handlers.set(source, byClient); }
240
240
  if (!byClient.has(id)) byClient.set(id, createClaudeGatewayHandler({ provider: source, apiKey: identities()[id], env, log, performance: legacy.claudePerformance,
241
+ desktopAliases: id === "claude_app" && source.id.startsWith("api_"),
241
242
  validateConversation: (body, headers) => validateConversation(body, headers, source, id),
242
243
  onRequest() { lastClients[id] = new Date().toISOString(); } }));
243
244
  const finish = track(source), headers = req.headers;
@@ -18,7 +18,7 @@
18
18
  if (result.source !== "connections" || !Array.isArray(result.providers) || !Array.isArray(result.clients)) throw new Error("ccdx_connections_unavailable");return result;
19
19
  }
20
20
  function panels(which = "list") {
21
- root.hidden = el("connection-clients").hidden = el("connection-disabled").hidden = which !== "list";
21
+ root.hidden = el("connection-clients").hidden = which !== "list";
22
22
  el("connection-editor").hidden = which !== "api";el("connection-client-editor").hidden = which !== "client";el("connection-disable-editor").hidden = which !== "disable";
23
23
  apiForm.elements.key.value = "";
24
24
  }
@@ -27,8 +27,8 @@
27
27
  for (const value of options) { const item = node("option", value.name);item.value = value.id;select.append(item); }select.value = selected || "";return select;
28
28
  }
29
29
  function list() {
30
- const providerList = el("connection-source-list"), clientList = el("connection-client-list"), disabledList = el("connection-disabled-list");
31
- providerList.replaceChildren();clientList.replaceChildren();disabledList.replaceChildren();
30
+ const providerList = el("connection-source-list"), clientList = el("connection-client-list"), disabledSources = el("connection-disabled-source-list"), disabledClients = el("connection-disabled-client-list");
31
+ providerList.replaceChildren();clientList.replaceChildren();disabledSources.replaceChildren();disabledClients.replaceChildren();
32
32
  for (const provider of data.providers) {
33
33
  const row = node("div", undefined, "connection-row"), info = node("div"), actions = node("div", undefined, "connection-actions");info.append(node("h3", provider.name));
34
34
  if (!provider.builtin) info.append(node("p", provider.base_url, "hint"));
@@ -39,7 +39,7 @@
39
39
  const toggle = node("input");toggle.type = "checkbox";toggle.checked = true;toggle.setAttribute("role", "switch");toggle.setAttribute("aria-label", format("api_disable_source") + " " + provider.name);
40
40
  toggle.addEventListener("change", () => { toggle.checked = true;disableSource(provider); });actions.append(toggle);
41
41
  } else actions.append(button("api_restore", () => void change({ operation: "provider", id: provider.id, enabled: true })));
42
- row.append(info, actions);(provider.enabled ? providerList : disabledList).append(row);
42
+ row.append(info, actions);(provider.enabled ? providerList : disabledSources).append(row);
43
43
  }
44
44
  for (const c of data.clients) {
45
45
  const row = node("div", undefined, "connection-row"), info = node("div"), actions = node("div", undefined, "connection-actions");info.append(node("h3", c.name));
@@ -49,9 +49,10 @@
49
49
  const toggle = node("input");toggle.type = "checkbox";toggle.checked = true;toggle.setAttribute("role", "switch");toggle.setAttribute("aria-label", format("api_close_client") + " " + c.name);
50
50
  toggle.addEventListener("change", () => { toggle.checked = true;void change({ operation: "client", id: c.id, enabled: false, source: null, allowed: c.allowed }); });actions.append(toggle);
51
51
  } else actions.append(button("api_restore", () => void change({ operation: "client", id: c.id, enabled: true, source: null, allowed: c.allowed })));
52
- row.append(info, actions);(c.enabled ? clientList : disabledList).append(row);
52
+ row.append(info, actions);(c.enabled ? clientList : disabledClients).append(row);
53
53
  }
54
- if (!disabledList.children.length) { const empty = node("p", undefined, "hint");words(empty, "api_no_disabled");disabledList.append(empty); }
54
+ el("connection-disabled-sources").hidden = !disabledSources.children.length;
55
+ el("connection-disabled-clients").hidden = !disabledClients.children.length;
55
56
  for (const route of ["codex", "claude"]) {
56
57
  const visible = route === "codex" ? client("codex").enabled : data.clients.some(c => c.enabled && c.id.startsWith("claude_"));
57
58
  const link = document.querySelector(`[data-route="${route}"]`);if (link) link.hidden = !visible;
@@ -292,11 +292,12 @@
292
292
  <section class="panel dashboard-section" id="connection-sources">
293
293
  <div class="panel-heading"><h2 data-i18n="model_services">Model sources</h2><button id="connection-add" type="button" data-i18n="api_add">Add API</button></div>
294
294
  <div id="connection-source-list"></div>
295
+ <details id="connection-disabled-sources" class="connection-disabled" hidden><summary data-i18n="api_disabled_sources">Disabled sources</summary><div id="connection-disabled-source-list"></div></details>
295
296
  </section>
296
297
  <section class="panel dashboard-section" id="connection-clients">
297
298
  <h2 data-i18n="api_clients">Clients</h2><div id="connection-client-list"></div>
299
+ <details id="connection-disabled-clients" class="connection-disabled" hidden><summary data-i18n="api_disabled_clients">Disabled clients</summary><div id="connection-disabled-client-list"></div></details>
298
300
  </section>
299
- <details id="connection-disabled" class="connection-disabled"><summary data-i18n="api_disabled">Disabled</summary><div id="connection-disabled-list"></div></details>
300
301
  <section class="panel dashboard-section" id="connection-editor" hidden aria-labelledby="connection-editor-title">
301
302
  <div class="panel-heading"><h2 id="connection-editor-title" data-i18n="api_add">Add API</h2><button type="button" id="connection-cancel" data-i18n="cancel">Cancel</button></div>
302
303
  <form id="connection-api-form">
@@ -2,7 +2,8 @@
2
2
  const translations = {
3
3
  "api_add": ["Add API", "添加 API"],
4
4
  "api_clients": ["Clients", "客户端"],
5
- "api_disabled": ["Disabled", "已关闭"],
5
+ "api_disabled_sources": ["Disabled sources", "已关闭的模型来源"],
6
+ "api_disabled_clients": ["Disabled clients", "已关闭的客户端"],
6
7
  "api_name": ["Name", "名称"],
7
8
  "api_base": ["API address", "API 地址"],
8
9
  "api_key_private": ["Stored separately. Never sent to clients.", "独立保存,不会传给客户端。"],
@@ -36,7 +37,6 @@
36
37
  "api_current_summary": ["Current source: {source}", "当前来源:{source}"],
37
38
  "api_client_disabled": ["CCDX access is off; the app stays open.", "接入已关闭,应用保持运行。"],
38
39
  "api_close_client": ["Disable client access", "关闭客户端接入"],
39
- "api_no_disabled": ["No disabled items.", "没有已关闭的项目。"],
40
40
  "api_saved": ["Saved. Reopen the app for first-time setup; existing requests stay unchanged.", "已保存。首次接入请重新打开应用。"],
41
41
  "api_config_saved": ["API saved. Current client sources are unchanged.", "API 已保存,客户端来源未改变。"],
42
42
  "api_provider_disabled": ["Source disabled. Its configuration was kept.", "来源已关闭,配置已保留。"],
@@ -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
  }