codex-copilot-dx 1.2.33 → 1.3.0

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.
Files changed (42) hide show
  1. package/README.md +64 -110
  2. package/bin/cli.mjs +38 -102
  3. package/docs/ARCHITECTURE.md +23 -7
  4. package/docs/README.md +9 -76
  5. package/docs/REFERENCE.md +137 -1936
  6. package/package.json +11 -4
  7. package/src/access-settings.mjs +2 -2
  8. package/src/adapter.mjs +1 -1
  9. package/src/auth-credentials.mjs +1 -1
  10. package/src/auto-review-model.mjs +2 -2
  11. package/src/cli-animation.mjs +2 -2
  12. package/src/cli-auth.mjs +3 -3
  13. package/src/cli-cache.mjs +2 -2
  14. package/src/cli-command-spec.mjs +260 -58
  15. package/src/cli-image.mjs +2 -2
  16. package/src/cli-limits.mjs +2 -2
  17. package/src/cli-m365.mjs +1 -1
  18. package/src/cli-management.mjs +7 -3
  19. package/src/cli-options.mjs +71 -408
  20. package/src/connection-runtime.mjs +1408 -377
  21. package/src/copilot-token-session.mjs +1 -1
  22. package/src/dashboard/connections.js +23 -4
  23. package/src/dashboard/ui.css +9 -2
  24. package/src/dashboard-api.mjs +5 -5
  25. package/src/doctor.mjs +4 -4
  26. package/src/image-mcp.mjs +2 -2
  27. package/src/native-prediction-fix.mjs +1 -1
  28. package/src/native-prediction-profile.mjs +1 -1
  29. package/src/native-prediction-windows.mjs +1 -1
  30. package/src/native-prediction.mjs +6 -6
  31. package/src/nightly-update.mjs +2 -2
  32. package/src/provider-runtime.mjs +1 -1
  33. package/src/providers/m365-accounts.mjs +1 -1
  34. package/src/release-install.mjs +11 -15
  35. package/src/startup-ui.mjs +15 -11
  36. package/src/terminal-console.mjs +5 -4
  37. package/src/terminal-state.mjs +1 -1
  38. package/src/usage.mjs +5 -5
  39. package/src/windows-command.mjs +2 -2
  40. package/bin/codex-copilot-dx.mjs +0 -11
  41. package/src/cli-models.mjs +0 -94
  42. package/src/legacy-command-warning.mjs +0 -38
@@ -1,6 +1,15 @@
1
1
  import fs from "node:fs";
2
2
  import { randomBytes, createHash } from "node:crypto";
3
- import { accessSettingsPath, readAccessSettings, updateAccessSettings, checkedApi, checkedAccessSettings, accessError, CLIENT_IDS, CLIENT_NAMES } from "./access-settings.mjs";
3
+ import {
4
+ accessSettingsPath,
5
+ readAccessSettings,
6
+ updateAccessSettings,
7
+ checkedApi,
8
+ checkedAccessSettings,
9
+ accessError,
10
+ CLIENT_IDS,
11
+ CLIENT_NAMES,
12
+ } from "./access-settings.mjs";
4
13
  import { createApiSecretStore, checkedApiKey } from "./api-secrets.mjs";
5
14
  import { publicModelCatalog } from "./provider-metadata.mjs";
6
15
  import { createApiCatalogRefresh } from "./api-catalog-refresh.mjs";
@@ -9,7 +18,11 @@ import { createApiModelDisplayStore } from "./api-model-display.mjs";
9
18
  import { createCodexMemoryModel } from "./codex-memory-model.mjs";
10
19
  import { readClientGatewayKeys, gatewayClient } from "./client-gateway-keys.mjs";
11
20
  import { createClaudeGatewayHandler } from "./claude-gateway.mjs";
12
- import { configureClaudeClients, restoreClaudeClients, inspectClaudeDesktopPolicy } from "./claude-client-config.mjs";
21
+ import {
22
+ configureClaudeClients,
23
+ restoreClaudeClients,
24
+ inspectClaudeDesktopPolicy,
25
+ } from "./claude-client-config.mjs";
13
26
  import { configureCodexApi } from "./codex-api-config.mjs";
14
27
  import { autoReviewReasoningEfforts } from "./models.mjs";
15
28
  import { createRequestAdmission } from "./request-admission.mjs";
@@ -18,43 +31,121 @@ import { createMessagesHistoryTransfer } from "./messages-history-transfer.mjs";
18
31
  import { compileClientModels, sourceModels } from "./client-model-plan.mjs";
19
32
  import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.mjs";
20
33
  import { currentRequestContext } from "./request-context.mjs";
21
- import { claudeSharedCapabilityPlan, syncClaudeCapabilities, inspectClaudeCapabilitySupport, inspectClaudeCapabilityConfiguration } from "./claude-capability-config.mjs";
34
+ import {
35
+ claudeSharedCapabilityPlan,
36
+ syncClaudeCapabilities,
37
+ inspectClaudeCapabilitySupport,
38
+ inspectClaudeCapabilityConfiguration,
39
+ } from "./claude-capability-config.mjs";
22
40
  import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from "./model-capabilities.mjs";
23
41
  import { m365Paths } from "./m365-settings.mjs";
24
42
 
25
- const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
26
- export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
27
- secretStore, createApi = createApiProvider, configureClaude = configureClaudeClients, restoreClaude = restoreClaudeClients,
28
- configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, preserveClientConfiguration, now = Date.now, log = () => {} } = {}) {
29
- const options = { home, env, platform, preserveClientConfiguration }, secrets = secretStore || createApiSecretStore(options), modelDisplay = createApiModelDisplayStore(options);
30
- const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
31
- const messagesTransfer = createMessagesHistoryTransfer({ ...options, onTransfer: () => log("info", "Conversation continued on the selected source; original history kept") });
43
+ const validObject = (value, keys) =>
44
+ value &&
45
+ typeof value === "object" &&
46
+ !Array.isArray(value) &&
47
+ Object.keys(value).every(key => keys.includes(key));
48
+ export function createConnectionRuntime({
49
+ legacy,
50
+ home,
51
+ env = process.env,
52
+ platform = process.platform,
53
+ corePort = 2026,
54
+ secretStore,
55
+ createApi = createApiProvider,
56
+ configureClaude = configureClaudeClients,
57
+ restoreClaude = restoreClaudeClients,
58
+ configureCodex = configureCodexApi,
59
+ inspectDesktop = inspectClaudeDesktopPolicy,
60
+ clientAccessChanged,
61
+ preserveClientConfiguration,
62
+ now = Date.now,
63
+ log = () => {},
64
+ } = {}) {
65
+ const options = { home, env, platform, preserveClientConfiguration },
66
+ secrets = secretStore || createApiSecretStore(options),
67
+ modelDisplay = createApiModelDisplayStore(options);
68
+ const guardConversation = createConversationSourceGuard(options),
69
+ acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
70
+ const messagesTransfer = createMessagesHistoryTransfer({
71
+ ...options,
72
+ onTransfer: () => log("info", "Conversation continued on the selected source; original history kept"),
73
+ });
32
74
  const memoryModel = createCodexMemoryModel({ ...options, corePort });
33
- let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
75
+ let settings = readAccessSettings(options),
76
+ managed = fs.existsSync(accessSettingsPath(options)),
77
+ serial = Promise.resolve(),
78
+ keys,
79
+ closed = false;
34
80
  const legacyClaudeAccess = fs.existsSync(m365Paths(options).ownership);
35
- const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
36
- const retiredSecrets = new Map(), cleanups = new Set(), plans = new Map(), discoveries = new Map();
37
- const catalogRefresh = createApiCatalogRefresh({ config: id => settings.apis.find(api => api.id === id), source: getSource, track,
81
+ const instances = new Map(),
82
+ active = new Map(),
83
+ retired = new Set(),
84
+ handlers = new Map(),
85
+ summaries = new WeakMap(),
86
+ sourceSecrets = new WeakMap(),
87
+ setup = {},
88
+ lastClients = {};
89
+ const retiredSecrets = new Map(),
90
+ cleanups = new Set(),
91
+ plans = new Map(),
92
+ discoveries = new Map();
93
+ const catalogRefresh = createApiCatalogRefresh({
94
+ config: id => settings.apis.find(api => api.id === id),
95
+ source: getSource,
96
+ track,
38
97
  complete: api => modelDisplay.has(api.id, deploymentRevision(api, env)),
39
- revision: api => deploymentRevision(api, env), now,
98
+ revision: api => deploymentRevision(api, env),
99
+ now,
40
100
  commit: (...args) => enqueue(() => applyCatalog(...args)),
41
- onState: (id, state) => state ? discoveries.set(id, state) : discoveries.delete(id) });
101
+ onState: (id, state) => (state ? discoveries.set(id, state) : discoveries.delete(id)),
102
+ });
42
103
  const capabilitySupport = inspectClaudeCapabilitySupport(options);
43
- let sharedSync = null, syncFlight = null, syncAgain = false, operations = 0;const syncTargets = new Set(), manualTargets = new Set();
104
+ let sharedSync = null,
105
+ syncFlight = null,
106
+ syncAgain = false,
107
+ operations = 0;
108
+ const syncTargets = new Set(),
109
+ manualTargets = new Set();
44
110
  function cleanSecrets(id) {
45
- const refs = retiredSecrets.get(id);if (!refs) return;
111
+ const refs = retiredSecrets.get(id);
112
+ if (!refs) return;
46
113
  for (const ref of refs) {
47
114
  if ([...active.keys()].some(source => sourceSecrets.get(source) === ref)) continue;
48
115
  refs.delete(ref);
49
- const task = secrets.remove(ref).catch(() => { log("warn", "Previous API credential cleanup needs review"); }).finally(() => cleanups.delete(task));cleanups.add(task);
116
+ const task = secrets
117
+ .remove(ref)
118
+ .catch(() => {
119
+ log("warn", "Previous API credential cleanup needs review");
120
+ })
121
+ .finally(() => cleanups.delete(task));
122
+ cleanups.add(task);
50
123
  }
51
124
  if (!refs.size) retiredSecrets.delete(id);
52
125
  }
53
- const identities = () => keys ||= readClientGatewayKeys(options);
54
- const enabled = id => id?.startsWith("api_") ? settings.apis.find(api => api.id === id)?.enabled === true : settings.providers[id] === true;
55
- const binding = id => managed ? settings.clients[id] : { ...settings.clients[id],
56
- allowed: settings.clients[id].allowed.filter(source => source !== "m365" || legacyClaudeAccess || id === "codex" && legacy.selection().codex === "m365"),
57
- source: id === "codex" ? legacy.selection().codex : legacyClaudeAccess && legacy.snapshot().m365.enabled ? "m365" : null };
126
+ const identities = () => (keys ||= readClientGatewayKeys(options));
127
+ const enabled = id =>
128
+ id?.startsWith("api_")
129
+ ? settings.apis.find(api => api.id === id)?.enabled === true
130
+ : settings.providers[id] === true;
131
+ const binding = id =>
132
+ managed
133
+ ? settings.clients[id]
134
+ : {
135
+ ...settings.clients[id],
136
+ allowed: settings.clients[id].allowed.filter(
137
+ source =>
138
+ source !== "m365" ||
139
+ legacyClaudeAccess ||
140
+ (id === "codex" && legacy.selection().codex === "m365")
141
+ ),
142
+ source:
143
+ id === "codex"
144
+ ? legacy.selection().codex
145
+ : legacyClaudeAccess && legacy.snapshot().m365.enabled
146
+ ? "m365"
147
+ : null,
148
+ };
58
149
  // GitHub-only selections retain the existing native loopback access contract.
59
150
  // Any other deployment still requires the private per-client credential.
60
151
  function codexAccessMode() {
@@ -73,433 +164,1215 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
73
164
  // denial must not trigger recovery/replacement of that unrelated sign-in.
74
165
  throw accessError("ccdx_client_credential_required", req.headers?.authorization ? 403 : 401);
75
166
  }
76
- const permitted = (id, source) => binding(id)?.enabled && binding(id).allowed.includes(source) && enabled(source);
167
+ const permitted = (id, source) =>
168
+ binding(id)?.enabled && binding(id).allowed.includes(source) && enabled(source);
77
169
  function getSource(id) {
78
170
  if (!id?.startsWith("api_")) return legacy.source(id);
79
- const config = settings.apis.find(value => value.id === id);if (!config) return null;
80
- const previous = instances.get(id), revision = deploymentRevision(config, env);if (previous?.config === config && previous.revision === revision) return previous.source;
171
+ const config = settings.apis.find(value => value.id === id);
172
+ if (!config) return null;
173
+ const previous = instances.get(id),
174
+ revision = deploymentRevision(config, env);
175
+ if (previous?.config === config && previous.revision === revision) return previous.source;
81
176
  const signature = JSON.stringify(config) + revision;
82
177
  if (previous?.signature === signature) return previous.source;
83
- const source = createApi({ config, secrets, env: { ...env }, platform, modelDisplay: model => modelDisplay.get(id, revision, model) });instances.set(id, { signature, source, config, revision });sourceSecrets.set(source, config.secret_ref);
84
- if (previous) retire(previous.source);return source;
178
+ const source = createApi({
179
+ config,
180
+ secrets,
181
+ env: { ...env },
182
+ platform,
183
+ modelDisplay: model => modelDisplay.get(id, revision, model),
184
+ });
185
+ instances.set(id, { signature, source, config, revision });
186
+ sourceSecrets.set(source, config.secret_ref);
187
+ if (previous) retire(previous.source);
188
+ return source;
85
189
  }
86
190
  function plan(id) {
87
- const selected = binding(id), definitions = selected.allowed.filter(enabled).map(source => getSource(source)).filter(Boolean);
88
- const cached = plans.get(id), stamps = definitions.map(source => [source, source.registry?.generation, source.registry?.models, source.profileId()]);
89
- 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;
90
- const value = compileClientModels({ client: id, binding: selected, source: getSource, enabled,
91
- names: Object.fromEntries([["github", "GitHub Copilot"], ["m365", "Microsoft 365"], ...settings.apis.map(api => [api.id, api.name])]),
92
- desktopEffortAliases: capabilitySupport.app });
93
- plans.set(id, { binding: selected, stamps, value });return value;
191
+ const selected = binding(id),
192
+ definitions = selected.allowed
193
+ .filter(enabled)
194
+ .map(source => getSource(source))
195
+ .filter(Boolean);
196
+ const cached = plans.get(id),
197
+ stamps = definitions.map(source => [
198
+ source,
199
+ source.registry?.generation,
200
+ source.registry?.models,
201
+ source.profileId(),
202
+ ]);
203
+ if (
204
+ cached?.binding === selected &&
205
+ cached.stamps.length === stamps.length &&
206
+ stamps.every((stamp, index) => stamp.every((value, at) => cached.stamps[index][at] === value))
207
+ )
208
+ return cached.value;
209
+ const value = compileClientModels({
210
+ client: id,
211
+ binding: selected,
212
+ source: getSource,
213
+ enabled,
214
+ names: Object.fromEntries([
215
+ ["github", "GitHub Copilot"],
216
+ ["m365", "Microsoft 365"],
217
+ ...settings.apis.map(api => [api.id, api.name]),
218
+ ]),
219
+ desktopEffortAliases: capabilitySupport.app,
220
+ });
221
+ plans.set(id, { binding: selected, stamps, value });
222
+ return value;
94
223
  }
95
224
  function resolveDeployment(id, model) {
96
- const value = plan(id), record = value.routes.get(model);
225
+ const value = plan(id),
226
+ record = value.routes.get(model);
97
227
  if (!record) {
98
- const selected = binding(id), configured = selected.deployments || [{ source: selected.source, model: selected.model }];
99
- const matches = configured.filter(item => item.model === model || deploymentModelId(item.source, item.model) === model);
100
- const reason = !selected.enabled ? "ccdx_client_source_disabled" : matches.length > 1 ? "ccdx_model_ambiguous"
101
- : matches.length && !permitted(id, matches[0].source) ? "ccdx_client_source_disabled"
102
- : matches.length ? "ccdx_model_catalog_unavailable" : "ccdx_model_not_selected";
103
- const error = accessError("ccdx_api_model_unavailable");error.jsonBody.error.reason = reason;
104
- currentRequestContext()?.onHttpError?.({ code: error.code, origin: "client_validation", reason });throw error;
228
+ const selected = binding(id),
229
+ configured = selected.deployments || [{ source: selected.source, model: selected.model }];
230
+ const matches = configured.filter(
231
+ item => item.model === model || deploymentModelId(item.source, item.model) === model
232
+ );
233
+ const reason = !selected.enabled
234
+ ? "ccdx_client_source_disabled"
235
+ : matches.length > 1
236
+ ? "ccdx_model_ambiguous"
237
+ : matches.length && !permitted(id, matches[0].source)
238
+ ? "ccdx_client_source_disabled"
239
+ : matches.length
240
+ ? "ccdx_model_catalog_unavailable"
241
+ : "ccdx_model_not_selected";
242
+ const error = accessError("ccdx_api_model_unavailable");
243
+ error.jsonBody.error.reason = reason;
244
+ currentRequestContext()?.onHttpError?.({ code: error.code, origin: "client_validation", reason });
245
+ throw error;
105
246
  }
106
247
  const provider = requireSource(id, record.source);
107
- if (provider !== record.provider) { plans.delete(id);return resolveDeployment(id, model); }
248
+ if (provider !== record.provider) {
249
+ plans.delete(id);
250
+ return resolveDeployment(id, model);
251
+ }
108
252
  return record;
109
253
  }
110
- function retire(source) { if (active.get(source)) retired.add(source);else source.close(); }
254
+ function retire(source) {
255
+ if (active.get(source)) retired.add(source);
256
+ else source.close();
257
+ }
111
258
  function track(source) {
112
- const finishLegacy = legacy.track(source);active.set(source, (active.get(source) || 0) + 1);let done = false;
259
+ const finishLegacy = legacy.track(source);
260
+ active.set(source, (active.get(source) || 0) + 1);
261
+ let done = false;
113
262
  return () => {
114
- if (done) return;done = true;finishLegacy?.();const count = (active.get(source) || 1) - 1;
115
- if (count) active.set(source, count);else { active.delete(source);if (retired.delete(source)) source.close();cleanSecrets(source.id); }
263
+ if (done) return;
264
+ done = true;
265
+ finishLegacy?.();
266
+ const count = (active.get(source) || 1) - 1;
267
+ if (count) active.set(source, count);
268
+ else {
269
+ active.delete(source);
270
+ if (retired.delete(source)) source.close();
271
+ cleanSecrets(source.id);
272
+ }
116
273
  };
117
274
  }
118
275
  function editable() {
119
276
  if (managed) return structuredClone(settings);
120
- const next = structuredClone(settings);next.providers.m365 = legacy.snapshot().m365.enabled === true;
277
+ const next = structuredClone(settings);
278
+ next.providers.m365 = legacy.snapshot().m365.enabled === true;
121
279
  for (const id of CLIENT_IDS) next.clients[id] = { ...binding(id) };
122
280
  return next;
123
281
  }
124
282
  function save(next) {
125
283
  plans.clear();
126
- settings = structuredClone(updateAccessSettings(current => {
127
- if (JSON.stringify(current) !== JSON.stringify(settings)) throw accessError("ccdx_connections_conflict", 409);return next;
128
- }, options));managed = true;catalogRefresh.invalidate();
284
+ settings = structuredClone(
285
+ updateAccessSettings(current => {
286
+ if (JSON.stringify(current) !== JSON.stringify(settings))
287
+ throw accessError("ccdx_connections_conflict", 409);
288
+ return next;
289
+ }, options)
290
+ );
291
+ managed = true;
292
+ catalogRefresh.invalidate();
129
293
  for (const [id, item] of instances) {
130
294
  const current = settings.apis.find(api => api.id === id);
131
- if (!current?.enabled || JSON.stringify(current) + deploymentRevision(current, env) !== item.signature) { instances.delete(id);retire(item.source); }else item.config = current;
295
+ if (
296
+ !current?.enabled ||
297
+ JSON.stringify(current) + deploymentRevision(current, env) !== item.signature
298
+ ) {
299
+ instances.delete(id);
300
+ retire(item.source);
301
+ } else item.config = current;
132
302
  }
133
303
  }
134
304
  function summary(api) {
135
- if (!summaries.has(api)) summaries.set(api, { model_count: api.models.length, codex_model_count: api.models.filter(model => model.protocols.includes("responses")).length, protocols: Object.keys(api.endpoints) });
305
+ if (!summaries.has(api))
306
+ summaries.set(api, {
307
+ model_count: api.models.length,
308
+ codex_model_count: api.models.filter(model => model.protocols.includes("responses")).length,
309
+ protocols: Object.keys(api.endpoints),
310
+ });
136
311
  return summaries.get(api);
137
312
  }
138
- function snapshot(compact = false) {
139
- const state = legacy.snapshot(), config = managed ? settings : editable();
140
- return structuredClone({ source: "connections", providers: [
141
- { id: "github", name: "GitHub Copilot", enabled: config.providers.github, builtin: true, protocols: ["responses"] },
142
- { id: "m365", name: "Microsoft 365", enabled: config.providers.m365, builtin: true, protocols: ["messages", "responses"] },
143
- ...config.apis.map(api => { const { secret_ref, ...publicApi } = api, revision = compact ? null : deploymentRevision(api, env);return { ...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
144
- ...summary(api), ...(compact ? {} : { deployment_revision: revision,
145
- model_display: Object.fromEntries(api.models.map(model => [model.id, modelDisplay.get(api.id, revision, model.id)])) }), discovery: discoveries.get(api.id) || null, builtin: false, key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref) }; }),
146
- ], clients: CLIENT_IDS.map(id => ({ id, name: CLIENT_NAMES[id], ...config.clients[id], setup: setup[id] || null,
313
+ function clientSnapshot(id, config, compact, readPlan) {
314
+ const base = {
315
+ id,
316
+ name: CLIENT_NAMES[id],
317
+ ...config.clients[id],
318
+ setup: setup[id] || null,
147
319
  ...(id === "codex" ? { memory_model: memoryModel.snapshot() } : {}),
148
- observed_at: lastClients[id] || null, ...(compact ? {} : { revision: clientRevision(id), model_plan: { default_model: plan(id).defaultModel, default_unavailable: plan(id).defaultUnavailable,
149
- models: plan(id).models.map(model => ({ source: model.source_id, id: model.id, display_name: model.display_name, public_id: model.public_id, route_id: model.route_id, capability: model.capability })),
150
- unavailable: (config.clients[id].deployments || []).filter(item => !plan(id).models.some(model => model.source_id === item.source && model.id === item.model))
151
- .map(item => ({ source: item.source, id: item.model, route_id: deploymentModelId(item.source, item.model) })),
152
- available: config.clients[id].allowed.filter(enabled).flatMap(source => sourceModels(getSource(source), id).map(model => ({ source, id: model.id,
153
- display_name: model.display_name || model.name || model.id, route_id: deploymentModelId(source, model.id), capability: model.capability || resolveModelCapabilities(model, { builtin: true }) }))), sync: sharedSync, support: capabilitySupport } }) })),
154
- ...(!compact ? { source_impacts: Object.fromEntries(["github", "m365", ...config.apis.map(api => api.id)].map(id => [id, sourceImpact(id)])) } : {}), managed, ...(!compact ? { management_version: 1 } : {}), m365_state: state.m365.state });
320
+ observed_at: lastClients[id] || null,
321
+ };
322
+ if (compact) return base;
323
+ const revision = clientRevision(id),
324
+ compiled = readPlan(id);
325
+ return {
326
+ ...base,
327
+ revision,
328
+ model_plan: {
329
+ default_model: compiled.defaultModel,
330
+ default_unavailable: compiled.defaultUnavailable,
331
+ models: compiled.models.map(model => ({
332
+ source: model.source_id,
333
+ id: model.id,
334
+ display_name: model.display_name,
335
+ public_id: model.public_id,
336
+ route_id: model.route_id,
337
+ capability: model.capability,
338
+ })),
339
+ unavailable: (config.clients[id].deployments || [])
340
+ .filter(
341
+ item => !compiled.models.some(model => model.source_id === item.source && model.id === item.model)
342
+ )
343
+ .map(item => ({
344
+ source: item.source,
345
+ id: item.model,
346
+ route_id: deploymentModelId(item.source, item.model),
347
+ })),
348
+ available: config.clients[id].allowed
349
+ .filter(enabled)
350
+ .flatMap(source =>
351
+ sourceModels(getSource(source), id).map(model => ({
352
+ source,
353
+ id: model.id,
354
+ display_name: model.display_name || model.name || model.id,
355
+ route_id: deploymentModelId(source, model.id),
356
+ capability: model.capability || resolveModelCapabilities(model, { builtin: true }),
357
+ }))
358
+ ),
359
+ sync: sharedSync,
360
+ support: capabilitySupport,
361
+ },
362
+ };
363
+ }
364
+ function snapshot(compact = false) {
365
+ const state = legacy.snapshot(),
366
+ config = managed ? settings : editable();
367
+ const localPlans = new Map();
368
+ const readPlan = id => {
369
+ if (!localPlans.has(id)) localPlans.set(id, plan(id));
370
+ return localPlans.get(id);
371
+ };
372
+ return structuredClone({
373
+ source: "connections",
374
+ providers: [
375
+ {
376
+ id: "github",
377
+ name: "GitHub Copilot",
378
+ enabled: config.providers.github,
379
+ builtin: true,
380
+ protocols: ["responses"],
381
+ },
382
+ {
383
+ id: "m365",
384
+ name: "Microsoft 365",
385
+ enabled: config.providers.m365,
386
+ builtin: true,
387
+ protocols: ["messages", "responses"],
388
+ },
389
+ ...config.apis.map(api => {
390
+ const { secret_ref, ...publicApi } = api,
391
+ revision = compact ? null : deploymentRevision(api, env);
392
+ return {
393
+ ...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
394
+ ...summary(api),
395
+ ...(compact
396
+ ? {}
397
+ : {
398
+ deployment_revision: revision,
399
+ model_display: Object.fromEntries(
400
+ api.models.map(model => [model.id, modelDisplay.get(api.id, revision, model.id)])
401
+ ),
402
+ }),
403
+ discovery: discoveries.get(api.id) || null,
404
+ builtin: false,
405
+ key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref),
406
+ };
407
+ }),
408
+ ],
409
+ clients: CLIENT_IDS.map(id => clientSnapshot(id, config, compact, readPlan)),
410
+ ...(!compact
411
+ ? {
412
+ source_impacts: Object.fromEntries(
413
+ ["github", "m365", ...config.apis.map(api => api.id)].map(id => [
414
+ id,
415
+ sourceImpact(id, readPlan),
416
+ ])
417
+ ),
418
+ }
419
+ : {}),
420
+ managed,
421
+ ...(!compact ? { management_version: 1 } : {}),
422
+ m365_state: state.m365.state,
423
+ });
155
424
  }
156
- const clientRevision = id => createHash("sha256").update(JSON.stringify(binding(id))).digest("hex");
157
- function sourceImpact(source) {
425
+ const clientRevision = id =>
426
+ createHash("sha256")
427
+ .update(JSON.stringify(binding(id)))
428
+ .digest("hex");
429
+ function sourceImpact(source, readPlan = plan) {
158
430
  const clients = CLIENT_IDS.flatMap(id => {
159
- const c = binding(id);if (!c.enabled) return [];
160
- const explicit = Array.isArray(c.deployments), removed = explicit ? c.deployments.filter(item => item.source === source) : [];
431
+ const c = binding(id);
432
+ if (!c.enabled) return [];
433
+ const explicit = Array.isArray(c.deployments),
434
+ removed = explicit ? c.deployments.filter(item => item.source === source) : [];
161
435
  if (explicit ? !removed.length : c.source !== source) return [];
162
436
  const remaining = explicit ? c.deployments.length - removed.length : 0;
163
- const defaultSource = plan(id).routes.get(c.default_model)?.source || removed.find(item => deploymentModelId(source, item.model) === c.default_model)?.source || c.source;
437
+ const defaultSource =
438
+ readPlan(id).routes.get(c.default_model)?.source ||
439
+ removed.find(item => deploymentModelId(source, item.model) === c.default_model)?.source ||
440
+ c.source;
164
441
  const default_affected = defaultSource === source;
165
- return [{ id, removed: explicit ? removed.length : sourceModels(getSource(source), id).length, remaining, default_affected, needs_replacement: default_affected || remaining === 0 }];
442
+ return [
443
+ {
444
+ id,
445
+ removed: explicit ? removed.length : sourceModels(getSource(source), id).length,
446
+ remaining,
447
+ default_affected,
448
+ needs_replacement: default_affected || remaining === 0,
449
+ },
450
+ ];
166
451
  });
167
- const api = settings.apis.find(item => item.id === source), profile = api ? deploymentRevision(api, env) : getSource(source)?.profileId();
168
- return { clients, revision: createHash("sha256").update(JSON.stringify([source, enabled(source), profile, CLIENT_IDS.map(id => binding(id))])).digest("hex") };
452
+ const api = settings.apis.find(item => item.id === source),
453
+ profile = api ? deploymentRevision(api, env) : getSource(source)?.profileId();
454
+ return {
455
+ clients,
456
+ revision: createHash("sha256")
457
+ .update(JSON.stringify([source, enabled(source), profile, CLIENT_IDS.map(id => binding(id))]))
458
+ .digest("hex"),
459
+ };
169
460
  }
170
461
  async function syncClients(ids = CLIENT_IDS, { manual = false } = {}) {
171
462
  if (!ids.length) return;
172
- for (const id of ids) { syncTargets.add(id);if (manual) manualTargets.add(id); }
173
- syncAgain = true;if (syncFlight) return syncFlight;
174
- syncFlight = (async () => { do { syncAgain = false;const targets = new Set(syncTargets);syncTargets.clear();const requested = new Set(manualTargets);manualTargets.clear();await performClientSync(targets, requested); } while (syncAgain && !closed); })();
175
- try { return await syncFlight; } finally { syncFlight = null; }
463
+ for (const id of ids) {
464
+ syncTargets.add(id);
465
+ if (manual) manualTargets.add(id);
466
+ }
467
+ syncAgain = true;
468
+ if (syncFlight) return syncFlight;
469
+ syncFlight = (async () => {
470
+ do {
471
+ syncAgain = false;
472
+ const targets = new Set(syncTargets);
473
+ syncTargets.clear();
474
+ const requested = new Set(manualTargets);
475
+ manualTargets.clear();
476
+ await performClientSync(targets, requested);
477
+ } while (syncAgain && !closed);
478
+ })();
479
+ try {
480
+ return await syncFlight;
481
+ } finally {
482
+ syncFlight = null;
483
+ }
176
484
  }
177
- async function performClientSync(targets, requested = new Set()) {
178
- if (!managed || closed) return;
179
- if (options.preserveClientConfiguration?.()) { for (const id of targets) setup[id] = "preserved";return; }
180
- const codex = binding("codex"), compiledCodex = plan("codex");
181
- const explicit = Array.isArray(codex.deployments), mode = codexAccessMode(), native = mode === "native";
182
- if (targets.has("codex")) try {
485
+ function syncCodexClient(codex, compiledCodex, requested, mode) {
486
+ const explicit = Array.isArray(codex.deployments),
487
+ native = mode === "native";
488
+ try {
183
489
  if (mode === "paused" || mode === "disabled") {
184
- if (mode === "disabled" || (codex.auto_sync !== false || requested.has("codex"))) configureCodex({ ...options, restore: true });
490
+ if (mode === "disabled" || codex.auto_sync !== false || requested.has("codex"))
491
+ configureCodex({ ...options, restore: true });
185
492
  setup.codex = mode;
186
493
  } else if (codex.auto_sync === false && !requested.has("codex")) setup.codex = "manual_sync";
187
- else if (codex.enabled && compiledCodex.defaultUnavailable && !native) setup.codex = "default_unavailable";
494
+ else if (codex.enabled && compiledCodex.defaultUnavailable && !native)
495
+ setup.codex = "default_unavailable";
188
496
  else {
189
- setup.codex = configureCodex({ ...options, ...(codex.enabled && (native || explicit && codex.deployments.length || codex.source?.startsWith("api_"))
190
- ? { baseUrl: `http://127.0.0.1:${corePort}/v1`, native, ...(native ? { nativeModels: compiledCodex.models } : {}), ...(!native ? { apiKey: identities().codex } : {}),
191
- ...(explicit || !native ? { model: compiledCodex.defaultModel || (!compiledCodex.defaultUnavailable ? codex.model : undefined) } : {}) } : { restore: true }) }).state;
192
- if (codex.enabled && compiledCodex.defaultUnavailable && setup.codex === "configured") setup.codex = "default_unavailable";
497
+ setup.codex = configureCodex({
498
+ ...options,
499
+ ...(codex.enabled &&
500
+ (native || (explicit && codex.deployments.length) || codex.source?.startsWith("api_"))
501
+ ? {
502
+ baseUrl: `http://127.0.0.1:${corePort}/v1`,
503
+ native,
504
+ ...(native ? { nativeModels: compiledCodex.models } : {}),
505
+ ...(!native ? { apiKey: identities().codex } : {}),
506
+ ...(explicit || !native
507
+ ? {
508
+ model:
509
+ compiledCodex.defaultModel ||
510
+ (!compiledCodex.defaultUnavailable ? codex.model : undefined),
511
+ }
512
+ : {}),
513
+ }
514
+ : { restore: true }),
515
+ }).state;
516
+ if (codex.enabled && compiledCodex.defaultUnavailable && setup.codex === "configured")
517
+ setup.codex = "default_unavailable";
193
518
  }
194
- } catch { setup.codex = "configuration_unavailable"; }
195
- if (!settings.claude_private_keys || !["claude_app", "claude_code"].some(id => targets.has(id))) return;
196
- let desktopManaged;
197
- for (const id of ["claude_app", "claude_code"]) {
198
- if (!targets.has(id)) continue;
199
- const selected = binding(id), compiled = plan(id), source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
200
- try {
201
- if (selected.enabled && compiled.defaultUnavailable) { setup[id] = "default_unavailable";continue; }
202
- if (!selected.enabled || !compiled.models.length) { const result = restoreClaude({ ...options, client: id });setup[id] = result.preserved ? "preserved" : "not_configured";continue; }
203
- if (selected.auto_sync === false && !requested.has(id)) { setup[id] = "manual_sync";continue; }
204
- if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
205
- const m365Only = compiled.models.every(model => model.source_id === "m365");
206
- if (id === "claude_code" && !m365Only) restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
207
- const result = configureClaude({ ...options, client: id, profileName: "CCDX", desktopAliases: id === "claude_app" && source?.id.startsWith("api_"), disableExperimentalBetas: m365Only, desktopManaged: id === "claude_app" ? desktopManaged : false,
208
- baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: identities()[id], models: compiled.models, defaultModel: Array.isArray(selected.deployments) ? compiled.defaultModel : undefined });
209
- setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
210
- } catch { setup[id] = "configuration_unavailable"; }
519
+ } catch {
520
+ setup.codex = "configuration_unavailable";
521
+ }
522
+ }
523
+ function prepareClaudeSync(id, requested) {
524
+ const selected = binding(id),
525
+ compiled = plan(id);
526
+ const source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
527
+ try {
528
+ if (selected.enabled && compiled.defaultUnavailable) {
529
+ setup[id] = "default_unavailable";
530
+ return null;
531
+ }
532
+ if (!selected.enabled || !compiled.models.length) {
533
+ const result = restoreClaude({ ...options, client: id });
534
+ setup[id] = result.preserved ? "preserved" : "not_configured";
535
+ return null;
536
+ }
537
+ if (selected.auto_sync === false && !requested.has(id)) {
538
+ setup[id] = "manual_sync";
539
+ return null;
540
+ }
541
+ return { selected, compiled, source };
542
+ } catch {
543
+ setup[id] = "configuration_unavailable";
544
+ return null;
211
545
  }
546
+ }
547
+ function writeClaudeSync(id, { selected, compiled, source }, desktopManaged) {
548
+ const m365Only = compiled.models.every(model => model.source_id === "m365");
549
+ if (id === "claude_code" && !m365Only)
550
+ restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
551
+ const result = configureClaude({
552
+ ...options,
553
+ client: id,
554
+ profileName: "CCDX",
555
+ desktopAliases: id === "claude_app" && source?.id.startsWith("api_"),
556
+ disableExperimentalBetas: m365Only,
557
+ desktopManaged: id === "claude_app" ? desktopManaged : false,
558
+ baseUrl: `http://127.0.0.1:${corePort}/anthropic`,
559
+ apiKey: identities()[id],
560
+ models: compiled.models,
561
+ defaultModel: Array.isArray(selected.deployments) ? compiled.defaultModel : undefined,
562
+ });
563
+ setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
564
+ }
565
+ function syncSharedClaudeCapabilities(targets) {
212
566
  if (["claude_app", "claude_code"].some(id => setup[id] === "default_unavailable")) {
213
- sharedSync = { ...sharedSync, state: "partially_preserved", limitations: [{ code: "default_model_unavailable" }] };return;
567
+ sharedSync = {
568
+ ...sharedSync,
569
+ state: "partially_preserved",
570
+ limitations: [{ code: "default_model_unavailable" }],
571
+ };
572
+ return;
214
573
  }
215
574
  if (!["claude_app", "claude_code"].some(id => targets.has(id))) return;
216
- if (["claude_app", "claude_code"].some(id => !targets.has(id) && !setup[id] && binding(id).enabled && plan(id).models.length)) {
217
- sharedSync = { state: "partially_preserved", limitations: [{ code: "other_client_not_checked" }] };return;
575
+ if (
576
+ ["claude_app", "claude_code"].some(
577
+ id => !targets.has(id) && !setup[id] && binding(id).enabled && plan(id).models.length
578
+ )
579
+ ) {
580
+ sharedSync = { state: "partially_preserved", limitations: [{ code: "other_client_not_checked" }] };
581
+ return;
218
582
  }
219
- const shared = claudeSharedCapabilityPlan({ app: setup.claude_app === "configured" ? plan("claude_app").models : [],
220
- code: setup.claude_code === "configured" ? plan("claude_code").models : [], support: capabilitySupport });
583
+ const shared = claudeSharedCapabilityPlan({
584
+ app: setup.claude_app === "configured" ? plan("claude_app").models : [],
585
+ code: setup.claude_code === "configured" ? plan("claude_code").models : [],
586
+ support: capabilitySupport,
587
+ });
221
588
  if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
222
- sharedSync = { ...shared, state: "partially_preserved", limitations: [...shared.limitations, { code: "manual_sync" }] };return;
589
+ sharedSync = {
590
+ ...shared,
591
+ state: "partially_preserved",
592
+ limitations: [...shared.limitations, { code: "manual_sync" }],
593
+ };
594
+ return;
595
+ }
596
+ try {
597
+ sharedSync = { ...shared, ...syncClaudeCapabilities(shared, options) };
598
+ } catch {
599
+ sharedSync = { state: "configuration_unavailable", limitations: shared.limitations };
223
600
  }
224
- try { sharedSync = { ...shared, ...syncClaudeCapabilities(shared, options) }; }
225
- catch { sharedSync = { state: "configuration_unavailable", limitations: shared.limitations }; }
601
+ }
602
+ async function performClientSync(targets, requested = new Set()) {
603
+ if (!managed || closed) return;
604
+ if (options.preserveClientConfiguration?.()) {
605
+ for (const id of targets) setup[id] = "preserved";
606
+ return;
607
+ }
608
+ const codex = binding("codex"),
609
+ compiledCodex = plan("codex"),
610
+ mode = codexAccessMode();
611
+ if (targets.has("codex")) syncCodexClient(codex, compiledCodex, requested, mode);
612
+ if (!settings.claude_private_keys || !["claude_app", "claude_code"].some(id => targets.has(id))) return;
613
+ let desktopManaged;
614
+ for (const id of ["claude_app", "claude_code"]) {
615
+ if (!targets.has(id)) continue;
616
+ const sync = prepareClaudeSync(id, requested);
617
+ if (!sync) continue;
618
+ try {
619
+ if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
620
+ writeClaudeSync(id, sync, desktopManaged);
621
+ } catch {
622
+ setup[id] = "configuration_unavailable";
623
+ }
624
+ }
625
+ syncSharedClaudeCapabilities(targets);
226
626
  }
227
627
  function requireSource(clientId, id) {
228
628
  if (!permitted(clientId, id)) throw accessError("ccdx_client_source_disabled", 503);
229
- if (id === "m365" && legacy.snapshot().m365.account_change_in_flight) throw accessError("m365_account_busy", 409);
230
- const source = getSource(id);if (!source) throw accessError("ccdx_api_not_ready", 503);return source;
629
+ if (id === "m365" && legacy.snapshot().m365.account_change_in_flight)
630
+ throw accessError("m365_account_busy", 409);
631
+ const source = getSource(id);
632
+ if (!source) throw accessError("ccdx_api_not_ready", 503);
633
+ return source;
231
634
  }
232
635
  function validateConversation(body, headers, source, client = "codex") {
233
636
  if (!body || typeof body !== "object" || Array.isArray(body)) return;
234
- if (managed && (binding(client).history_isolation || source?.id.startsWith("api_") || client === "claude_app")) {
235
- const transfer = client === "claude_app" ? {
236
- profiles: [...new Set(plan(client).models.map(model => model.source_id))].map(id => getSource(id).profileId("messages")),
237
- prepare: input => messagesTransfer.prepare({ ...input, countTokens: currentRequestContext()?.route === "messages_count_tokens" }),
238
- } : undefined;
239
- return guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client], transfer);
637
+ if (
638
+ managed &&
639
+ (binding(client).history_isolation || source?.id.startsWith("api_") || client === "claude_app")
640
+ ) {
641
+ const transfer =
642
+ client === "claude_app"
643
+ ? {
644
+ profiles: [...new Set(plan(client).models.map(model => model.source_id))].map(id =>
645
+ getSource(id).profileId("messages")
646
+ ),
647
+ prepare: input =>
648
+ messagesTransfer.prepare({
649
+ ...input,
650
+ countTokens: currentRequestContext()?.route === "messages_count_tokens",
651
+ }),
652
+ }
653
+ : undefined;
654
+ return guardConversation(
655
+ client,
656
+ source.profileId(client === "codex" ? "responses" : "messages"),
657
+ body,
658
+ headers,
659
+ identities()[client],
660
+ transfer
661
+ );
240
662
  }
241
663
  }
242
664
  async function applyCatalog(id, models, revision, checkedAt, active) {
243
665
  if (!active()) throw accessError("ccdx_connections_conflict", 409);
244
- const next = editable(), current = next.apis.find(api => api.id === id);
245
- if (!current?.enabled || deploymentRevision(current, env) !== revision) throw accessError("ccdx_connections_conflict", 409);
666
+ const next = editable(),
667
+ current = next.apis.find(api => api.id === id);
668
+ if (!current?.enabled || deploymentRevision(current, env) !== revision)
669
+ throw accessError("ccdx_connections_conflict", 409);
246
670
  const byId = new Map(models.map(model => [model.id, model]));
247
671
  let displayChanged = false;
248
- try { displayChanged = modelDisplay.set(id, revision, models); } catch { log("warn", "Model display metadata could not be saved; routing is unchanged"); }
249
- for (const model of current.models) if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
672
+ try {
673
+ displayChanged = modelDisplay.set(id, revision, models);
674
+ } catch {
675
+ log("warn", "Model display metadata could not be saved; routing is unchanged");
676
+ }
677
+ for (const model of current.models)
678
+ if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
250
679
  current.checked_at = checkedAt;
251
680
  const changed = JSON.stringify(current) !== JSON.stringify(settings.apis.find(api => api.id === id));
252
681
  if (changed) save(next);
253
682
  if (changed || displayChanged) {
254
- plans.clear();await syncClients(CLIENT_IDS.filter(client => binding(client).source === id || binding(client).deployments?.some(model => model.source === id)));
683
+ plans.clear();
684
+ await syncClients(
685
+ CLIENT_IDS.filter(
686
+ client =>
687
+ binding(client).source === id || binding(client).deployments?.some(model => model.source === id)
688
+ )
689
+ );
255
690
  }
256
691
  }
257
- function enqueue(work) { operations++;const job = serial.then(work).finally(() => { operations--; });serial = job.catch(() => {});return job; }
258
- const refreshApis = () => !closed && managed && !preserveClientConfiguration?.() ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id)) : Promise.resolve();
259
- async function change(input) {
260
- if (closed) throw accessError("ccdx_connections_closed", 503);
261
- if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "impact_revision", "model", "auto_review_model", "auto_review_effort", "deployments", "default_model", "auto_sync", "client_revision"])) throw accessError("ccdx_connections_action_invalid");
262
- if (["client", "preview_client", "sync_client", "client_state"].includes(input.operation) && input.client_revision !== undefined
263
- && (!CLIENT_IDS.includes(input.id) || input.client_revision !== clientRevision(input.id))) throw accessError("ccdx_connections_conflict", 409);
264
- if (!["client", "preview_client", "sync_client", "client_state"].includes(input.operation) && input.impact_revision !== undefined
265
- && input.impact_revision !== sourceImpact(input.id).revision) throw accessError("ccdx_connections_conflict", 409);
266
- if (input.operation === "sync_client") {
267
- if (!validObject(input, ["operation", "id", "client_revision"]) || !CLIENT_IDS.includes(input.id) || typeof input.client_revision !== "string") throw accessError("ccdx_connections_action_invalid");
268
- await syncClients([input.id], { manual: true });return snapshot();
692
+ function enqueue(work) {
693
+ operations++;
694
+ const job = serial.then(work).finally(() => {
695
+ operations--;
696
+ });
697
+ serial = job.catch(() => {});
698
+ return job;
699
+ }
700
+ const refreshApis = () =>
701
+ !closed && managed && !preserveClientConfiguration?.()
702
+ ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id))
703
+ : Promise.resolve();
704
+ function prepareSourceAccess(input, next) {
705
+ if (
706
+ !["github", "m365", ...next.apis.map(api => api.id)].includes(input.id) ||
707
+ !Array.isArray(input.allowed) ||
708
+ new Set(input.allowed).size !== input.allowed.length ||
709
+ input.allowed.some(id => !CLIENT_IDS.includes(id))
710
+ )
711
+ throw accessError("ccdx_connections_action_invalid");
712
+ const api = next.apis.find(api => api.id === input.id);
713
+ if (
714
+ input.allowed.some(
715
+ id =>
716
+ (input.id === "github" && id !== "codex") ||
717
+ (api && !api.endpoints[id === "codex" ? "responses" : "messages"])
718
+ )
719
+ )
720
+ throw accessError("ccdx_api_protocol_required");
721
+ const affected = CLIENT_IDS.filter(
722
+ id => next.clients[id].allowed.includes(input.id) !== input.allowed.includes(id)
723
+ );
724
+ const sharedClaude = ["claude_app", "claude_code"].filter(
725
+ id => next.clients[id].enabled && next.clients[id].source === "m365"
726
+ );
727
+ const migrateClaude =
728
+ input.id === "m365" &&
729
+ !next.claude_private_keys &&
730
+ sharedClaude.length > 0 &&
731
+ affected.some(id => id !== "codex");
732
+ const targets = new Set();
733
+ for (const id of affected) {
734
+ const c = next.clients[id];
735
+ c.allowed = [
736
+ ...c.allowed.filter(source => source !== input.id),
737
+ ...(input.allowed.includes(id) ? [input.id] : []),
738
+ ];
739
+ if (!input.allowed.includes(id)) {
740
+ if (c.source === input.id || c.deployments?.some(item => item.source === input.id)) targets.add(id);
741
+ if (c.source === input.id) c.source = null;
742
+ if (Array.isArray(c.deployments))
743
+ c.deployments = c.deployments.filter(item => item.source !== input.id);
744
+ c.history_isolation = true;
745
+ }
269
746
  }
270
- if (input.operation === "client_state") {
271
- if (!validObject(input, ["operation", "id", "enabled", "client_revision"]) || !CLIENT_IDS.includes(input.id)
272
- || typeof input.enabled !== "boolean" || typeof input.client_revision !== "string") throw accessError("ccdx_connections_action_invalid");
273
- const next = editable();next.clients[input.id].enabled = input.enabled;save(next);
274
- await syncClients([input.id]);
275
- if (input.id === "codex") await clientAccessChanged?.(input.enabled);
276
- return snapshot();
747
+ if (migrateClaude) next.claude_private_keys = true;
748
+ if (migrateClaude)
749
+ for (const id of ["claude_app", "claude_code"]) if (next.clients[id].source === "m365") targets.add(id);
750
+ return { targets, migrateClaude };
751
+ }
752
+ function removeApi(input, next) {
753
+ const existing = next.apis.find(api => api.id === input.id);
754
+ if (
755
+ !validObject(input, ["operation", "id", "impact_revision"]) ||
756
+ !existing ||
757
+ existing.enabled ||
758
+ CLIENT_IDS.some(
759
+ id =>
760
+ binding(id).source === input.id || binding(id).deployments?.some(item => item.source === input.id)
761
+ )
762
+ )
763
+ throw accessError("ccdx_source_in_use", 409);
764
+ const previousRef = existing.secret_ref;
765
+ catalogRefresh.cancel(input.id);
766
+ next.apis = next.apis.filter(api => api.id !== input.id);
767
+ for (const id of CLIENT_IDS)
768
+ next.clients[id].allowed = next.clients[id].allowed.filter(source => source !== input.id);
769
+ save(next);
770
+ discoveries.delete(input.id);
771
+ return previousRef;
772
+ }
773
+ function prepareApiSave(input, next) {
774
+ let freshRef, previousRef;
775
+ const existing = next.apis.find(api => api.id === input.id);
776
+ if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
777
+ if (
778
+ !validObject(input.config, [
779
+ "name",
780
+ "base_url",
781
+ "endpoints",
782
+ "auth_header",
783
+ "models",
784
+ "key_env",
785
+ "model_display",
786
+ ])
787
+ )
788
+ throw accessError("ccdx_api_config_invalid");
789
+ // Existing clients round-trip catalog data. New display-only fields must
790
+ // remain readable without becoming editable connection configuration.
791
+ const { model_display, ...editableConfig } = input.config;
792
+ input = {
793
+ ...input,
794
+ config: {
795
+ ...editableConfig,
796
+ models: Array.isArray(editableConfig.models)
797
+ ? editableConfig.models.map(model => {
798
+ if (!model || typeof model !== "object" || Array.isArray(model)) return model;
799
+ const { display, ...editable } = model;
800
+ return editable;
801
+ })
802
+ : editableConfig.models,
803
+ },
804
+ };
805
+ const id = existing?.id || "api_" + randomBytes(8).toString("hex");
806
+ if (input.key !== undefined && input.key !== "") {
807
+ checkedApiKey(input.key);
808
+ freshRef = randomBytes(16).toString("hex");
277
809
  }
278
- const next = editable();let freshRef, previousRef;
279
- if (input.operation === "source_access") {
280
- if (!["github", "m365", ...next.apis.map(api => api.id)].includes(input.id) || !Array.isArray(input.allowed) || new Set(input.allowed).size !== input.allowed.length || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
281
- const api = next.apis.find(api => api.id === input.id);
282
- if (input.allowed.some(id => input.id === "github" && id !== "codex" || api && !api.endpoints[id === "codex" ? "responses" : "messages"])) throw accessError("ccdx_api_protocol_required");
283
- const affected = CLIENT_IDS.filter(id => next.clients[id].allowed.includes(input.id) !== input.allowed.includes(id));
284
- const sharedClaude = ["claude_app", "claude_code"].filter(id => next.clients[id].enabled && next.clients[id].source === "m365");
285
- const migrateClaude = input.id === "m365" && !next.claude_private_keys && sharedClaude.length > 0 && affected.some(id => id !== "codex");
286
- const targets = new Set();
287
- for (const id of affected) {
288
- const c = next.clients[id];
289
- c.allowed = [...c.allowed.filter(source => source !== input.id), ...(input.allowed.includes(id) ? [input.id] : [])];
290
- if (!input.allowed.includes(id)) {
291
- if (c.source === input.id || c.deployments?.some(item => item.source === input.id)) targets.add(id);
292
- if (c.source === input.id) c.source = null;
293
- if (Array.isArray(c.deployments)) c.deployments = c.deployments.filter(item => item.source !== input.id);
294
- c.history_isolation = true;
295
- }
296
- }
297
- if (migrateClaude) next.claude_private_keys = true;
298
- if (migrateClaude) for (const id of ["claude_app", "claude_code"]) if (next.clients[id].source === "m365") targets.add(id);
299
- save(next);await syncClients([...targets]);
300
- const retained = migrateClaude ? [...targets].filter(id => id !== "codex" && next.clients[id].enabled && next.clients[id].source === "m365") : [];
301
- return { ...snapshot(), client_refresh: retained.filter(id => setup[id] === "configured"),
302
- client_review: retained.filter(id => ["preserved", "partially_preserved", "manual_sync", "configuration_unavailable"].includes(setup[id])) };
303
- } else if (input.operation === "remove_api") {
304
- const existing = next.apis.find(api => api.id === input.id);
305
- if (!validObject(input, ["operation", "id", "impact_revision"]) || !existing || existing.enabled || CLIENT_IDS.some(id => binding(id).source === input.id || binding(id).deployments?.some(item => item.source === input.id))) throw accessError("ccdx_source_in_use", 409);
306
- previousRef = existing.secret_ref;catalogRefresh.cancel(input.id);
307
- next.apis = next.apis.filter(api => api.id !== input.id);
308
- for (const id of CLIENT_IDS) next.clients[id].allowed = next.clients[id].allowed.filter(source => source !== input.id);
309
- save(next);discoveries.delete(input.id);
310
- } else if (input.operation === "save_api") {
311
- const existing = next.apis.find(api => api.id === input.id);
312
- if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
313
- if (!validObject(input.config, ["name", "base_url", "endpoints", "auth_header", "models", "key_env", "model_display"])) throw accessError("ccdx_api_config_invalid");
314
- // Existing clients round-trip catalog data. New display-only fields must
315
- // remain readable without becoming editable connection configuration.
316
- const { model_display, ...editableConfig } = input.config;
317
- input = { ...input, config: { ...editableConfig, models: Array.isArray(editableConfig.models) ? editableConfig.models.map(model => {
318
- if (!model || typeof model !== "object" || Array.isArray(model)) return model;
319
- const { display, ...editable } = model;return editable;
320
- }) : editableConfig.models } };
321
- const id = existing?.id || "api_" + randomBytes(8).toString("hex");
322
- if (input.key !== undefined && input.key !== "") { checkedApiKey(input.key);freshRef = randomBytes(16).toString("hex"); }
323
- if (input.config.key_env && freshRef || !input.config.key_env && !freshRef && !existing?.secret_ref) throw accessError("ccdx_api_key_invalid");
324
- const config = checkedApi({ ...input.config, id, enabled: existing?.enabled ?? true, ...(!input.config.key_env ? { secret_ref: freshRef || existing.secret_ref } : {}) });
325
- if (!Array.isArray(input.allowed) || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
326
- for (const id of CLIENT_IDS) {
327
- const c = next.clients[id];if (c.deployments?.some(item => item.source === config.id && (!input.allowed.includes(id)
328
- || !config.models.some(model => model.id === item.model && model.protocols.includes(id === "codex" ? "responses" : "messages"))))) throw accessError("ccdx_source_in_use", 409);
329
- if (c.source === config.id && !input.allowed.includes(id)) throw accessError("ccdx_source_in_use", 409);
330
- if (c.source === config.id && c.enabled && !Array.isArray(c.deployments) && (!config.models.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages"))
331
- || 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");
332
- if (input.allowed.includes(id) && !config.endpoints[id === "codex" ? "responses" : "messages"]) throw accessError("ccdx_api_protocol_required");
333
- c.allowed = [...new Set([...c.allowed.filter(value => value !== config.id), ...(input.allowed.includes(id) ? [config.id] : [])])];
334
- }
335
- if (existing) { previousRef = existing.secret_ref;next.apis[next.apis.indexOf(existing)] = config; } else next.apis.push(config);
810
+ if ((input.config.key_env && freshRef) || (!input.config.key_env && !freshRef && !existing?.secret_ref))
811
+ throw accessError("ccdx_api_key_invalid");
812
+ const config = checkedApi({
813
+ ...input.config,
814
+ id,
815
+ enabled: existing?.enabled ?? true,
816
+ ...(!input.config.key_env ? { secret_ref: freshRef || existing.secret_ref } : {}),
817
+ });
818
+ if (!Array.isArray(input.allowed) || input.allowed.some(id => !CLIENT_IDS.includes(id)))
819
+ throw accessError("ccdx_connections_action_invalid");
820
+ for (const id of CLIENT_IDS) {
821
+ const c = next.clients[id];
822
+ if (
823
+ c.deployments?.some(
824
+ item =>
825
+ item.source === config.id &&
826
+ (!input.allowed.includes(id) ||
827
+ !config.models.some(
828
+ model =>
829
+ model.id === item.model &&
830
+ model.protocols.includes(id === "codex" ? "responses" : "messages")
831
+ ))
832
+ )
833
+ )
834
+ throw accessError("ccdx_source_in_use", 409);
835
+ if (c.source === config.id && !input.allowed.includes(id)) throw accessError("ccdx_source_in_use", 409);
836
+ if (
837
+ c.source === config.id &&
838
+ c.enabled &&
839
+ !Array.isArray(c.deployments) &&
840
+ (!config.models.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages")) ||
841
+ (id === "codex" &&
842
+ [c.model, c.auto_review_model]
843
+ .filter(Boolean)
844
+ .some(
845
+ value =>
846
+ !config.models.some(model => model.id === value && model.protocols.includes("responses"))
847
+ )))
848
+ )
849
+ throw accessError("ccdx_api_model_unavailable");
850
+ if (input.allowed.includes(id) && !config.endpoints[id === "codex" ? "responses" : "messages"])
851
+ throw accessError("ccdx_api_protocol_required");
852
+ c.allowed = [
853
+ ...new Set([
854
+ ...c.allowed.filter(value => value !== config.id),
855
+ ...(input.allowed.includes(id) ? [config.id] : []),
856
+ ]),
857
+ ];
858
+ }
859
+ if (existing) {
860
+ previousRef = existing.secret_ref;
861
+ next.apis[next.apis.indexOf(existing)] = config;
862
+ } else next.apis.push(config);
863
+ checkedAccessSettings(next);
864
+ return { input, freshRef, previousRef };
865
+ }
866
+ function applyClientSelection(input, next) {
867
+ if (
868
+ !CLIENT_IDS.includes(input.id) ||
869
+ typeof input.enabled !== "boolean" ||
870
+ !Array.isArray(input.allowed) ||
871
+ (input.source !== null && input.source !== undefined && !input.allowed.includes(input.source))
872
+ )
873
+ throw accessError("ccdx_connections_action_invalid");
874
+ const old = next.clients[input.id],
875
+ retained = { ...old };
876
+ if (old.source !== input.source || (Array.isArray(old.deployments) && input.deployments === null))
877
+ for (const key of ["model", "auto_review_model", "auto_review_effort"]) delete retained[key];
878
+ next.clients[input.id] = {
879
+ ...retained,
880
+ enabled: input.enabled,
881
+ allowed: input.allowed,
882
+ source: input.enabled ? (input.source ?? old.source) : null,
883
+ ...(input.deployments !== undefined
884
+ ? {
885
+ deployments: input.deployments,
886
+ default_model: input.default_model ?? null,
887
+ auto_sync: input.auto_sync ?? true,
888
+ }
889
+ : old.source !== input.source
890
+ ? { deployments: null, default_model: null }
891
+ : {}),
892
+ ...(input.model ? { model: input.model } : {}),
893
+ ...(input.auto_review_model ? { auto_review_model: input.auto_review_model } : {}),
894
+ ...(input.auto_review_effort !== undefined ? { auto_review_effort: input.auto_review_effort } : {}),
895
+ };
896
+ if (input.id !== "codex") next.claude_private_keys = true;
897
+ if (old.source !== input.source) next.clients[input.id].history_isolation = true;
898
+ const c = next.clients[input.id];
899
+ if (Array.isArray(input.deployments)) {
336
900
  checkedAccessSettings(next);
337
- try { if (freshRef) await secrets.set(freshRef, input.key);save(next); } catch (error) { if (freshRef) await secrets.remove(freshRef).catch(() => {});throw error; }
338
- } else if (["client", "preview_client"].includes(input.operation)) {
339
- if (!CLIENT_IDS.includes(input.id) || typeof input.enabled !== "boolean" || !Array.isArray(input.allowed)
340
- || input.source !== null && input.source !== undefined && !input.allowed.includes(input.source)) throw accessError("ccdx_connections_action_invalid");
341
- 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];
342
- next.clients[input.id] = { ...retained, enabled: input.enabled, allowed: input.allowed, source: input.enabled ? input.source ?? old.source : null,
343
- ...(input.deployments !== undefined ? { deployments: input.deployments, default_model: input.default_model ?? null, auto_sync: input.auto_sync ?? true }
344
- : old.source !== input.source ? { deployments: null, default_model: null } : {}),
345
- ...(input.model ? { model: input.model } : {}), ...(input.auto_review_model ? { auto_review_model: input.auto_review_model } : {}),
346
- ...(input.auto_review_effort !== undefined ? { auto_review_effort: input.auto_review_effort } : {}) };
347
- if (input.id !== "codex") next.claude_private_keys = true;
348
- if (old.source !== input.source) next.clients[input.id].history_isolation = true;
349
- const c = next.clients[input.id];
350
- if (Array.isArray(input.deployments)) {
351
- checkedAccessSettings(next);
352
- for (const item of c.deployments || []) {
353
- if (!enabled(item.source) || !sourceModels(getSource(item.source), input.id).some(model => model.id === item.model)) throw accessError("ccdx_api_model_unavailable");
354
- }
355
- const names = Object.fromEntries(next.apis.map(api => [api.id, api.name]));
356
- const compiled = compileClientModels({ client: input.id, binding: c, source: getSource, enabled, names, desktopEffortAliases: capabilitySupport.app });
357
- if (c.default_model && !compiled.routes.has(c.default_model)) throw accessError("ccdx_api_model_unavailable");
358
- 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;
359
- c.history_isolation = true;
360
- if (input.id === "codex") {
361
- c.model = compiled.routes.get(c.default_model)?.upstreamModel;
362
- const review = compiled.routes.get(old.auto_review_model) || [...compiled.routes.values()].find(record => record.source === old.source && record.upstreamModel === old.auto_review_model);
363
- 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;
364
- if (review?.source === c.source && old.auto_review_effort !== undefined) c.auto_review_effort = old.auto_review_effort;else delete c.auto_review_effort;
365
- }
901
+ for (const item of c.deployments || []) {
902
+ if (
903
+ !enabled(item.source) ||
904
+ !sourceModels(getSource(item.source), input.id).some(model => model.id === item.model)
905
+ )
906
+ throw accessError("ccdx_api_model_unavailable");
366
907
  }
367
- if (c.source && !Array.isArray(input.deployments)) {
368
- if (!enabled(c.source)) throw accessError("ccdx_client_source_disabled", 503);
369
- const target = getSource(c.source), family = input.id === "codex" ? "gpt" : "claude";
370
- 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);
371
- if (input.id !== "codex" && c.source === "github" || c.source !== "github" && !target?.models(family).length) throw accessError("ccdx_api_model_unavailable");
372
- if (input.id === "codex" && c.source !== "github") {
373
- const previous = c.source === "m365" ? legacy.selection().m365 : null;
374
- c.model = input.model || previous?.model || target.models("gpt")[0].id;c.auto_review_model = input.auto_review_model || previous?.auto_review_model || c.model;
375
- if (![c.model, c.auto_review_model].every(id => target.models("gpt").some(model => model.id === id))) throw accessError("ccdx_api_model_unavailable");
376
- const efforts = api ? sourceModels(target, "codex").find(model => model.id === c.auto_review_model)?.capability.values.reasoning_efforts || []
377
- : autoReviewReasoningEfforts(target.models("gpt").find(model => model.id === c.auto_review_model));
378
- if (c.auto_review_effort !== undefined && c.auto_review_effort !== null && !efforts.includes(c.auto_review_effort)) throw accessError("ccdx_api_effort_unavailable");
379
- }
908
+ const names = Object.fromEntries(next.apis.map(api => [api.id, api.name]));
909
+ const compiled = compileClientModels({
910
+ client: input.id,
911
+ binding: c,
912
+ source: getSource,
913
+ enabled,
914
+ names,
915
+ desktopEffortAliases: capabilitySupport.app,
916
+ });
917
+ if (c.default_model && !compiled.routes.has(c.default_model))
918
+ throw accessError("ccdx_api_model_unavailable");
919
+ c.default_model = compiled.routes.get(compiled.defaultModel)?.model.route_id || null;
920
+ c.source = c.enabled ? compiled.routes.get(c.default_model)?.source || null : null;
921
+ c.history_isolation = true;
922
+ if (input.id === "codex") {
923
+ c.model = compiled.routes.get(c.default_model)?.upstreamModel;
924
+ const review =
925
+ compiled.routes.get(old.auto_review_model) ||
926
+ [...compiled.routes.values()].find(
927
+ record => record.source === old.source && record.upstreamModel === old.auto_review_model
928
+ );
929
+ if (c.default_model)
930
+ c.auto_review_model = review?.source === c.source ? review.model.route_id : c.default_model;
931
+ else delete c.auto_review_model;
932
+ if (review?.source === c.source && old.auto_review_effort !== undefined)
933
+ c.auto_review_effort = old.auto_review_effort;
934
+ else delete c.auto_review_effort;
380
935
  }
381
- if (input.operation === "preview_client") {
382
- const proposed = compileClientModels({ client: input.id, binding: c, source: getSource, enabled, desktopEffortAliases: capabilitySupport.app });
383
- const shared = input.id === "codex" ? null : claudeSharedCapabilityPlan({ app: input.id === "claude_app" ? proposed.models : plan("claude_app").models,
384
- code: input.id === "claude_code" ? proposed.models : plan("claude_code").models, support: capabilitySupport });
385
- return { ...snapshot(), preview: { models: proposed.models.map(model => ({ source: model.source_id, id: model.id, public_id: model.public_id, capability: model.capability })),
386
- shared, current: input.id === "codex" ? null : inspectClaudeCapabilityConfiguration(proposed.models, options), saved: false } };
936
+ }
937
+ if (c.source && !Array.isArray(input.deployments)) {
938
+ if (!enabled(c.source)) throw accessError("ccdx_client_source_disabled", 503);
939
+ const target = getSource(c.source),
940
+ family = input.id === "codex" ? "gpt" : "claude";
941
+ const api = settings.apis.find(api => api.id === c.source);
942
+ if (api?.key_env && !env[api.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
943
+ if (
944
+ (input.id !== "codex" && c.source === "github") ||
945
+ (c.source !== "github" && !target?.models(family).length)
946
+ )
947
+ throw accessError("ccdx_api_model_unavailable");
948
+ if (input.id === "codex" && c.source !== "github") {
949
+ const previous = c.source === "m365" ? legacy.selection().m365 : null;
950
+ c.model = input.model || previous?.model || target.models("gpt")[0].id;
951
+ c.auto_review_model = input.auto_review_model || previous?.auto_review_model || c.model;
952
+ if (![c.model, c.auto_review_model].every(id => target.models("gpt").some(model => model.id === id)))
953
+ throw accessError("ccdx_api_model_unavailable");
954
+ const efforts = api
955
+ ? sourceModels(target, "codex").find(model => model.id === c.auto_review_model)?.capability.values
956
+ .reasoning_efforts || []
957
+ : autoReviewReasoningEfforts(target.models("gpt").find(model => model.id === c.auto_review_model));
958
+ if (
959
+ c.auto_review_effort !== undefined &&
960
+ c.auto_review_effort !== null &&
961
+ !efforts.includes(c.auto_review_effort)
962
+ )
963
+ throw accessError("ccdx_api_effort_unavailable");
387
964
  }
388
- save(next);
389
- } else if (input.operation === "provider") {
390
- if (typeof input.enabled !== "boolean" || !["github", "m365", ...next.apis.map(api => api.id)].includes(input.id)) throw accessError("ccdx_connections_action_invalid");
391
- if (input.id === "m365" && input.enabled && env.CCDX_M365 === "0") throw accessError("ccdx_provider_environment_disabled", 409);
392
- if (input.id === "m365" && !input.enabled && legacy.snapshot().m365.claude.requests?.active > 0) throw accessError("ccdx_source_busy", 409);
393
- if (!input.enabled) {
394
- const impact = sourceImpact(input.id);
395
- if (input.impact_revision !== undefined && input.impact_revision !== impact.revision) throw accessError("ccdx_connections_conflict", 409);
396
- const affected = impact.clients.filter(client => client.needs_replacement).map(client => client.id);
397
- if (affected.some(id => id !== "codex")) next.claude_private_keys = true;
398
- if (affected.length && !validObject(input.replacements, affected)) throw accessError("ccdx_source_in_use", 409);
399
- for (const id of affected) {
400
- const replacement = input.replacements[id];
401
- if (replacement !== null && (replacement === input.id || !permitted(id, replacement) || replacement !== "github" && !getSource(replacement)?.models(id === "codex" ? "gpt" : "claude").length)) throw accessError("ccdx_connections_action_invalid");
402
- next.clients[id].source = replacement;
403
- next.clients[id].history_isolation = true;
404
- }
965
+ }
966
+ if (input.operation === "preview_client") {
967
+ const proposed = compileClientModels({
968
+ client: input.id,
969
+ binding: c,
970
+ source: getSource,
971
+ enabled,
972
+ desktopEffortAliases: capabilitySupport.app,
973
+ });
974
+ const shared =
975
+ input.id === "codex"
976
+ ? null
977
+ : claudeSharedCapabilityPlan({
978
+ app: input.id === "claude_app" ? proposed.models : plan("claude_app").models,
979
+ code: input.id === "claude_code" ? proposed.models : plan("claude_code").models,
980
+ support: capabilitySupport,
981
+ });
982
+ return {
983
+ ...snapshot(),
984
+ preview: {
985
+ models: proposed.models.map(model => ({
986
+ source: model.source_id,
987
+ id: model.id,
988
+ public_id: model.public_id,
989
+ capability: model.capability,
990
+ })),
991
+ shared,
992
+ current:
993
+ input.id === "codex" ? null : inspectClaudeCapabilityConfiguration(proposed.models, options),
994
+ saved: false,
995
+ },
996
+ };
997
+ }
998
+ save(next);
999
+ }
1000
+ function applyProviderEnabled(input, next) {
1001
+ if (
1002
+ typeof input.enabled !== "boolean" ||
1003
+ !["github", "m365", ...next.apis.map(api => api.id)].includes(input.id)
1004
+ )
1005
+ throw accessError("ccdx_connections_action_invalid");
1006
+ if (input.id === "m365" && input.enabled && env.CCDX_M365 === "0")
1007
+ throw accessError("ccdx_provider_environment_disabled", 409);
1008
+ if (input.id === "m365" && !input.enabled && legacy.snapshot().m365.claude.requests?.active > 0)
1009
+ throw accessError("ccdx_source_busy", 409);
1010
+ if (!input.enabled) {
1011
+ const impact = sourceImpact(input.id);
1012
+ if (input.impact_revision !== undefined && input.impact_revision !== impact.revision)
1013
+ throw accessError("ccdx_connections_conflict", 409);
1014
+ const affected = impact.clients.filter(client => client.needs_replacement).map(client => client.id);
1015
+ if (affected.some(id => id !== "codex")) next.claude_private_keys = true;
1016
+ if (affected.length && !validObject(input.replacements, affected))
1017
+ throw accessError("ccdx_source_in_use", 409);
1018
+ for (const id of affected) {
1019
+ const replacement = input.replacements[id];
1020
+ if (
1021
+ replacement !== null &&
1022
+ (replacement === input.id ||
1023
+ !permitted(id, replacement) ||
1024
+ (replacement !== "github" &&
1025
+ !getSource(replacement)?.models(id === "codex" ? "gpt" : "claude").length))
1026
+ )
1027
+ throw accessError("ccdx_connections_action_invalid");
1028
+ next.clients[id].source = replacement;
1029
+ next.clients[id].history_isolation = true;
405
1030
  }
406
- if (!input.enabled) for (const id of CLIENT_IDS) {
407
- const c = next.clients[id];if (!Array.isArray(c.deployments)) continue;
408
- const had = c.deployments.some(item => item.source === input.id);if (!had) continue;
1031
+ }
1032
+ if (!input.enabled)
1033
+ for (const id of CLIENT_IDS) {
1034
+ const c = next.clients[id];
1035
+ if (!Array.isArray(c.deployments)) continue;
1036
+ const had = c.deployments.some(item => item.source === input.id);
1037
+ if (!had) continue;
409
1038
  c.deployments = c.deployments.filter(item => item.source !== input.id);
410
1039
  if (input.replacements && Object.hasOwn(input.replacements, id)) {
411
1040
  const replacement = input.replacements[id];
412
1041
  if (!replacement) c.deployments = [];
413
1042
  else if (!c.deployments.some(item => item.source === replacement)) {
414
- const model = sourceModels(getSource(replacement), id)[0];if (model) c.deployments.push({ source: replacement, model: model.id });
1043
+ const model = sourceModels(getSource(replacement), id)[0];
1044
+ if (model) c.deployments.push({ source: replacement, model: model.id });
415
1045
  }
416
- c.default_model = c.deployments.find(item => item.source === replacement) ? deploymentModelId(replacement, c.deployments.find(item => item.source === replacement).model) : null;
1046
+ c.default_model = c.deployments.find(item => item.source === replacement)
1047
+ ? deploymentModelId(replacement, c.deployments.find(item => item.source === replacement).model)
1048
+ : null;
417
1049
  }
418
1050
  }
419
- if (input.id.startsWith("api_")) next.apis.find(api => api.id === input.id).enabled = input.enabled;else next.providers[input.id] = input.enabled;
1051
+ if (input.id.startsWith("api_")) next.apis.find(api => api.id === input.id).enabled = input.enabled;
1052
+ else next.providers[input.id] = input.enabled;
1053
+ save(next);
1054
+ }
1055
+ async function change(input) {
1056
+ if (closed) throw accessError("ccdx_connections_closed", 503);
1057
+ if (
1058
+ !validObject(input, [
1059
+ "operation",
1060
+ "id",
1061
+ "config",
1062
+ "key",
1063
+ "allowed",
1064
+ "source",
1065
+ "enabled",
1066
+ "replacements",
1067
+ "impact_revision",
1068
+ "model",
1069
+ "auto_review_model",
1070
+ "auto_review_effort",
1071
+ "deployments",
1072
+ "default_model",
1073
+ "auto_sync",
1074
+ "client_revision",
1075
+ ])
1076
+ )
1077
+ throw accessError("ccdx_connections_action_invalid");
1078
+ if (
1079
+ ["client", "preview_client", "sync_client", "client_state"].includes(input.operation) &&
1080
+ input.client_revision !== undefined &&
1081
+ (!CLIENT_IDS.includes(input.id) || input.client_revision !== clientRevision(input.id))
1082
+ )
1083
+ throw accessError("ccdx_connections_conflict", 409);
1084
+ if (
1085
+ !["client", "preview_client", "sync_client", "client_state"].includes(input.operation) &&
1086
+ input.impact_revision !== undefined &&
1087
+ input.impact_revision !== sourceImpact(input.id).revision
1088
+ )
1089
+ throw accessError("ccdx_connections_conflict", 409);
1090
+ if (input.operation === "sync_client") {
1091
+ if (
1092
+ !validObject(input, ["operation", "id", "client_revision"]) ||
1093
+ !CLIENT_IDS.includes(input.id) ||
1094
+ typeof input.client_revision !== "string"
1095
+ )
1096
+ throw accessError("ccdx_connections_action_invalid");
1097
+ await syncClients([input.id], { manual: true });
1098
+ return snapshot();
1099
+ }
1100
+ if (input.operation === "client_state") {
1101
+ if (
1102
+ !validObject(input, ["operation", "id", "enabled", "client_revision"]) ||
1103
+ !CLIENT_IDS.includes(input.id) ||
1104
+ typeof input.enabled !== "boolean" ||
1105
+ typeof input.client_revision !== "string"
1106
+ )
1107
+ throw accessError("ccdx_connections_action_invalid");
1108
+ const next = editable();
1109
+ next.clients[input.id].enabled = input.enabled;
420
1110
  save(next);
1111
+ await syncClients([input.id]);
1112
+ if (input.id === "codex") await clientAccessChanged?.(input.enabled);
1113
+ return snapshot();
1114
+ }
1115
+ const next = editable();
1116
+ let freshRef, previousRef;
1117
+ if (input.operation === "source_access") {
1118
+ const { targets, migrateClaude } = prepareSourceAccess(input, next);
1119
+ save(next);
1120
+ await syncClients([...targets]);
1121
+ const retained = migrateClaude
1122
+ ? [...targets].filter(
1123
+ id => id !== "codex" && next.clients[id].enabled && next.clients[id].source === "m365"
1124
+ )
1125
+ : [];
1126
+ return {
1127
+ ...snapshot(),
1128
+ client_refresh: retained.filter(id => setup[id] === "configured"),
1129
+ client_review: retained.filter(id =>
1130
+ ["preserved", "partially_preserved", "manual_sync", "configuration_unavailable"].includes(setup[id])
1131
+ ),
1132
+ };
1133
+ } else if (input.operation === "remove_api") {
1134
+ previousRef = removeApi(input, next);
1135
+ } else if (input.operation === "save_api") {
1136
+ ({ input, freshRef, previousRef } = prepareApiSave(input, next));
1137
+ try {
1138
+ if (freshRef) await secrets.set(freshRef, input.key);
1139
+ save(next);
1140
+ } catch (error) {
1141
+ if (freshRef) await secrets.remove(freshRef).catch(() => {});
1142
+ throw error;
1143
+ }
1144
+ } else if (["client", "preview_client"].includes(input.operation)) {
1145
+ const preview = applyClientSelection(input, next);
1146
+ if (input.operation === "preview_client") return preview;
1147
+ } else if (input.operation === "provider") {
1148
+ applyProviderEnabled(input, next);
421
1149
  if (input.id === "m365") {
422
1150
  if (input.enabled) await legacy.action({ action: "on" });
423
1151
  else {
424
- const source = await legacy.pauseM365();if (source) retire(source);
1152
+ const source = await legacy.pauseM365();
1153
+ if (source) retire(source);
425
1154
  }
426
1155
  }
427
1156
  } else throw accessError("ccdx_connections_action_invalid");
428
1157
  await syncClients();
429
- if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
430
- if (previousRef && (freshRef || input.config?.key_env || input.operation === "remove_api")) { if (!retiredSecrets.has(input.id)) retiredSecrets.set(input.id, new Set());retiredSecrets.get(input.id).add(previousRef);cleanSecrets(input.id); }
1158
+ if (input.operation === "client" && input.id === "codex")
1159
+ await clientAccessChanged?.(binding("codex").enabled);
1160
+ if (previousRef && (freshRef || input.config?.key_env || input.operation === "remove_api")) {
1161
+ if (!retiredSecrets.has(input.id)) retiredSecrets.set(input.id, new Set());
1162
+ retiredSecrets.get(input.id).add(previousRef);
1163
+ cleanSecrets(input.id);
1164
+ }
431
1165
  return snapshot();
432
1166
  }
433
1167
  return {
434
1168
  ...legacy,
435
- managesClaude() { return !managed ? !legacyClaudeAccess : settings.claude_private_keys
436
- || !["claude_app", "claude_code"].every(id => binding(id).enabled && binding(id).source === "m365" && binding(id).allowed.includes("m365")); },
437
- syncSourceClients(source) { return syncClients(CLIENT_IDS.filter(id => binding(id).source === source || binding(id).deployments?.some(item => item.source === source))); },
1169
+ managesClaude() {
1170
+ return !managed
1171
+ ? !legacyClaudeAccess
1172
+ : settings.claude_private_keys ||
1173
+ !["claude_app", "claude_code"].every(
1174
+ id =>
1175
+ binding(id).enabled && binding(id).source === "m365" && binding(id).allowed.includes("m365")
1176
+ );
1177
+ },
1178
+ syncSourceClients(source) {
1179
+ return syncClients(
1180
+ CLIENT_IDS.filter(
1181
+ id => binding(id).source === source || binding(id).deployments?.some(item => item.source === source)
1182
+ )
1183
+ );
1184
+ },
438
1185
  source: getSource,
439
1186
  connections: snapshot,
440
- privateScopes: id => [...new Set(plan(id).models.map(model => model.source_id))].sort().map(source => [source, getSource(source).profileId(id === "codex" ? "responses" : "messages")]),
1187
+ privateScopes: id =>
1188
+ [...new Set(plan(id).models.map(model => model.source_id))]
1189
+ .sort()
1190
+ .map(source => [source, getSource(source).profileId(id === "codex" ? "responses" : "messages")]),
441
1191
  validateLocalKeys() {
442
- if (managed && CLIENT_IDS.some(id => binding(id).enabled && plan(id).models.some(model => model.source_id.startsWith("api_") || id !== "codex" && settings.claude_private_keys))) keys = readClientGatewayKeys({ ...options, create: false });
1192
+ if (
1193
+ managed &&
1194
+ CLIENT_IDS.some(
1195
+ id =>
1196
+ binding(id).enabled &&
1197
+ plan(id).models.some(
1198
+ model => model.source_id.startsWith("api_") || (id !== "codex" && settings.claude_private_keys)
1199
+ )
1200
+ )
1201
+ )
1202
+ keys = readClientGatewayKeys({ ...options, create: false });
443
1203
  },
444
1204
  exportPrivateState: () => {
445
- const credentials = secrets.exportState?.(settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)) || [];
446
- return { credentials, bytes: credentials.reduce((sum, [ref, key]) => sum + 2 * Buffer.byteLength(ref + key) + 64, 0) };
1205
+ const credentials =
1206
+ secrets.exportState?.(
1207
+ settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)
1208
+ ) || [];
1209
+ return {
1210
+ credentials,
1211
+ bytes: credentials.reduce((sum, [ref, key]) => sum + 2 * Buffer.byteLength(ref + key) + 64, 0),
1212
+ };
447
1213
  },
448
- importPrivateState: state => secrets.importState?.(state?.credentials || [], settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)),
449
- busy: () => operations > 0 || active.size > 0 || Boolean(syncFlight) || catalogRefresh.busy() || legacy.snapshot().m365.account_change_in_flight === true || legacy.snapshot().m365.state === "checking",
1214
+ importPrivateState: state =>
1215
+ secrets.importState?.(
1216
+ state?.credentials || [],
1217
+ settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)
1218
+ ),
1219
+ busy: () =>
1220
+ operations > 0 ||
1221
+ active.size > 0 ||
1222
+ Boolean(syncFlight) ||
1223
+ catalogRefresh.busy() ||
1224
+ legacy.snapshot().m365.account_change_in_flight === true ||
1225
+ legacy.snapshot().m365.state === "checking",
450
1226
  syncClients,
451
1227
  async manageConnections(input) {
452
- if (!input) { if (binding("codex").enabled) void memoryModel.refresh();return snapshot(); }
1228
+ if (!input) {
1229
+ if (binding("codex").enabled) void memoryModel.refresh();
1230
+ return snapshot();
1231
+ }
453
1232
  if (validObject(input, ["operation", "id"]) && input.operation === "source_catalog") {
454
- if (!["github", "m365", ...settings.apis.map(api => api.id)].includes(input.id)) throw accessError("ccdx_connections_action_invalid");
455
- const source = getSource(input.id), raw = source?.catalog?.() || source?.registry?.models?.data;
456
- return { source: input.id, loaded: Array.isArray(raw), evidence: input.id.startsWith("api_") ? "configured" : "cached", access_checked: false,
457
- models: publicModelCatalog(raw || []).map(({ selectable, clients, ...model }) => model) };
1233
+ if (!["github", "m365", ...settings.apis.map(api => api.id)].includes(input.id))
1234
+ throw accessError("ccdx_connections_action_invalid");
1235
+ const source = getSource(input.id),
1236
+ raw = source?.catalog?.() || source?.registry?.models?.data;
1237
+ return {
1238
+ source: input.id,
1239
+ loaded: Array.isArray(raw),
1240
+ evidence: input.id.startsWith("api_") ? "configured" : "cached",
1241
+ access_checked: false,
1242
+ models: publicModelCatalog(raw || []).map(({ selectable, clients, ...model }) => model),
1243
+ };
458
1244
  }
459
1245
  if (validObject(input, ["operation", "id"]) && input.operation === "discover") {
460
- const models = await catalogRefresh.refresh(input.id, true);return { ...snapshot(), discovered: models };
1246
+ const models = await catalogRefresh.refresh(input.id, true);
1247
+ return { ...snapshot(), discovered: models };
1248
+ }
1249
+ if (validObject(input, ["operation", "id"]) && input.operation === "cancel_discovery") {
1250
+ catalogRefresh.cancel(input.id);
1251
+ return snapshot();
461
1252
  }
462
- if (validObject(input, ["operation", "id"]) && input.operation === "cancel_discovery") { catalogRefresh.cancel(input.id);return snapshot(); }
463
1253
  const result = await enqueue(() => change(input));
464
1254
  if (input.operation === "save_api") {
465
- const id = input.id || result.providers.find(api => !api.builtin && api.name === input.config.name)?.id;
1255
+ const id =
1256
+ input.id || result.providers.find(api => !api.builtin && api.name === input.config.name)?.id;
466
1257
  if (enabled(id)) void catalogRefresh.refresh(id).catch(() => {});
467
- } else if (input.operation === "provider" && input.enabled && input.id?.startsWith("api_")) void catalogRefresh.refresh(input.id).catch(() => {});
1258
+ } else if (input.operation === "provider" && input.enabled && input.id?.startsWith("api_"))
1259
+ void catalogRefresh.refresh(input.id).catch(() => {});
468
1260
  return input.operation === "save_api" ? snapshot() : result;
469
1261
  },
470
- async start() { if (binding("codex").enabled) void memoryModel.refresh();const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();void refreshApis();return result; },
471
- async refresh() { const result = await Promise.allSettled([!managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(), refreshApis()]);if (result[0].status === "rejected") throw result[0].reason; },
472
- selection() { return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null }; },
1262
+ async start() {
1263
+ if (binding("codex").enabled) void memoryModel.refresh();
1264
+ const old = legacy.start();
1265
+ if (managed) await syncClients();
1266
+ const result = await old;
1267
+ if (managed) await syncClients();
1268
+ void refreshApis();
1269
+ return result;
1270
+ },
1271
+ async refresh() {
1272
+ const result = await Promise.allSettled([
1273
+ !managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(),
1274
+ refreshApis(),
1275
+ ]);
1276
+ if (result[0].status === "rejected") throw result[0].reason;
1277
+ },
1278
+ selection() {
1279
+ return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null };
1280
+ },
473
1281
  providerPreference(id) {
474
1282
  const c = settings.clients.codex;
475
- 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;
1283
+ return managed && c.source === id && c.auto_review_model
1284
+ ? {
1285
+ ...c,
1286
+ auto_review_model:
1287
+ plan("codex").routes.get(c.auto_review_model)?.upstreamModel || c.auto_review_model,
1288
+ }
1289
+ : legacy.selection().m365;
476
1290
  },
477
1291
  snapshot() {
478
- const result = legacy.snapshot();if (!managed) return result;
479
- const performance = legacy.claudePerformance.snapshot(), totals = performance.by_route.messages.terminal_outcomes.totals;
1292
+ const result = legacy.snapshot();
1293
+ if (!managed) return result;
1294
+ const performance = legacy.claudePerformance.snapshot(),
1295
+ totals = performance.by_route.messages.terminal_outcomes.totals;
480
1296
  const ms = performance.by_route.messages.by_provider.m365;
481
- const m365Requests = ms ? { ...ms.terminal_outcomes.totals, active: ms.active, total: ms.requests,
482
- performance: { by_route: { messages: { by_provider: { m365: ms }, terminal_outcomes: ms.terminal_outcomes } },
483
- active_total: ms.active, active_requests: performance.active_requests.filter(row => row.provider === "m365"),
484
- recent_requests: performance.recent_requests.filter(row => row.provider === "m365") } } : null;
485
- return { ...result, codex_provider: this.selection().codex, connections: snapshot(true),
486
- m365: { ...result.m365, ...(binding("codex").source === "m365" ? { preference: this.providerPreference(binding("codex").source) } : {}), claude: { ...result.m365.claude, requests: m365Requests,
487
- 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"])) } },
488
- 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",
1297
+ const m365Requests = ms
1298
+ ? {
1299
+ ...ms.terminal_outcomes.totals,
1300
+ active: ms.active,
1301
+ total: ms.requests,
1302
+ performance: {
1303
+ by_route: { messages: { by_provider: { m365: ms }, terminal_outcomes: ms.terminal_outcomes } },
1304
+ active_total: ms.active,
1305
+ active_requests: performance.active_requests.filter(row => row.provider === "m365"),
1306
+ recent_requests: performance.recent_requests.filter(row => row.provider === "m365"),
1307
+ },
1308
+ }
1309
+ : null;
1310
+ return {
1311
+ ...result,
1312
+ codex_provider: this.selection().codex,
1313
+ connections: snapshot(true),
1314
+ m365: {
1315
+ ...result.m365,
1316
+ ...(binding("codex").source === "m365"
1317
+ ? { preference: this.providerPreference(binding("codex").source) }
1318
+ : {}),
1319
+ claude: {
1320
+ ...result.m365.claude,
1321
+ requests: m365Requests,
1322
+ clients: Object.fromEntries(
1323
+ [
1324
+ ["app", "claude_app"],
1325
+ ["code", "claude_code"],
1326
+ ].map(([short, id]) => [
1327
+ short,
1328
+ binding(id).enabled && binding(id).source === "m365"
1329
+ ? setup[id] || result.m365.claude.clients[short]
1330
+ : "not_selected",
1331
+ ])
1332
+ ),
1333
+ },
1334
+ },
1335
+ claude: {
1336
+ base_url: `http://127.0.0.1:${corePort}/anthropic`,
1337
+ gateway: CLIENT_IDS.some(
1338
+ id => id !== "codex" && binding(id).enabled && permitted(id, binding(id).source)
1339
+ )
1340
+ ? "running"
1341
+ : "unavailable",
489
1342
  clients: { app: setup.claude_app || "not_configured", code: setup.claude_code || "not_configured" },
490
- requests: { ...totals, active: performance.active_total, total: Object.values(totals).reduce((sum, value) => sum + value, 0) + performance.active_total, performance } },
491
- ...Object.fromEntries(settings.apis.map(api => [api.id, { preference: this.providerPreference(binding("codex").source) }])) };
1343
+ requests: {
1344
+ ...totals,
1345
+ active: performance.active_total,
1346
+ total: Object.values(totals).reduce((sum, value) => sum + value, 0) + performance.active_total,
1347
+ performance,
1348
+ },
1349
+ },
1350
+ ...Object.fromEntries(
1351
+ settings.apis.map(api => [api.id, { preference: this.providerPreference(binding("codex").source) }])
1352
+ ),
1353
+ };
492
1354
  },
493
1355
  current(req) {
494
1356
  if (!managed) return legacy.current();
495
1357
  const mode = codexAccessMode();
496
1358
  if (mode === "paused" || mode === "disabled") throw accessError("ccdx_client_source_disabled", 503);
497
- const c = binding("codex"), compiled = plan("codex");
1359
+ const c = binding("codex"),
1360
+ compiled = plan("codex");
498
1361
  if (Array.isArray(c.deployments) && req?.method === "GET") {
499
1362
  if (codexRequiresKey()) requireCodexKey(req);
500
- return { id: "connections", registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
501
- client: { listModels: async () => ({ status: 200, body: JSON.stringify({ data: compiled.models.map(model => ({ ...model, id: model.public_id })) }) }) },
502
- codexCatalog: codexClientCatalog(compiled) };
1363
+ return {
1364
+ id: "connections",
1365
+ registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
1366
+ client: {
1367
+ listModels: async () => ({
1368
+ status: 200,
1369
+ body: JSON.stringify({
1370
+ data: compiled.models.map(model => ({ ...model, id: model.public_id })),
1371
+ }),
1372
+ }),
1373
+ },
1374
+ codexCatalog: codexClientCatalog(compiled),
1375
+ };
503
1376
  }
504
1377
  if (Array.isArray(c.deployments) && compiled.defaultUnavailable) {
505
1378
  if (req && codexRequiresKey()) requireCodexKey(req);
@@ -507,29 +1380,44 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
507
1380
  // explicitly requested model before any provider request is opened.
508
1381
  return null;
509
1382
  }
510
- const source = requireSource("codex", Array.isArray(c.deployments) ? compiled.routes.get(compiled.defaultModel)?.source : c.source);
1383
+ const source = requireSource(
1384
+ "codex",
1385
+ Array.isArray(c.deployments) ? compiled.routes.get(compiled.defaultModel)?.source : c.source
1386
+ );
511
1387
  if (source?.id.startsWith("api_") && req) requireCodexKey(req);
512
- return req?.method === "GET" && source?.configuredModels && source.id.startsWith("api_") ? { ...source, codexCatalog: codexSourceCatalog(source) } : source;
1388
+ return req?.method === "GET" && source?.configuredModels && source.id.startsWith("api_")
1389
+ ? { ...source, codexCatalog: codexSourceCatalog(source) }
1390
+ : source;
1391
+ },
1392
+ hasModelBindings(client = "codex") {
1393
+ return managed && Array.isArray(binding(client).deployments);
513
1394
  },
514
- hasModelBindings(client = "codex") { return managed && Array.isArray(binding(client).deployments); },
515
1395
  resolveCodex(body, req) {
516
1396
  if (!managed) return null;
517
1397
  const mode = codexAccessMode();
518
1398
  if (mode === "paused" || mode === "disabled") throw accessError("ccdx_client_source_disabled", 503);
519
1399
  if (!Array.isArray(binding("codex").deployments)) return null;
520
1400
  if (codexRequiresKey()) requireCodexKey(req);
521
- const requested = body.model === "codex-auto-review" ? binding("codex").auto_review_model || plan("codex").defaultModel : body.model;
1401
+ const requested =
1402
+ body.model === "codex-auto-review"
1403
+ ? binding("codex").auto_review_model || plan("codex").defaultModel
1404
+ : body.model;
522
1405
  if (body.model === "codex-auto-review") {
523
1406
  delete body.service_tier;
524
- if (binding("codex").auto_review_effort) body.reasoning = { ...body.reasoning, effort: binding("codex").auto_review_effort };
1407
+ if (binding("codex").auto_review_effort)
1408
+ body.reasoning = { ...body.reasoning, effort: binding("codex").auto_review_effort };
525
1409
  }
526
- const record = resolveDeployment("codex", requested), context = currentRequestContext();
1410
+ const record = resolveDeployment("codex", requested),
1411
+ context = currentRequestContext();
527
1412
  if (context) {
528
- context.finishProvider?.();context.finishProvider = track(record.provider);context.provider = record.provider.id;
1413
+ context.finishProvider?.();
1414
+ context.finishProvider = track(record.provider);
1415
+ context.provider = record.provider.id;
529
1416
  context.streamPerformance?.setProvider?.(record.provider.id);
530
1417
  Object.assign(context, this.historyContext(req.headers, record.provider));
531
1418
  }
532
- body.model = record.upstreamModel;return record.provider;
1419
+ body.model = record.upstreamModel;
1420
+ return record.provider;
533
1421
  },
534
1422
  track,
535
1423
  validateConversation,
@@ -540,81 +1428,224 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
540
1428
  return { historyNamespace: target.profileId() };
541
1429
  },
542
1430
  async handleClaude(req, res) {
543
- if (!managed) { if (!legacyClaudeAccess) throw accessError("ccdx_client_source_disabled", 503);return legacy.handleClaude(req, res); }
1431
+ if (!managed) {
1432
+ if (!legacyClaudeAccess) throw accessError("ccdx_client_source_disabled", 503);
1433
+ return legacy.handleClaude(req, res);
1434
+ }
544
1435
  if (!settings.claude_private_keys) {
545
- if (["claude_app", "claude_code"].every(id => permitted(id, "m365") && binding(id).source === "m365")) return legacy.handleClaude(req, res);
1436
+ if (["claude_app", "claude_code"].every(id => permitted(id, "m365") && binding(id).source === "m365"))
1437
+ return legacy.handleClaude(req, res);
546
1438
  throw accessError("ccdx_client_source_disabled", 503);
547
1439
  }
548
1440
  const id = gatewayClient(req.headers, identities());
549
1441
  if (!id || id === "codex") throw accessError("ccdx_client_credential_required", 401);
550
- const compiled = plan(id);if (!binding(id).enabled || !compiled.models.length) throw accessError("ccdx_client_source_disabled", 503);
1442
+ const compiled = plan(id);
1443
+ if (!binding(id).enabled || !compiled.models.length)
1444
+ throw accessError("ccdx_client_source_disabled", 503);
551
1445
  // A request resolves once after its bounded body read. Its source and
552
1446
  // capability snapshot stay pinned while catalogs/configuration change.
553
1447
  const catalog = { id: "connections", configuredModels: true, models: () => compiled.models };
554
1448
  let cached = handlers.get(id);
555
1449
  if (cached?.compiled !== compiled) {
556
- const handler = createClaudeGatewayHandler({ provider: catalog, acquireRequest: acquireClaudeRequest, apiKey: identities()[id], env, log, performance: legacy.claudePerformance,
557
- desktopAliases: id === "claude_app",
558
- resolveRequest(body) {
559
- const record = resolveDeployment(id, body.model), finish = track(record.provider);
560
- return { provider: record.provider, model: record.upstreamModel, capability: record.model.capability, finish };
561
- },
562
- validateConversation: (body, headers, source) => validateConversation(body, headers, source, id),
563
- onRequest() { lastClients[id] = new Date().toISOString(); } });
564
- cached = { compiled, handler };handlers.set(id, cached);
1450
+ const handler = createClaudeGatewayHandler({
1451
+ provider: catalog,
1452
+ acquireRequest: acquireClaudeRequest,
1453
+ apiKey: identities()[id],
1454
+ env,
1455
+ log,
1456
+ performance: legacy.claudePerformance,
1457
+ desktopAliases: id === "claude_app",
1458
+ resolveRequest(body) {
1459
+ const record = resolveDeployment(id, body.model),
1460
+ finish = track(record.provider);
1461
+ return {
1462
+ provider: record.provider,
1463
+ model: record.upstreamModel,
1464
+ capability: record.model.capability,
1465
+ finish,
1466
+ };
1467
+ },
1468
+ validateConversation: (body, headers, source) => validateConversation(body, headers, source, id),
1469
+ onRequest() {
1470
+ lastClients[id] = new Date().toISOString();
1471
+ },
1472
+ });
1473
+ cached = { compiled, handler };
1474
+ handlers.set(id, cached);
1475
+ }
1476
+ const headers = req.headers;
1477
+ req.headers = { ...headers, "x-ccdx-client": id === "claude_app" ? "claude-app" : "claude-code" };
1478
+ try {
1479
+ return await cached.handler(req, res);
1480
+ } finally {
1481
+ req.headers = headers;
565
1482
  }
566
- const headers = req.headers;req.headers = { ...headers, "x-ccdx-client": id === "claude_app" ? "claude-app" : "claude-code" };
567
- try { return await cached.handler(req, res); } finally { req.headers = headers; }
568
1483
  },
569
1484
  dashboardProviders() {
570
- const builtins = legacy.dashboardProviders();if (!managed) return builtins.filter(source => source.enabled);
571
- const definitions = snapshot(true).providers, performance = legacy.claudePerformance.snapshot();
572
- return definitions.filter(item => item.enabled).map(item => {
573
- const old = builtins.find(source => source.id === item.id), source = item.builtin ? null : getSource(item.id);
574
- const clients = CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(item.id)
575
- && (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,
576
- 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 }));
577
- return { ...old, id: item.id, name: item.name, enabled: true, generation: old?.generation || source?.registry.generation || 1,
578
- state: old?.state || "configured", auth: old?.auth || { state: "saved", token_cached: false },
579
- selection: { codex: clients.some(client => client.id === "codex"), models_required: item.id !== "github" }, clients,
580
- models: old?.models || { count: item.model_count, source: "configured" },
581
- requests: performance.by_route.messages.by_provider[item.id] ? { ...performance.by_route.messages.by_provider[item.id].terminal_outcomes.totals,
582
- active: performance.by_route.messages.by_provider[item.id].active, total: performance.by_route.messages.by_provider[item.id].requests } : null };
583
- });
1485
+ const builtins = legacy.dashboardProviders();
1486
+ if (!managed) return builtins.filter(source => source.enabled);
1487
+ const definitions = snapshot(true).providers,
1488
+ performance = legacy.claudePerformance.snapshot();
1489
+ return definitions
1490
+ .filter(item => item.enabled)
1491
+ .map(item => {
1492
+ const old = builtins.find(source => source.id === item.id),
1493
+ source = item.builtin ? null : getSource(item.id);
1494
+ const clients = CLIENT_IDS.filter(
1495
+ id =>
1496
+ binding(id).enabled &&
1497
+ binding(id).allowed.includes(item.id) &&
1498
+ (id === "codex" ? item.protocols.includes("responses") : item.protocols.includes("messages"))
1499
+ ).map(id => ({
1500
+ id,
1501
+ name: CLIENT_NAMES[id],
1502
+ selected:
1503
+ binding(id).deployments?.some(model => model.source === item.id) ||
1504
+ binding(id).source === item.id,
1505
+ state: setup[id] || old?.clients?.find(client => client.id === id)?.state || "unknown",
1506
+ gateway:
1507
+ binding(id).deployments?.some(model => model.source === item.id) ||
1508
+ binding(id).source === item.id
1509
+ ? "running"
1510
+ : "standby",
1511
+ last_request_at: lastClients[id] || null,
1512
+ }));
1513
+ return {
1514
+ ...old,
1515
+ id: item.id,
1516
+ name: item.name,
1517
+ enabled: true,
1518
+ generation: old?.generation || source?.registry.generation || 1,
1519
+ state: old?.state || "configured",
1520
+ auth: old?.auth || { state: "saved", token_cached: false },
1521
+ selection: {
1522
+ codex: clients.some(client => client.id === "codex"),
1523
+ models_required: item.id !== "github",
1524
+ },
1525
+ clients,
1526
+ models: old?.models || { count: item.model_count, source: "configured" },
1527
+ requests: performance.by_route.messages.by_provider[item.id]
1528
+ ? {
1529
+ ...performance.by_route.messages.by_provider[item.id].terminal_outcomes.totals,
1530
+ active: performance.by_route.messages.by_provider[item.id].active,
1531
+ total: performance.by_route.messages.by_provider[item.id].requests,
1532
+ }
1533
+ : null,
1534
+ };
1535
+ });
584
1536
  },
585
1537
  dashboardCatalog(input = {}) {
586
1538
  if (!input.provider?.startsWith("api_")) return legacy.dashboardCatalog(input);
587
1539
  if (!enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
588
- return getSource(input.provider).publicCatalog(CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider)));
1540
+ return getSource(input.provider).publicCatalog(
1541
+ CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider))
1542
+ );
589
1543
  },
590
1544
  async action(input) {
591
1545
  if (managed && input.action === "auto-review" && Array.isArray(binding("codex").deployments)) {
592
- const c = binding("codex"), compiled = plan("codex");
1546
+ const c = binding("codex"),
1547
+ compiled = plan("codex");
593
1548
  if (!c.enabled || input.provider !== c.source) throw accessError("ccdx_client_source_mismatch", 409);
594
- const record = [...compiled.routes.values()].find(record => record.source === input.provider && record.upstreamModel === input.model);
1549
+ const record = [...compiled.routes.values()].find(
1550
+ record => record.source === input.provider && record.upstreamModel === input.model
1551
+ );
595
1552
  if (!record) throw accessError("ccdx_api_model_unavailable");
596
- if (input.effort && !record.model.capability.values.reasoning_efforts?.includes(input.effort)) throw accessError("ccdx_api_effort_unavailable");
597
- 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();
1553
+ if (input.effort && !record.model.capability.values.reasoning_efforts?.includes(input.effort))
1554
+ throw accessError("ccdx_api_effort_unavailable");
1555
+ const next = editable();
1556
+ next.clients.codex.auto_review_model = record.model.route_id;
1557
+ next.clients.codex.auto_review_effort = input.effort || null;
1558
+ save(next);
1559
+ return this.snapshot();
598
1560
  }
599
- if (managed && input.action === "auto-review" && input.provider && input.provider !== this.selection().codex) throw accessError("ccdx_client_source_mismatch", 409);
600
- if (managed && input.action === "auto-review" && (!binding("codex").enabled || !binding("codex").source)) throw accessError("ccdx_client_source_disabled", 503);
1561
+ if (
1562
+ managed &&
1563
+ input.action === "auto-review" &&
1564
+ input.provider &&
1565
+ input.provider !== this.selection().codex
1566
+ )
1567
+ throw accessError("ccdx_client_source_mismatch", 409);
1568
+ if (
1569
+ managed &&
1570
+ input.action === "auto-review" &&
1571
+ (!binding("codex").enabled || !binding("codex").source)
1572
+ )
1573
+ throw accessError("ccdx_client_source_disabled", 503);
601
1574
  if (managed && ["on", "off", "remove"].includes(input.action)) {
602
- if (input.action === "remove" && legacy.snapshot().m365.active_requests > 0) throw accessError("ccdx_source_busy", 409);
603
- const replacements = Object.fromEntries(CLIENT_IDS.filter(id => binding(id).source === "m365" && binding(id).enabled).map(id => [id, null]));
604
- await this.manageConnections({ operation: "provider", id: "m365", enabled: input.action === "on", replacements });
605
- if (input.action === "remove") legacy.removeM365SavedProfile();return this.snapshot();
1575
+ if (input.action === "remove" && legacy.snapshot().m365.active_requests > 0)
1576
+ throw accessError("ccdx_source_busy", 409);
1577
+ const replacements = Object.fromEntries(
1578
+ CLIENT_IDS.filter(id => binding(id).source === "m365" && binding(id).enabled).map(id => [id, null])
1579
+ );
1580
+ await this.manageConnections({
1581
+ operation: "provider",
1582
+ id: "m365",
1583
+ enabled: input.action === "on",
1584
+ replacements,
1585
+ });
1586
+ if (input.action === "remove") legacy.removeM365SavedProfile();
1587
+ return this.snapshot();
606
1588
  }
607
- if (managed && input.action === "switch" && !binding("codex").enabled) throw accessError("ccdx_client_source_disabled", 503);
1589
+ if (managed && input.action === "switch" && !binding("codex").enabled)
1590
+ throw accessError("ccdx_client_source_disabled", 503);
608
1591
  const { history_isolation, ...clientInput } = binding("codex");
609
- if (input.action === "switch" && input.provider?.startsWith("api_")) { await this.manageConnections({ operation: "client", id: "codex", ...clientInput, deployments: null, default_model: null, source: input.provider,
610
- model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort });return this.snapshot(); }
611
- 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(); }
612
- if (input.action === "auto-review" && managed && legacy.selection().codex !== "github") await legacy.action({ action: "switch", provider: "github" });
613
- if (managed && input.action === "switch" && !enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
1592
+ if (input.action === "switch" && input.provider?.startsWith("api_")) {
1593
+ await this.manageConnections({
1594
+ operation: "client",
1595
+ id: "codex",
1596
+ ...clientInput,
1597
+ deployments: null,
1598
+ default_model: null,
1599
+ source: input.provider,
1600
+ model: input.model,
1601
+ auto_review_model: input.auto_review_model,
1602
+ auto_review_effort: input.auto_review_effort,
1603
+ });
1604
+ return this.snapshot();
1605
+ }
1606
+ if (input.action === "auto-review" && managed && binding("codex").source !== "github") {
1607
+ await this.manageConnections({
1608
+ operation: "client",
1609
+ id: "codex",
1610
+ ...clientInput,
1611
+ auto_review_model: input.model,
1612
+ auto_review_effort: input.effort,
1613
+ });
1614
+ return this.snapshot();
1615
+ }
1616
+ if (input.action === "auto-review" && managed && legacy.selection().codex !== "github")
1617
+ await legacy.action({ action: "switch", provider: "github" });
1618
+ if (managed && input.action === "switch" && !enabled(input.provider))
1619
+ throw accessError("ccdx_client_source_disabled", 503);
614
1620
  const result = await legacy.action(input);
615
- if (managed && input.action === "switch") { const next = editable();if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;next.clients.codex.allowed = [...new Set([...next.clients.codex.allowed, input.provider])];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(["codex"]); }
1621
+ if (managed && input.action === "switch") {
1622
+ const next = editable();
1623
+ if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;
1624
+ next.clients.codex.allowed = [...new Set([...next.clients.codex.allowed, input.provider])];
1625
+ next.clients.codex.source = input.provider;
1626
+ next.clients.codex.deployments = null;
1627
+ next.clients.codex.default_model = null;
1628
+ for (const key of ["model", "auto_review_model", "auto_review_effort"])
1629
+ delete next.clients.codex[key];
1630
+ if (input.provider === "m365") Object.assign(next.clients.codex, legacy.selection().m365);
1631
+ save(next);
1632
+ await syncClients(["codex"]);
1633
+ }
616
1634
  return result;
617
1635
  },
618
- async close() { closed = true;await memoryModel.close();await catalogRefresh.close();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(); },
1636
+ async close() {
1637
+ closed = true;
1638
+ await memoryModel.close();
1639
+ await catalogRefresh.close();
1640
+ await serial;
1641
+ await syncFlight;
1642
+ for (const { source } of instances.values()) source.close();
1643
+ for (const source of retired) source.close();
1644
+ active.clear();
1645
+ for (const id of retiredSecrets.keys()) cleanSecrets(id);
1646
+ await Promise.allSettled([...cleanups]);
1647
+ secrets.close();
1648
+ await legacy.close();
1649
+ },
619
1650
  };
620
1651
  }