codex-copilot-dx 1.2.16 → 1.2.18

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.
@@ -88,12 +88,13 @@ export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024, clie
88
88
  }
89
89
 
90
90
  export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
91
- record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
91
+ resolveRequest, record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
92
92
  if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
93
93
  const config = loadRuntimeConfig(env), performance = sharedPerformance || createStreamPerformanceMetrics({ routeNames: ["messages"] });
94
94
  const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
95
95
  const stats = { total: 0, active: 0, completed: 0, incomplete: 0, failed: 0, cancelled: 0, last_request_at: null, last_model: null };
96
96
  async function dispatch(req, res) {
97
+ let selectedProvider = provider, finishProvider = () => {};
97
98
  if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers.host === undefined || !isLoopbackHostHeader(req.headers.host)
98
99
  || Object.hasOwn(req.headers, "origin")) { send(res, 403, apiError("ccdx_local_only", "The Claude gateway accepts native local clients only"));return; }
99
100
  if (!authenticated(req.headers, apiKey)) { send(res, 401, apiError("ccdx_gateway_auth", "Invalid local gateway credential"));return; }
@@ -101,7 +102,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
101
102
  if (req.method === "GET" && pathname === "/v1/models") {
102
103
  try {
103
104
  const entries = provider.models("claude");
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 }));
105
+ const models = claudeModelEntries(entries, { desktopAliases }).map((entry, index) => ({ id: entry.name, type: "model", ...(entry.supports1m ? { supports_1m: true } : {}), display_name: entry.labelOverride || typeof entries[index].name === "string" && entries[index].name || entry.name }));
105
106
  send(res, 200, { data: models, has_more: false, first_id: models[0]?.id || null, last_id: models.at(-1)?.id || null });
106
107
  } catch (error) { send(res, 503, apiError(error.code || "ccdx_catalog_unavailable", "Claude model discovery is unavailable; refresh the provider catalog.")); }
107
108
  return;
@@ -113,12 +114,12 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
113
114
  if (parent) parent.provider = provider.id;
114
115
  const countTokens = pathname.endsWith("/count_tokens"), requestId = parent?.requestId || randomUUID();
115
116
  const tracker = countTokens ? null : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
116
- tracker?.setProvider(provider.id);
117
+ if (!resolveRequest) tracker?.setProvider(provider.id);
117
118
  const abort = createRequestAbort(req, res);
118
119
  let release = () => {}, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
119
120
  let terminalOrigin = "client_validation", failureStatus = null;
120
121
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
121
- await runWithRequestContext({ requestId, provider: provider.id, route: "messages", streamPerformance: tracker }, async () => {
122
+ await runWithRequestContext({ requestId, provider: selectedProvider.id, route: "messages", streamPerformance: tracker }, async () => {
122
123
  try {
123
124
  release = await acquireRequest(req, { signal: abort.signal });
124
125
  abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
@@ -126,16 +127,23 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
126
127
  if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
127
128
  send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
128
129
  }
130
+ if (resolveRequest) {
131
+ const resolved = await resolveRequest(body, req);
132
+ selectedProvider = resolved.provider;finishProvider = resolved.finish || finishProvider;
133
+ configuredModel = resolved.model;clientModel = body.model === configuredModel ? null : body.model;
134
+ body = { ...body, model: configuredModel };tracker?.setProvider(selectedProvider.id);
135
+ const context = currentRequestContext();if (context) context.provider = selectedProvider.id;
136
+ }
129
137
  if (desktopAliases) body = desktopMessages(body);
130
138
  model = body.model;streamed = !countTokens && body.stream === true;
131
- configuredModel = provider.configuredModels || desktopAliases ? resolveClaudeModel(provider.models("claude"), model, { desktopAliases })?.id : null;
139
+ if (!resolveRequest) configuredModel = provider.configuredModels || desktopAliases ? resolveClaudeModel(provider.models("claude"), model, { desktopAliases })?.id : null;
132
140
  if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
133
141
  if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
134
142
  stats.last_model = model;
135
143
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
136
- validateConversation?.(body, req.headers);
144
+ validateConversation?.(body, req.headers, selectedProvider);
137
145
  terminalOrigin = "transport";
138
- const upstream = await provider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
146
+ const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
139
147
  onUpstreamStart() { abort.setTimeout(streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs, "upstream_timeout"); } });
140
148
  body = null;
141
149
  terminalOrigin = upstream.ok ? "upstream_response" : "upstream_http";
@@ -199,14 +207,14 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
199
207
  }
200
208
  else if (!res.destroyed && !res.writableEnded) res.end(`event: error\ndata: ${JSON.stringify(apiError("ccdx_gateway_error", message))}\n\n`);
201
209
  } finally {
202
- release();abort.cleanup();
210
+ release();abort.cleanup();finishProvider();
203
211
  if (!countTokens) {
204
212
  stats.active--;stats[outcome]++;
205
213
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
206
214
  tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
207
215
  tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: failureStatus || res.statusCode });
208
216
  const client = req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude";
209
- try { void Promise.resolve(record(buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json", client, provider: provider.id }))).catch(() => {}); } catch {}
217
+ try { void Promise.resolve(record(buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json", client, provider: selectedProvider.id }))).catch(() => {}); } catch {}
210
218
  }
211
219
  }
212
220
  });
@@ -20,16 +20,19 @@ function desktopModelId(id) {
20
20
  export function claudeModelEntries(models, { desktopAliases = false } = {}) {
21
21
  const ids = new Set(), upstreamIds = new Set(models.map(model => model.id));
22
22
  return models.map(model => {
23
- const name = desktopAliases ? desktopModelId(model.id) : claudeClientModelId(model.id);
23
+ const name = model.client_id || (desktopAliases ? desktopModelId(model.id) : claudeClientModelId(model.id));
24
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 });
25
25
  ids.add(name);
26
- const advertised = modelReasoningEfforts(model);
26
+ const advertised = model.capability?.values.reasoning === false ? [] : model.capability?.values.reasoning_efforts || modelReasoningEfforts(model);
27
27
  const maxEffort = EFFORTS.filter(value => advertised?.includes(value)).at(-1);
28
- return { name, ...(desktopAliases && name !== claudeClientModelId(model.id) ? { labelOverride: model.id } : {}), ...(maxEffort ? { maxEffort } : {}) };
28
+ return { name, ...(model.display_name || desktopAliases && name !== claudeClientModelId(model.id) ? { labelOverride: model.display_name || model.id } : {}),
29
+ ...(model.capability?.values.context_window >= 1000000 ? { supports1m: true } : {}), ...(maxEffort ? { maxEffort } : {}) };
29
30
  });
30
31
  }
31
32
 
32
33
  export function resolveClaudeModel(models, id, options) {
33
34
  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);
35
+ const alias = entries.findIndex(entry => entry.name === id);
36
+ if (alias >= 0) return models[alias];
37
+ const exact = models.filter(model => model.id === id);return exact.length === 1 ? exact[0] : undefined;
35
38
  }
@@ -0,0 +1,75 @@
1
+ import { deploymentModelId, resolveModelCapabilities, claudeEffortsExpressible } from "./model-capabilities.mjs";
2
+ import { claudeModelEntries } from "./claude-models.mjs";
3
+
4
+ const endpoints = { codex: ["/responses", "/v1/responses"], claude_app: ["/v1/messages"], claude_code: ["/v1/messages"] };
5
+ export function sourceModels(source, client) {
6
+ if (!source) return [];
7
+ const models = source.models?.(client === "codex" ? "gpt" : "claude") || source.registry?.models?.data || [];
8
+ return models.filter(model => model.supported_endpoints?.some(endpoint => endpoints[client].includes(endpoint)
9
+ || client === "codex" && source.id === "github" && ["/chat/completions", "/v1/chat/completions"].includes(endpoint)));
10
+ }
11
+
12
+ export function compileClientModels({ client, binding, source, enabled, names = {}, desktopEffortAliases = false }) {
13
+ if (!binding.enabled) return { models: [], routes: new Map(), defaultModel: null, revision: "disabled" };
14
+ const explicit = Array.isArray(binding.deployments), selected = explicit ? binding.deployments : binding.source
15
+ ? sourceModels(source(binding.source), client).map(model => ({ source: binding.source, model: model.id })) : [];
16
+ const models = [], routes = new Map(), raw = new Map();
17
+ for (const item of selected) {
18
+ if (!binding.allowed.includes(item.source) || !enabled(item.source)) continue;
19
+ const provider = source(item.source), model = sourceModels(provider, client).find(model => model.id === item.model);
20
+ if (!model || model.policy?.state && model.policy.state !== "enabled" || model.model_picker_enabled === false) continue;
21
+ const route = deploymentModelId(item.source, model.id), capability = model.capability || resolveModelCapabilities(model, { builtin: true });
22
+ const entry = { ...model, capability, source_id: item.source, route_id: route,
23
+ ...(explicit ? { client_id: route, display_name: `${model.id} · ${names[item.source] || item.source}` } : {}) };
24
+ if (client === "claude_app" && explicit) {
25
+ const number = route.slice("ccdx/model-".length);
26
+ const efforts = capability.values.reasoning === false ? [] : capability.values.reasoning_efforts || [];
27
+ const native = /^claude-(?:opus|sonnet|haiku)-\d[\d.-]*(?:-latest)?$/.test(model.id);
28
+ entry.client_id = native ? `ccdx-${number}.anthropic.${model.id.replace(/(\d)\.(\d)/g, "$1-$2")}`
29
+ : desktopEffortAliases && claudeEffortsExpressible(capability.values) ? `mythos-ccdx-${number}` : `ccdx/claude-compatible-${number}`;
30
+ }
31
+ const publicId = explicit ? entry.client_id : client === "codex" ? model.id : claudeModelEntries([entry], { desktopAliases: client === "claude_app" && provider.id.startsWith("api_") })[0].name;
32
+ entry.public_id = publicId;
33
+ const record = { provider, model: entry, source: item.source, upstreamModel: model.id, publicId };
34
+ if (routes.has(publicId)) throw Object.assign(new Error("Model routes collide"), { code: "ccdx_model_route_collision", statusCode: 503 });
35
+ routes.set(publicId, record);routes.set(route, record);
36
+ if (client === "claude_app" && explicit) {
37
+ const number = route.slice("ccdx/model-".length);routes.set(`mythos-ccdx-${number}`, record);routes.set(`ccdx/claude-compatible-${number}`, record);
38
+ }
39
+ models.push(entry);
40
+ raw.set(model.id, raw.has(model.id) ? null : record);
41
+ }
42
+ // Old model IDs/desktop aliases remain valid only when they resolve to one
43
+ // authorized deployment. Same-named deployments never pick the first source.
44
+ for (const [id, record] of raw) if (record && !routes.has(id)) {
45
+ routes.set(id, record);
46
+ if (client !== "codex") {
47
+ for (const options of [{ desktopAliases: false }, { desktopAliases: true }]) {
48
+ const old = claudeModelEntries([{ ...record.model, client_id: undefined }], options)[0].name;
49
+ if (!routes.has(old)) routes.set(old, record);
50
+ }
51
+ }
52
+ }
53
+ const fallback = models.find(model => model.id === binding.model || model.route_id === binding.default_model) || models[0];
54
+ return { models, routes, defaultModel: routes.get(binding.default_model)?.publicId || fallback?.public_id || null,
55
+ revision: models.map(model => model.route_id + ":" + model.capability.revision).join(";") };
56
+ }
57
+
58
+ // Client metadata is a projection, never a source of deployment capabilities.
59
+ export function codexModelEntry(model, { priority = 0, name = "", template = {} } = {}) {
60
+ const values = model.capability?.values || {}, efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
61
+ return { shell_type: "unified_exec", availability_nux: null, upgrade: null, additional_speed_tiers: [], service_tiers: [],
62
+ base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
63
+ supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
64
+ experimental_supported_tools: [], input_modalities: values.input_modalities || ["text"], ...template,
65
+ slug: model.public_id || model.id, display_name: model.display_name || model.id, description: name, visibility: "list", supported_in_api: true, priority,
66
+ default_reasoning_level: efforts[0] || null, supported_reasoning_levels: efforts.map(effort => ({ effort, description: effort })),
67
+ context_window: values.context_window || template.context_window || null, max_context_window: values.context_window || template.max_context_window || null };
68
+ }
69
+ export function codexClientCatalog(plan, source) {
70
+ return Object.assign((value, nativeCatalog) => ({ ...value, models: plan.models.map((model, priority) => {
71
+ const template = model.source_id === "github" ? nativeCatalog?.models?.find(entry => entry.slug === model.id)
72
+ : source(model.source_id).codexCatalog?.({ models: [] })?.models?.find(entry => entry.slug === model.id);
73
+ return codexModelEntry(model, { priority, template, name: model.source_id });
74
+ }) }), { needsNativeCatalog: plan.models.some(model => model.source_id === "github") });
75
+ }
@@ -8,6 +8,17 @@ import { atomicWriteFilePairSync } from "./atomic-file.mjs";
8
8
  import { withFileLockSync } from "./lock.mjs";
9
9
 
10
10
  const ID = "ccdx_gateway";
11
+ function retainsCodexSignIn(config, directory, env) {
12
+ if (["keyring", "auto"].includes(config.cli_auth_credentials_store) || config.forced_login_method
13
+ || config.forced_chatgpt_workspace_id || ["CODEX_ACCESS_TOKEN", "CODEX_API_KEY", "OPENAI_API_KEY"].some(key => env[key])) return true;
14
+ try {
15
+ const auth = JSON.parse(readBoundedFileSync(path.join(directory, "auth.json"), { encoding: "utf8", maxBytes: 1024 * 1024 }));
16
+ return Boolean(auth?.auth_mode || auth?.tokens || auth?.OPENAI_API_KEY);
17
+ } catch (error) {
18
+ if (error.code === "ENOENT") return false;
19
+ throw accessError("ccdx_codex_config_invalid", 409);
20
+ }
21
+ }
11
22
  // Only the provider, selected model and private provider table are owned.
12
23
  export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...options } = {}) {
13
24
  if (!restore) {
@@ -27,7 +38,9 @@ export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...
27
38
  const firstTable = content.search(/^\s*\[/m), head = firstTable < 0 ? content : content.slice(0, firstTable), tail = firstTable < 0 ? "" : content.slice(firstTable);
28
39
  const sectionPattern = /^\[model_providers\.ccdx_gateway\]\r?\n[^]*?(?=^\[|$(?![^]))/m;
29
40
  const currentSection = tail.match(sectionPattern)?.[0] || null;
30
- if (owner && (config.model_provider !== ID || currentSection !== owner.section || owner.model !== undefined && config.model !== owner.model)) return { state: "preserved" };
41
+ if (owner && (config.model_provider !== ID || currentSection !== owner.section)) return { state: "preserved" };
42
+ const modelEdited = owner?.model !== undefined && config.model !== owner.model;
43
+ if (restore && modelEdited) return { state: "preserved" };
31
44
  if (!owner && (config.model_provider && config.model_provider !== "openai" || config.model_providers?.[ID])) return { state: "preserved" };
32
45
  let next, nextOwner = null;
33
46
  if (restore) {
@@ -36,16 +49,19 @@ export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...
36
49
  if (owner.model !== undefined) root = root.replace(/^model\s*=.*(?:\r?\n|$)/m, owner.beforeModel || "");
37
50
  next = root + tail.replace(sectionPattern, owner.beforeSection || "");
38
51
  } else {
39
- const section = `[model_providers.${ID}]\nname = "CCDX"\nbase_url = ${JSON.stringify(baseUrl)}\nmodel_catalog_url = ${JSON.stringify(baseUrl + "/models")}\nwire_api = "responses"\nexperimental_bearer_token = ${JSON.stringify(apiKey)}\n\n`;
52
+ // Account identity remains native; only model traffic uses the local key.
53
+ const requiresAuth = retainsCodexSignIn(config, path.dirname(file), options.env || process.env);
54
+ const section = `[model_providers.${ID}]\nname = "CCDX"\nbase_url = ${JSON.stringify(baseUrl)}\nmodel_catalog_url = ${JSON.stringify(baseUrl + "/models")}\nwire_api = "responses"\nrequires_openai_auth = ${requiresAuth}\nexperimental_bearer_token = ${JSON.stringify(apiKey)}\n\n`;
40
55
  let root = head;
41
- if (model) root = root.match(/^model\s*=/m) ? root.replace(/^model\s*=.*(?:\r?\n|$)/m, `model = ${JSON.stringify(model)}\n`) : `model = ${JSON.stringify(model)}\n` + root;
56
+ if (model && !modelEdited) root = root.match(/^model\s*=/m) ? root.replace(/^model\s*=.*(?:\r?\n|$)/m, `model = ${JSON.stringify(model)}\n`) : `model = ${JSON.stringify(model)}\n` + root;
42
57
  next = (root.match(/^model_provider\s*=/m) ? root.replace(/^model_provider\s*=.*(?:\r?\n|$)/m, `model_provider = "${ID}"\n`) : `model_provider = "${ID}"\n` + root)
43
58
  + (currentSection ? tail.replace(sectionPattern, section) : tail + (tail && !tail.endsWith("\n") ? "\n" : "") + "\n" + section);
44
59
  nextOwner = { version: 1, beforeProvider: owner ? owner.beforeProvider : head.match(/^model_provider\s*=.*(?:\r?\n|$)/m)?.[0] || null,
45
60
  beforeSection: owner ? owner.beforeSection : currentSection, section,
46
- ...(model ? { model, beforeModel: owner && Object.hasOwn(owner, "beforeModel") ? owner.beforeModel : head.match(/^model\s*=.*(?:\r?\n|$)/m)?.[0] || null } : {}) };
61
+ ...(modelEdited ? { model: owner.model, beforeModel: owner.beforeModel }
62
+ : model ? { model, beforeModel: owner && Object.hasOwn(owner, "beforeModel") ? owner.beforeModel : head.match(/^model\s*=.*(?:\r?\n|$)/m)?.[0] || null } : {}) };
47
63
  }
48
64
  parse(next);if (next !== content || JSON.stringify(nextOwner) !== JSON.stringify(owner)) atomicWriteFilePairSync(file, next, journal, nextOwner ? JSON.stringify(nextOwner) + "\n" : null, { mode: 0o600 });
49
- return { state: "configured", changed: next !== content };
65
+ return { state: modelEdited ? "preserved" : "configured", changed: next !== content };
50
66
  });
51
67
  }