codex-copilot-dx 1.2.16 → 1.2.17

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,17 +8,24 @@ import { createClaudeGatewayHandler } from "./claude-gateway.mjs";
8
8
  import { configureClaudeClients, restoreClaudeClients, inspectClaudeDesktopPolicy } from "./claude-client-config.mjs";
9
9
  import { configureCodexApi } from "./codex-api-config.mjs";
10
10
  import { autoReviewReasoningEfforts } from "./models.mjs";
11
+ import { createRequestAdmission } from "./request-admission.mjs";
11
12
  import { createConversationSourceGuard } from "./conversation-source-guard.mjs";
13
+ import { compileClientModels, sourceModels, codexClientCatalog } from "./client-model-plan.mjs";
14
+ import { currentRequestContext } from "./request-context.mjs";
15
+ import { claudeSharedCapabilityPlan, syncClaudeCapabilities, inspectClaudeCapabilitySupport, inspectClaudeCapabilityConfiguration } from "./claude-capability-config.mjs";
16
+ import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from "./model-capabilities.mjs";
12
17
 
13
18
  const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
14
19
  export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
15
20
  secretStore, createApi = createApiProvider, configureClaude = configureClaudeClients, restoreClaude = restoreClaudeClients,
16
21
  configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, log = () => {} } = {}) {
17
22
  const options = { home, env, platform }, secrets = secretStore || createApiSecretStore(options);
18
- const guardConversation = createConversationSourceGuard(options);
23
+ const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
19
24
  let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
20
- const instances = new Map(), active = new Map(), retired = new Set(), handlers = new WeakMap(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
21
- const retiredSecrets = new Map(), cleanups = new Set();
25
+ const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
26
+ const retiredSecrets = new Map(), cleanups = new Set(), plans = new Map(), discoveries = new Map();
27
+ const capabilitySupport = inspectClaudeCapabilitySupport(options);
28
+ let sharedSync = null, syncFlight = null, syncAgain = false;
22
29
  function cleanSecrets(id) {
23
30
  const refs = retiredSecrets.get(id);if (!refs) return;
24
31
  for (const ref of refs) {
@@ -41,6 +48,22 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
41
48
  const source = createApi({ config, secrets, env, platform });instances.set(id, { signature, source, config });sourceSecrets.set(source, config.secret_ref);
42
49
  if (previous) retire(previous.source);return source;
43
50
  }
51
+ function plan(id) {
52
+ const selected = binding(id), definitions = selected.allowed.filter(enabled).map(source => getSource(source)).filter(Boolean);
53
+ const cached = plans.get(id), stamps = definitions.map(source => [source, source.registry?.generation, source.registry?.models, source.profileId()]);
54
+ if (cached?.binding === selected && cached.stamps.length === stamps.length && stamps.every((stamp, index) => stamp.every((value, at) => cached.stamps[index][at] === value))) return cached.value;
55
+ const value = compileClientModels({ client: id, binding: selected, source: getSource, enabled,
56
+ names: Object.fromEntries([["github", "GitHub Copilot"], ["m365", "Microsoft 365"], ...settings.apis.map(api => [api.id, api.name])]),
57
+ desktopEffortAliases: capabilitySupport.app });
58
+ plans.set(id, { binding: selected, stamps, value });return value;
59
+ }
60
+ function resolveDeployment(id, model) {
61
+ const value = plan(id), record = value.routes.get(model);
62
+ if (!record) throw accessError("ccdx_api_model_unavailable");
63
+ const provider = requireSource(id, record.source);
64
+ if (provider !== record.provider) { plans.delete(id);return resolveDeployment(id, model); }
65
+ return record;
66
+ }
44
67
  function retire(source) { if (active.get(source)) retired.add(source);else source.close(); }
45
68
  function track(source) {
46
69
  const finishLegacy = legacy.track(source);active.set(source, (active.get(source) || 0) + 1);let done = false;
@@ -56,6 +79,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
56
79
  return next;
57
80
  }
58
81
  function save(next) {
82
+ plans.clear();
59
83
  settings = structuredClone(updateAccessSettings(current => {
60
84
  if (JSON.stringify(current) !== JSON.stringify(settings)) throw accessError("ccdx_connections_conflict", 409);return next;
61
85
  }, options));managed = true;
@@ -74,30 +98,46 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
74
98
  { id: "github", name: "GitHub Copilot", enabled: config.providers.github, builtin: true, protocols: ["responses"] },
75
99
  { id: "m365", name: "Microsoft 365", enabled: config.providers.m365, builtin: true, protocols: ["messages", "responses"] },
76
100
  ...config.apis.map(api => { const { secret_ref, ...publicApi } = api;return { ...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
77
- ...summary(api), builtin: false, key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref) }; }),
101
+ ...summary(api), ...(compact ? {} : { deployment_revision: deploymentRevision(api, env) }), discovery: discoveries.get(api.id) || null, builtin: false, key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref) }; }),
78
102
  ], clients: CLIENT_IDS.map(id => ({ id, name: CLIENT_NAMES[id], ...config.clients[id], setup: setup[id] || null,
79
- observed_at: lastClients[id] || null })), managed, m365_state: state.m365.state });
103
+ observed_at: lastClients[id] || null, ...(compact ? {} : { model_plan: { default_model: plan(id).defaultModel,
104
+ models: plan(id).models.map(model => ({ source: model.source_id, id: model.id, public_id: model.public_id, route_id: model.route_id, capability: model.capability })),
105
+ available: config.clients[id].allowed.filter(enabled).flatMap(source => sourceModels(getSource(source), id).map(model => ({ source, id: model.id,
106
+ route_id: deploymentModelId(source, model.id), capability: model.capability || resolveModelCapabilities(model, { builtin: true }) }))), sync: sharedSync, support: capabilitySupport } }) })), managed, m365_state: state.m365.state });
80
107
  }
81
108
  async function syncClients() {
109
+ syncAgain = true;if (syncFlight) return syncFlight;
110
+ syncFlight = (async () => { do { syncAgain = false;await performClientSync(); } while (syncAgain && !closed); })();
111
+ try { return await syncFlight; } finally { syncFlight = null; }
112
+ }
113
+ async function performClientSync() {
82
114
  if (!managed || closed) return;
83
115
  const codex = binding("codex");
84
- try { setup.codex = configureCodex({ ...options, ...(codex.enabled && codex.source?.startsWith("api_")
85
- ? { baseUrl: `http://127.0.0.1:${corePort}/v1`, apiKey: identities().codex, model: codex.model } : { restore: true }) }).state; }
116
+ try { if (codex.enabled && codex.auto_sync === false) setup.codex = "manual_sync";else setup.codex = configureCodex({ ...options, ...(codex.enabled && (Array.isArray(codex.deployments) || codex.source?.startsWith("api_"))
117
+ ? { baseUrl: `http://127.0.0.1:${corePort}/v1`, apiKey: identities().codex, model: plan("codex").defaultModel || codex.model } : { restore: true }) }).state; }
86
118
  catch { setup.codex = "configuration_unavailable"; }
87
119
  if (!settings.claude_private_keys) return;
88
120
  let desktopManaged;
89
121
  for (const id of ["claude_app", "claude_code"]) {
90
- const selected = binding(id), source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
122
+ const selected = binding(id), compiled = plan(id), source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
91
123
  try {
92
- if (!selected.enabled || !selected.source || !permitted(id, selected.source)) { const result = restoreClaude({ ...options, client: id });setup[id] = result.preserved ? "preserved" : "not_configured";continue; }
93
- if (!source?.models?.("claude").length) { setup[id] = "unavailable";continue; }
124
+ if (!selected.enabled || !compiled.models.length) { const result = restoreClaude({ ...options, client: id });setup[id] = result.preserved ? "preserved" : "not_configured";continue; }
125
+ if (selected.auto_sync === false) { setup[id] = "manual_sync";continue; }
94
126
  if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
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", desktopAliases: id === "claude_app" && source.id.startsWith("api_"), disableExperimentalBetas: source.id === "m365", desktopManaged: id === "claude_app" ? desktopManaged : false,
97
- baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: identities()[id], models: source.models("claude") });
127
+ const m365Only = compiled.models.every(model => model.source_id === "m365");
128
+ if (id === "claude_code" && !m365Only) restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
129
+ const result = configureClaude({ ...options, client: id, profileName: "CCDX", desktopAliases: id === "claude_app" && source?.id.startsWith("api_"), disableExperimentalBetas: m365Only, desktopManaged: id === "claude_app" ? desktopManaged : false,
130
+ baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: identities()[id], models: compiled.models, defaultModel: Array.isArray(selected.deployments) ? compiled.defaultModel : undefined });
98
131
  setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
99
132
  } catch { setup[id] = "configuration_unavailable"; }
100
133
  }
134
+ const shared = claudeSharedCapabilityPlan({ app: setup.claude_app === "configured" ? plan("claude_app").models : [],
135
+ code: setup.claude_code === "configured" ? plan("claude_code").models : [], support: capabilitySupport });
136
+ if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
137
+ sharedSync = { ...shared, state: "partially_preserved", limitations: [...shared.limitations, { code: "manual_sync" }] };return;
138
+ }
139
+ try { sharedSync = { ...shared, ...syncClaudeCapabilities(shared, options) }; }
140
+ catch { sharedSync = { state: "configuration_unavailable", limitations: shared.limitations }; }
101
141
  }
102
142
  function requireSource(clientId, id) {
103
143
  if (!permitted(clientId, id)) throw accessError("ccdx_client_source_disabled", 503);
@@ -106,11 +146,11 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
106
146
  }
107
147
  function validateConversation(body, headers, source, client = "codex") {
108
148
  if (!body || typeof body !== "object" || Array.isArray(body)) return;
109
- if (managed && (binding(client).history_isolation || source.id.startsWith("api_"))) guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client]);
149
+ if (managed && (binding(client).history_isolation || source?.id.startsWith("api_"))) guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client]);
110
150
  }
111
151
  async function change(input) {
112
152
  if (closed) throw accessError("ccdx_connections_closed", 503);
113
- if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "model", "auto_review_model", "auto_review_effort"])) throw accessError("ccdx_connections_action_invalid");
153
+ if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "model", "auto_review_model", "auto_review_effort", "deployments", "default_model", "auto_sync"])) throw accessError("ccdx_connections_action_invalid");
114
154
  const next = editable();let freshRef, previousRef;
115
155
  if (input.operation === "save_api") {
116
156
  const existing = next.apis.find(api => api.id === input.id);
@@ -122,8 +162,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
122
162
  const config = checkedApi({ ...input.config, id, enabled: existing?.enabled ?? true, ...(!input.config.key_env ? { secret_ref: freshRef || existing.secret_ref } : {}) });
123
163
  if (!Array.isArray(input.allowed) || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
124
164
  for (const id of CLIENT_IDS) {
125
- const c = next.clients[id];if (c.source === config.id && !input.allowed.includes(id)) throw accessError("ccdx_source_in_use", 409);
126
- if (c.source === config.id && c.enabled && (!config.models.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages"))
165
+ const c = next.clients[id];if (c.deployments?.some(item => item.source === config.id && (!input.allowed.includes(id)
166
+ || !config.models.some(model => model.id === item.model && model.protocols.includes(id === "codex" ? "responses" : "messages"))))) throw accessError("ccdx_source_in_use", 409);
167
+ if (c.source === config.id && !input.allowed.includes(id)) throw accessError("ccdx_source_in_use", 409);
168
+ if (c.source === config.id && c.enabled && !Array.isArray(c.deployments) && (!config.models.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages"))
127
169
  || id === "codex" && [c.model, c.auto_review_model].filter(Boolean).some(value => !config.models.some(model => model.id === value && model.protocols.includes("responses"))))) throw accessError("ccdx_api_model_unavailable");
128
170
  if (input.allowed.includes(id) && !config.endpoints[id === "codex" ? "responses" : "messages"]) throw accessError("ccdx_api_protocol_required");
129
171
  c.allowed = [...new Set([...c.allowed.filter(value => value !== config.id), ...(input.allowed.includes(id) ? [config.id] : [])])];
@@ -131,17 +173,36 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
131
173
  if (existing) { previousRef = existing.secret_ref;next.apis[next.apis.indexOf(existing)] = config; } else next.apis.push(config);
132
174
  checkedAccessSettings(next);
133
175
  try { if (freshRef) await secrets.set(freshRef, input.key);save(next); } catch (error) { if (freshRef) await secrets.remove(freshRef).catch(() => {});throw error; }
134
- } else if (input.operation === "client") {
176
+ } else if (["client", "preview_client"].includes(input.operation)) {
135
177
  if (!CLIENT_IDS.includes(input.id) || typeof input.enabled !== "boolean" || !Array.isArray(input.allowed)
136
- || input.source !== null && !input.allowed.includes(input.source)) throw accessError("ccdx_connections_action_invalid");
137
- const old = next.clients[input.id], retained = { ...old };if (old.source !== input.source) for (const key of ["model", "auto_review_model", "auto_review_effort"]) delete retained[key];
138
- next.clients[input.id] = { ...retained, enabled: input.enabled, allowed: input.allowed, source: input.enabled ? input.source : null,
178
+ || input.source !== null && input.source !== undefined && !input.allowed.includes(input.source)) throw accessError("ccdx_connections_action_invalid");
179
+ const old = next.clients[input.id], retained = { ...old };if (old.source !== input.source || Array.isArray(old.deployments) && input.deployments === null) for (const key of ["model", "auto_review_model", "auto_review_effort"]) delete retained[key];
180
+ next.clients[input.id] = { ...retained, enabled: input.enabled, allowed: input.allowed, source: input.enabled ? input.source ?? old.source : null,
181
+ ...(input.deployments !== undefined ? { deployments: input.deployments, default_model: input.default_model ?? null, auto_sync: input.auto_sync ?? true }
182
+ : old.source !== input.source ? { deployments: null, default_model: null } : {}),
139
183
  ...(input.model ? { model: input.model } : {}), ...(input.auto_review_model ? { auto_review_model: input.auto_review_model } : {}),
140
184
  ...(input.auto_review_effort !== undefined ? { auto_review_effort: input.auto_review_effort } : {}) };
141
185
  if (input.id !== "codex") next.claude_private_keys = true;
142
186
  if (old.source !== input.source) next.clients[input.id].history_isolation = true;
143
187
  const c = next.clients[input.id];
144
- if (c.source) {
188
+ if (Array.isArray(input.deployments)) {
189
+ checkedAccessSettings(next);
190
+ for (const item of c.deployments || []) {
191
+ if (!enabled(item.source) || !sourceModels(getSource(item.source), input.id).some(model => model.id === item.model)) throw accessError("ccdx_api_model_unavailable");
192
+ }
193
+ const names = Object.fromEntries(next.apis.map(api => [api.id, api.name]));
194
+ const compiled = compileClientModels({ client: input.id, binding: c, source: getSource, enabled, names, desktopEffortAliases: capabilitySupport.app });
195
+ if (c.default_model && !compiled.routes.has(c.default_model)) throw accessError("ccdx_api_model_unavailable");
196
+ c.default_model = compiled.routes.get(compiled.defaultModel)?.model.route_id || null;c.source = c.enabled ? compiled.routes.get(c.default_model)?.source || null : null;
197
+ c.history_isolation = true;
198
+ if (input.id === "codex") {
199
+ c.model = compiled.routes.get(c.default_model)?.upstreamModel;
200
+ const review = compiled.routes.get(old.auto_review_model) || [...compiled.routes.values()].find(record => record.source === old.source && record.upstreamModel === old.auto_review_model);
201
+ if (c.default_model) c.auto_review_model = review?.source === c.source ? review.model.route_id : c.default_model;else delete c.auto_review_model;
202
+ if (review?.source === c.source && old.auto_review_effort !== undefined) c.auto_review_effort = old.auto_review_effort;else delete c.auto_review_effort;
203
+ }
204
+ }
205
+ if (c.source && !Array.isArray(input.deployments)) {
145
206
  if (!enabled(c.source)) throw accessError("ccdx_client_source_disabled", 503);
146
207
  const target = getSource(c.source), family = input.id === "codex" ? "gpt" : "claude";
147
208
  const api = settings.apis.find(api => api.id === c.source);if (api?.key_env && !env[api.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
@@ -155,6 +216,13 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
155
216
  if (c.auto_review_effort !== undefined && c.auto_review_effort !== null && !efforts.includes(c.auto_review_effort)) throw accessError("ccdx_api_effort_unavailable");
156
217
  }
157
218
  }
219
+ if (input.operation === "preview_client") {
220
+ const proposed = compileClientModels({ client: input.id, binding: c, source: getSource, enabled, desktopEffortAliases: capabilitySupport.app });
221
+ const shared = input.id === "codex" ? null : claudeSharedCapabilityPlan({ app: input.id === "claude_app" ? proposed.models : plan("claude_app").models,
222
+ code: input.id === "claude_code" ? proposed.models : plan("claude_code").models, support: capabilitySupport });
223
+ return { ...snapshot(), preview: { models: proposed.models.map(model => ({ source: model.source_id, id: model.id, public_id: model.public_id, capability: model.capability })),
224
+ shared, current: input.id === "codex" ? null : inspectClaudeCapabilityConfiguration(proposed.models, options), saved: false } };
225
+ }
158
226
  save(next);
159
227
  } else if (input.operation === "provider") {
160
228
  if (typeof input.enabled !== "boolean" || !["github", "m365", ...next.apis.map(api => api.id)].includes(input.id)) throw accessError("ccdx_connections_action_invalid");
@@ -171,6 +239,19 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
171
239
  next.clients[id].history_isolation = true;
172
240
  }
173
241
  }
242
+ if (!input.enabled) for (const id of CLIENT_IDS) {
243
+ const c = next.clients[id];if (!Array.isArray(c.deployments)) continue;
244
+ const had = c.deployments.some(item => item.source === input.id);if (!had) continue;
245
+ c.deployments = c.deployments.filter(item => item.source !== input.id);
246
+ if (input.replacements && Object.hasOwn(input.replacements, id)) {
247
+ const replacement = input.replacements[id];
248
+ if (!replacement) c.deployments = [];
249
+ else if (!c.deployments.some(item => item.source === replacement)) {
250
+ const model = sourceModels(getSource(replacement), id)[0];if (model) c.deployments.push({ source: replacement, model: model.id });
251
+ }
252
+ c.default_model = c.deployments.find(item => item.source === replacement) ? deploymentModelId(replacement, c.deployments.find(item => item.source === replacement).model) : null;
253
+ }
254
+ }
174
255
  if (input.id.startsWith("api_")) next.apis.find(api => api.id === input.id).enabled = input.enabled;else next.providers[input.id] = input.enabled;
175
256
  save(next);
176
257
  if (input.id === "m365") {
@@ -181,7 +262,15 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
181
262
  }
182
263
  } else if (input.operation === "discover") {
183
264
  if (!settings.apis.some(api => api.id === input.id && api.enabled)) throw accessError("ccdx_client_source_disabled", 503);
184
- const models = await getSource(input.id).discover({ signal: AbortSignal.timeout(20000) });return { ...snapshot(), discovered: models };
265
+ try {
266
+ const models = await getSource(input.id).discover({ signal: AbortSignal.timeout(20000) });
267
+ const byId = new Map(models.map(model => [model.id, model]));
268
+ const config = next.apis.find(api => api.id === input.id);
269
+ for (const model of config.models) if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
270
+ config.checked_at = new Date().toISOString();save(next);
271
+ discoveries.set(input.id, { state: "ready", checked_at: config.checked_at });await syncClients();
272
+ return { ...snapshot(), discovered: models };
273
+ } catch (error) { discoveries.set(input.id, { state: "stale", code: error.code || "ccdx_api_catalog_unavailable", checked_at: new Date().toISOString() });throw error; }
185
274
  } else throw accessError("ccdx_connections_action_invalid");
186
275
  await syncClients();
187
276
  if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
@@ -197,7 +286,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
197
286
  async start() { const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();return result; },
198
287
  refresh() { return !managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(); },
199
288
  selection() { return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null }; },
200
- providerPreference(id) { return managed && settings.clients.codex.source === id && settings.clients.codex.auto_review_model ? settings.clients.codex : legacy.selection().m365; },
289
+ providerPreference(id) {
290
+ const c = settings.clients.codex;
291
+ return managed && c.source === id && c.auto_review_model ? { ...c, auto_review_model: plan("codex").routes.get(c.auto_review_model)?.upstreamModel || c.auto_review_model } : legacy.selection().m365;
292
+ },
201
293
  snapshot() {
202
294
  const result = legacy.snapshot();if (!managed) return result;
203
295
  const performance = legacy.claudePerformance.snapshot(), totals = performance.by_route.messages.terminal_outcomes.totals;
@@ -207,19 +299,43 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
207
299
  active_total: ms.active, active_requests: performance.active_requests.filter(row => row.provider === "m365"),
208
300
  recent_requests: performance.recent_requests.filter(row => row.provider === "m365") } } : null;
209
301
  return { ...result, codex_provider: this.selection().codex, connections: snapshot(true),
210
- m365: { ...result.m365, ...(binding("codex").source === "m365" ? { preference: settings.clients.codex } : {}), claude: { ...result.m365.claude, requests: m365Requests,
302
+ m365: { ...result.m365, ...(binding("codex").source === "m365" ? { preference: this.providerPreference(binding("codex").source) } : {}), claude: { ...result.m365.claude, requests: m365Requests,
211
303
  clients: Object.fromEntries([["app", "claude_app"], ["code", "claude_code"]].map(([short, id]) => [short, binding(id).enabled && binding(id).source === "m365" ? setup[id] || result.m365.claude.clients[short] : "not_selected"])) } },
212
304
  claude: { base_url: `http://127.0.0.1:${corePort}/anthropic`, gateway: CLIENT_IDS.some(id => id !== "codex" && binding(id).enabled && permitted(id, binding(id).source)) ? "running" : "unavailable",
213
305
  clients: { app: setup.claude_app || "not_configured", code: setup.claude_code || "not_configured" },
214
306
  requests: { ...totals, active: performance.active_total, total: Object.values(totals).reduce((sum, value) => sum + value, 0) + performance.active_total, performance } },
215
- ...Object.fromEntries(settings.apis.map(api => [api.id, { preference: settings.clients.codex }])) };
307
+ ...Object.fromEntries(settings.apis.map(api => [api.id, { preference: this.providerPreference(binding("codex").source) }])) };
216
308
  },
217
309
  current(req) {
218
310
  if (!managed) return legacy.current();
219
- const c = binding("codex"), source = requireSource("codex", c.source);
220
- if (source.id.startsWith("api_") && req && gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
311
+ const c = binding("codex"), compiled = plan("codex");
312
+ const source = requireSource("codex", Array.isArray(c.deployments) ? compiled.routes.get(compiled.defaultModel)?.source : c.source);
313
+ if (Array.isArray(c.deployments) && req?.method === "GET") {
314
+ if (gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
315
+ return { ...source, registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
316
+ client: { ...source.client, listModels: async () => ({ status: 200, body: JSON.stringify({ data: compiled.models.map(model => ({ ...model, id: model.public_id })) }) }) },
317
+ codexCatalog: codexClientCatalog(compiled, getSource) };
318
+ }
319
+ if (source?.id.startsWith("api_") && req && gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
221
320
  return source;
222
321
  },
322
+ hasModelBindings(client = "codex") { return managed && Array.isArray(binding(client).deployments); },
323
+ resolveCodex(body, req) {
324
+ if (!managed || !Array.isArray(binding("codex").deployments)) return null;
325
+ if (gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
326
+ const requested = body.model === "codex-auto-review" ? binding("codex").auto_review_model || plan("codex").defaultModel : body.model;
327
+ if (body.model === "codex-auto-review") {
328
+ delete body.service_tier;
329
+ if (binding("codex").auto_review_effort) body.reasoning = { ...body.reasoning, effort: binding("codex").auto_review_effort };
330
+ }
331
+ const record = resolveDeployment("codex", requested), context = currentRequestContext();
332
+ if (context) {
333
+ context.finishProvider?.();context.finishProvider = track(record.provider);context.provider = record.provider.id;
334
+ context.streamPerformance?.setProvider?.(record.provider.id);
335
+ Object.assign(context, this.historyContext(req.headers, record.provider));
336
+ }
337
+ body.model = record.upstreamModel;return record.provider;
338
+ },
223
339
  track,
224
340
  validateConversation,
225
341
  historyContext(headers, target) {
@@ -235,15 +351,24 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
235
351
  }
236
352
  const id = gatewayClient(req.headers, identities());
237
353
  if (!id || id === "codex") throw accessError("ccdx_client_credential_required", 401);
238
- const source = requireSource(id, binding(id).source);let byClient = handlers.get(source);
239
- if (!byClient) { byClient = new Map();handlers.set(source, byClient); }
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_"),
242
- validateConversation: (body, headers) => validateConversation(body, headers, source, id),
243
- onRequest() { lastClients[id] = new Date().toISOString(); } }));
244
- const finish = track(source), headers = req.headers;
245
- req.headers = { ...headers, "x-ccdx-client": id === "claude_app" ? "claude-app" : "claude-code" };
246
- try { return await byClient.get(id)(req, res); } finally { req.headers = headers;finish(); }
354
+ const compiled = plan(id);if (!binding(id).enabled || !compiled.models.length) throw accessError("ccdx_client_source_disabled", 503);
355
+ // A request resolves once after its bounded body read. Its source and
356
+ // capability snapshot stay pinned while catalogs/configuration change.
357
+ const catalog = { id: "connections", configuredModels: true, models: () => compiled.models };
358
+ let cached = handlers.get(id);
359
+ if (cached?.compiled !== compiled) {
360
+ const handler = createClaudeGatewayHandler({ provider: catalog, acquireRequest: acquireClaudeRequest, apiKey: identities()[id], env, log, performance: legacy.claudePerformance,
361
+ desktopAliases: id === "claude_app",
362
+ resolveRequest(body) {
363
+ const record = resolveDeployment(id, body.model), finish = track(record.provider);
364
+ return { provider: record.provider, model: record.upstreamModel, capability: record.model.capability, finish };
365
+ },
366
+ validateConversation: (body, headers, source) => validateConversation(body, headers, source, id),
367
+ onRequest() { lastClients[id] = new Date().toISOString(); } });
368
+ cached = { compiled, handler };handlers.set(id, cached);
369
+ }
370
+ const headers = req.headers;req.headers = { ...headers, "x-ccdx-client": id === "claude_app" ? "claude-app" : "claude-code" };
371
+ try { return await cached.handler(req, res); } finally { req.headers = headers; }
247
372
  },
248
373
  dashboardProviders() {
249
374
  const builtins = legacy.dashboardProviders();if (!managed) return builtins.filter(source => source.enabled);
@@ -251,8 +376,8 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
251
376
  return definitions.filter(item => item.enabled).map(item => {
252
377
  const old = builtins.find(source => source.id === item.id), source = item.builtin ? null : getSource(item.id);
253
378
  const clients = CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(item.id)
254
- && (id === "codex" ? item.protocols.includes("responses") : item.protocols.includes("messages"))).map(id => ({ id, name: CLIENT_NAMES[id], selected: binding(id).source === item.id,
255
- state: setup[id] || old?.clients?.find(client => client.id === id)?.state || "unknown", gateway: binding(id).source === item.id ? "running" : "standby", last_request_at: lastClients[id] || null }));
379
+ && (id === "codex" ? item.protocols.includes("responses") : item.protocols.includes("messages"))).map(id => ({ id, name: CLIENT_NAMES[id], selected: binding(id).deployments?.some(model => model.source === item.id) || binding(id).source === item.id,
380
+ state: setup[id] || old?.clients?.find(client => client.id === id)?.state || "unknown", gateway: binding(id).deployments?.some(model => model.source === item.id) || binding(id).source === item.id ? "running" : "standby", last_request_at: lastClients[id] || null }));
256
381
  return { ...old, id: item.id, name: item.name, enabled: true, generation: old?.generation || source?.registry.generation || 1,
257
382
  state: old?.state || "configured", auth: old?.auth || { state: "saved", token_cached: false },
258
383
  selection: { codex: clients.some(client => client.id === "codex"), models_required: item.id !== "github" }, clients,
@@ -267,6 +392,14 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
267
392
  return getSource(input.provider).publicCatalog(CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider)));
268
393
  },
269
394
  async action(input) {
395
+ if (managed && input.action === "auto-review" && Array.isArray(binding("codex").deployments)) {
396
+ const c = binding("codex"), compiled = plan("codex");
397
+ if (!c.enabled || input.provider !== c.source) throw accessError("ccdx_client_source_mismatch", 409);
398
+ const record = [...compiled.routes.values()].find(record => record.source === input.provider && record.upstreamModel === input.model);
399
+ if (!record) throw accessError("ccdx_api_model_unavailable");
400
+ if (input.effort && !record.model.capability.values.reasoning_efforts?.includes(input.effort)) throw accessError("ccdx_api_effort_unavailable");
401
+ const next = editable();next.clients.codex.auto_review_model = record.model.route_id;next.clients.codex.auto_review_effort = input.effort || null;save(next);return this.snapshot();
402
+ }
270
403
  if (managed && input.action === "auto-review" && input.provider && input.provider !== this.selection().codex) throw accessError("ccdx_client_source_mismatch", 409);
271
404
  if (managed && input.action === "auto-review" && (!binding("codex").enabled || !binding("codex").source)) throw accessError("ccdx_client_source_disabled", 503);
272
405
  if (managed && ["on", "off", "remove"].includes(input.action)) {
@@ -277,14 +410,15 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
277
410
  }
278
411
  if (managed && input.action === "switch" && !binding("codex").enabled) throw accessError("ccdx_client_source_disabled", 503);
279
412
  const { history_isolation, ...clientInput } = binding("codex");
280
- if (input.action === "switch" && input.provider?.startsWith("api_")) { await this.manageConnections({ operation: "client", id: "codex", ...clientInput, source: input.provider,
413
+ if (input.action === "switch" && input.provider?.startsWith("api_")) { await this.manageConnections({ operation: "client", id: "codex", ...clientInput, deployments: null, default_model: null, source: input.provider,
281
414
  model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort });return this.snapshot(); }
282
415
  if (input.action === "auto-review" && managed && binding("codex").source !== "github") { await this.manageConnections({ operation: "client", id: "codex", ...clientInput, auto_review_model: input.model, auto_review_effort: input.effort });return this.snapshot(); }
283
416
  if (input.action === "auto-review" && managed && legacy.selection().codex !== "github") await legacy.action({ action: "switch", provider: "github" });
417
+ if (managed && input.action === "switch" && !permitted("codex", input.provider)) throw accessError("ccdx_client_source_disabled", 503);
284
418
  const result = await legacy.action(input);
285
- if (managed && input.action === "switch") { const next = editable();if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;next.clients.codex.source = input.provider;if (input.provider === "m365") Object.assign(next.clients.codex, legacy.selection().m365);save(next);await syncClients(); }
419
+ if (managed && input.action === "switch") { const next = editable();if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;next.clients.codex.source = input.provider;next.clients.codex.deployments = null;next.clients.codex.default_model = null;for (const key of ["model", "auto_review_model", "auto_review_effort"]) delete next.clients.codex[key];if (input.provider === "m365") Object.assign(next.clients.codex, legacy.selection().m365);save(next);await syncClients(); }
286
420
  return result;
287
421
  },
288
- async close() { closed = true;await serial;for (const { source } of instances.values()) source.close();for (const source of retired) source.close();active.clear();for (const id of retiredSecrets.keys()) cleanSecrets(id);await Promise.allSettled([...cleanups]);secrets.close();await legacy.close(); },
422
+ async close() { closed = true;await serial;await syncFlight;for (const { source } of instances.values()) source.close();for (const source of retired) source.close();active.clear();for (const id of retiredSecrets.keys()) cleanSecrets(id);await Promise.allSettled([...cleanups]);secrets.close();await legacy.close(); },
289
423
  };
290
424
  }