codex-copilot-dx 1.2.15 → 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.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).
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.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).
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. 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).
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
 
@@ -62,6 +62,20 @@ independent app/code lifecycles. M365 beta policy is not imposed on API clients;
62
62
  adding a source alone never migrates old client credentials. Configuring clients
63
63
  does not patch/restart their binaries or override managed settings.
64
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
+
65
79
  `conversation-source-guard.mjs` retains bounded HMAC correlations for observed
66
80
  managed histories. Known source/key conflicts fail before forwarding. It does
67
81
  not establish provenance for an unseen history or implement dynamic affinity.
@@ -70,6 +84,8 @@ The existing Responses route-plan boundary continues to own opaque-state checks.
70
84
  `dashboard/connections.js` owns settings forms; application source/review and
71
85
  account/catalog views keep their existing scopes and use the same backend graph.
72
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.
73
89
  Shared Messages observation includes all sources, while M365-specific status
74
90
  projects M365 counts. Bounds cover two built-ins plus 16 APIs without unbounded
75
91
  labels, request histories, body logging or a new refresh loop.
package/docs/REFERENCE.md CHANGED
@@ -48,10 +48,33 @@ or inference call. **Read models** performs one explicit catalog read, with a
48
48
  support until reviewed. Opening normal views reads saved models rather than
49
49
  probing every API. `ccdx models` labels manual models as configured, not live.
50
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.
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.
55
78
 
56
79
  `connections.json` beside user settings (respecting `XDG_CONFIG_HOME`) stores a
57
80
  strict version-one graph of provider switches, API metadata and each client's
@@ -65,7 +88,9 @@ Private helpers omit unrelated credentials and Node hooks. API error bodies are
65
88
  replaced with stable codes; valid Retry-After metadata is retained.
66
89
 
67
90
  `client-gateway-keys.json` holds local credentials separately. Disabled sources
68
- 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**.
69
94
  Closing a client stops CCDX access, not the app. Disabling an in-use source
70
95
  requires explicit replacements or pauses. Pinned API streams finish on their
71
96
  original provider; retired transports/keys are released afterwards. Legacy M365
@@ -1139,7 +1164,7 @@ Unknown support prevents an explicitly requested exception from starting.
1139
1164
  For an older updater that still requires Git, install the Release tarball directly:
1140
1165
 
1141
1166
  ```sh
1142
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.15/codex-copilot-dx-1.2.15.tgz
1167
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.16/codex-copilot-dx-1.2.16.tgz
1143
1168
  # Windows PowerShell: use npm.cmd instead of npm.
1144
1169
  ```
1145
1170
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.15",
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);
@@ -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(); }
@@ -169,7 +206,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, o
169
206
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
170
207
  tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode });
171
208
  const client = req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude";
172
- 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 {}
173
210
  }
174
211
  }
175
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.", "来源已关闭,配置已保留。"],