codex-copilot-dx 1.2.32 → 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 (48) hide show
  1. package/README.md +65 -113
  2. package/bin/cli.mjs +61 -103
  3. package/docs/ARCHITECTURE.md +51 -3
  4. package/docs/README.md +9 -76
  5. package/docs/REFERENCE.md +137 -1827
  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 +325 -0
  15. package/src/cli-image.mjs +4 -4
  16. package/src/cli-limits.mjs +2 -2
  17. package/src/cli-m365.mjs +1 -1
  18. package/src/cli-management.mjs +344 -0
  19. package/src/cli-options.mjs +73 -443
  20. package/src/cli-status.mjs +7 -7
  21. package/src/cli-tools.mjs +3 -2
  22. package/src/client-integration.mjs +7 -3
  23. package/src/config.mjs +4 -3
  24. package/src/connection-runtime.mjs +1414 -350
  25. package/src/copilot-token-session.mjs +1 -1
  26. package/src/dashboard/connections.js +23 -4
  27. package/src/dashboard/ui.css +9 -2
  28. package/src/dashboard-api.mjs +5 -5
  29. package/src/doctor.mjs +4 -4
  30. package/src/image-mcp.mjs +2 -2
  31. package/src/native-prediction-fix.mjs +1 -1
  32. package/src/native-prediction-profile.mjs +1 -1
  33. package/src/native-prediction-windows.mjs +1 -1
  34. package/src/native-prediction.mjs +6 -6
  35. package/src/nightly-update.mjs +2 -2
  36. package/src/provider-runtime.mjs +1 -1
  37. package/src/providers/m365-accounts.mjs +1 -1
  38. package/src/release-install.mjs +11 -15
  39. package/src/service-control.mjs +1 -1
  40. package/src/settings-preferences.mjs +6 -4
  41. package/src/startup-ui.mjs +34 -2
  42. package/src/terminal-console.mjs +32 -30
  43. package/src/terminal-state.mjs +69 -0
  44. package/src/usage.mjs +5 -5
  45. package/src/windows-command.mjs +2 -2
  46. package/bin/codex-copilot-dx.mjs +0 -11
  47. package/src/cli-models.mjs +0 -94
  48. package/src/legacy-command-warning.mjs +0 -38
@@ -1,14 +1,28 @@
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";
14
+ import { publicModelCatalog } from "./provider-metadata.mjs";
5
15
  import { createApiCatalogRefresh } from "./api-catalog-refresh.mjs";
6
16
  import { createApiProvider } from "./providers/api.mjs";
7
17
  import { createApiModelDisplayStore } from "./api-model-display.mjs";
8
18
  import { createCodexMemoryModel } from "./codex-memory-model.mjs";
9
19
  import { readClientGatewayKeys, gatewayClient } from "./client-gateway-keys.mjs";
10
20
  import { createClaudeGatewayHandler } from "./claude-gateway.mjs";
11
- import { configureClaudeClients, restoreClaudeClients, inspectClaudeDesktopPolicy } from "./claude-client-config.mjs";
21
+ import {
22
+ configureClaudeClients,
23
+ restoreClaudeClients,
24
+ inspectClaudeDesktopPolicy,
25
+ } from "./claude-client-config.mjs";
12
26
  import { configureCodexApi } from "./codex-api-config.mjs";
13
27
  import { autoReviewReasoningEfforts } from "./models.mjs";
14
28
  import { createRequestAdmission } from "./request-admission.mjs";
@@ -17,43 +31,121 @@ import { createMessagesHistoryTransfer } from "./messages-history-transfer.mjs";
17
31
  import { compileClientModels, sourceModels } from "./client-model-plan.mjs";
18
32
  import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.mjs";
19
33
  import { currentRequestContext } from "./request-context.mjs";
20
- 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";
21
40
  import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from "./model-capabilities.mjs";
22
41
  import { m365Paths } from "./m365-settings.mjs";
23
42
 
24
- const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
25
- export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
26
- secretStore, createApi = createApiProvider, configureClaude = configureClaudeClients, restoreClaude = restoreClaudeClients,
27
- configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, preserveClientConfiguration, now = Date.now, log = () => {} } = {}) {
28
- const options = { home, env, platform, preserveClientConfiguration }, secrets = secretStore || createApiSecretStore(options), modelDisplay = createApiModelDisplayStore(options);
29
- const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
30
- 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
+ });
31
74
  const memoryModel = createCodexMemoryModel({ ...options, corePort });
32
- 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;
33
80
  const legacyClaudeAccess = fs.existsSync(m365Paths(options).ownership);
34
- const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
35
- const retiredSecrets = new Map(), cleanups = new Set(), plans = new Map(), discoveries = new Map();
36
- 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,
37
97
  complete: api => modelDisplay.has(api.id, deploymentRevision(api, env)),
38
- revision: api => deploymentRevision(api, env), now,
98
+ revision: api => deploymentRevision(api, env),
99
+ now,
39
100
  commit: (...args) => enqueue(() => applyCatalog(...args)),
40
- onState: (id, state) => state ? discoveries.set(id, state) : discoveries.delete(id) });
101
+ onState: (id, state) => (state ? discoveries.set(id, state) : discoveries.delete(id)),
102
+ });
41
103
  const capabilitySupport = inspectClaudeCapabilitySupport(options);
42
- let sharedSync = null, syncFlight = null, syncAgain = false, operations = 0;const syncTargets = new Set();
104
+ let sharedSync = null,
105
+ syncFlight = null,
106
+ syncAgain = false,
107
+ operations = 0;
108
+ const syncTargets = new Set(),
109
+ manualTargets = new Set();
43
110
  function cleanSecrets(id) {
44
- const refs = retiredSecrets.get(id);if (!refs) return;
111
+ const refs = retiredSecrets.get(id);
112
+ if (!refs) return;
45
113
  for (const ref of refs) {
46
114
  if ([...active.keys()].some(source => sourceSecrets.get(source) === ref)) continue;
47
115
  refs.delete(ref);
48
- 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);
49
123
  }
50
124
  if (!refs.size) retiredSecrets.delete(id);
51
125
  }
52
- const identities = () => keys ||= readClientGatewayKeys(options);
53
- const enabled = id => id?.startsWith("api_") ? settings.apis.find(api => api.id === id)?.enabled === true : settings.providers[id] === true;
54
- const binding = id => managed ? settings.clients[id] : { ...settings.clients[id],
55
- allowed: settings.clients[id].allowed.filter(source => source !== "m365" || legacyClaudeAccess || id === "codex" && legacy.selection().codex === "m365"),
56
- 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
+ };
57
149
  // GitHub-only selections retain the existing native loopback access contract.
58
150
  // Any other deployment still requires the private per-client credential.
59
151
  function codexAccessMode() {
@@ -72,401 +164,1215 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
72
164
  // denial must not trigger recovery/replacement of that unrelated sign-in.
73
165
  throw accessError("ccdx_client_credential_required", req.headers?.authorization ? 403 : 401);
74
166
  }
75
- 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);
76
169
  function getSource(id) {
77
170
  if (!id?.startsWith("api_")) return legacy.source(id);
78
- const config = settings.apis.find(value => value.id === id);if (!config) return null;
79
- 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;
80
176
  const signature = JSON.stringify(config) + revision;
81
177
  if (previous?.signature === signature) return previous.source;
82
- 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);
83
- 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;
84
189
  }
85
190
  function plan(id) {
86
- const selected = binding(id), definitions = selected.allowed.filter(enabled).map(source => getSource(source)).filter(Boolean);
87
- const cached = plans.get(id), stamps = definitions.map(source => [source, source.registry?.generation, source.registry?.models, source.profileId()]);
88
- 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;
89
- const value = compileClientModels({ client: id, binding: selected, source: getSource, enabled,
90
- names: Object.fromEntries([["github", "GitHub Copilot"], ["m365", "Microsoft 365"], ...settings.apis.map(api => [api.id, api.name])]),
91
- desktopEffortAliases: capabilitySupport.app });
92
- 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;
93
223
  }
94
224
  function resolveDeployment(id, model) {
95
- const value = plan(id), record = value.routes.get(model);
225
+ const value = plan(id),
226
+ record = value.routes.get(model);
96
227
  if (!record) {
97
- const selected = binding(id), configured = selected.deployments || [{ source: selected.source, model: selected.model }];
98
- const matches = configured.filter(item => item.model === model || deploymentModelId(item.source, item.model) === model);
99
- const reason = !selected.enabled ? "ccdx_client_source_disabled" : matches.length > 1 ? "ccdx_model_ambiguous"
100
- : matches.length && !permitted(id, matches[0].source) ? "ccdx_client_source_disabled"
101
- : matches.length ? "ccdx_model_catalog_unavailable" : "ccdx_model_not_selected";
102
- const error = accessError("ccdx_api_model_unavailable");error.jsonBody.error.reason = reason;
103
- 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;
104
246
  }
105
247
  const provider = requireSource(id, record.source);
106
- 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
+ }
107
252
  return record;
108
253
  }
109
- 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
+ }
110
258
  function track(source) {
111
- 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;
112
262
  return () => {
113
- if (done) return;done = true;finishLegacy?.();const count = (active.get(source) || 1) - 1;
114
- 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
+ }
115
273
  };
116
274
  }
117
275
  function editable() {
118
276
  if (managed) return structuredClone(settings);
119
- 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;
120
279
  for (const id of CLIENT_IDS) next.clients[id] = { ...binding(id) };
121
280
  return next;
122
281
  }
123
282
  function save(next) {
124
283
  plans.clear();
125
- settings = structuredClone(updateAccessSettings(current => {
126
- if (JSON.stringify(current) !== JSON.stringify(settings)) throw accessError("ccdx_connections_conflict", 409);return next;
127
- }, 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();
128
293
  for (const [id, item] of instances) {
129
294
  const current = settings.apis.find(api => api.id === id);
130
- 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;
131
302
  }
132
303
  }
133
304
  function summary(api) {
134
- 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
+ });
135
311
  return summaries.get(api);
136
312
  }
137
- function snapshot(compact = false) {
138
- const state = legacy.snapshot(), config = managed ? settings : editable();
139
- return structuredClone({ source: "connections", providers: [
140
- { id: "github", name: "GitHub Copilot", enabled: config.providers.github, builtin: true, protocols: ["responses"] },
141
- { id: "m365", name: "Microsoft 365", enabled: config.providers.m365, builtin: true, protocols: ["messages", "responses"] },
142
- ...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),
143
- ...summary(api), ...(compact ? {} : { deployment_revision: revision,
144
- 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) }; }),
145
- ], 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,
146
319
  ...(id === "codex" ? { memory_model: memoryModel.snapshot() } : {}),
147
- observed_at: lastClients[id] || null, ...(compact ? {} : { model_plan: { default_model: plan(id).defaultModel, default_unavailable: plan(id).defaultUnavailable,
148
- 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 })),
149
- unavailable: (config.clients[id].deployments || []).filter(item => !plan(id).models.some(model => model.source_id === item.source && model.id === item.model))
150
- .map(item => ({ source: item.source, id: item.model, route_id: deploymentModelId(item.source, item.model) })),
151
- available: config.clients[id].allowed.filter(enabled).flatMap(source => sourceModels(getSource(source), id).map(model => ({ source, id: model.id,
152
- 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 } }) })),
153
- ...(!compact ? { source_impacts: Object.fromEntries(["github", "m365", ...config.apis.map(api => api.id)].map(id => [id, sourceImpact(id)])) } : {}), managed, 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
+ };
154
363
  }
155
- function sourceImpact(source) {
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
+ });
424
+ }
425
+ const clientRevision = id =>
426
+ createHash("sha256")
427
+ .update(JSON.stringify(binding(id)))
428
+ .digest("hex");
429
+ function sourceImpact(source, readPlan = plan) {
156
430
  const clients = CLIENT_IDS.flatMap(id => {
157
- const c = binding(id);if (!c.enabled) return [];
158
- 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) : [];
159
435
  if (explicit ? !removed.length : c.source !== source) return [];
160
436
  const remaining = explicit ? c.deployments.length - removed.length : 0;
161
- 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;
162
441
  const default_affected = defaultSource === source;
163
- 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
+ ];
164
451
  });
165
- const api = settings.apis.find(item => item.id === source), profile = api ? deploymentRevision(api, env) : getSource(source)?.profileId();
166
- 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
+ };
167
460
  }
168
- async function syncClients(ids = CLIENT_IDS) {
461
+ async function syncClients(ids = CLIENT_IDS, { manual = false } = {}) {
169
462
  if (!ids.length) return;
170
- for (const id of ids) syncTargets.add(id);
171
- syncAgain = true;if (syncFlight) return syncFlight;
172
- syncFlight = (async () => { do { syncAgain = false;const targets = new Set(syncTargets);syncTargets.clear();await performClientSync(targets); } while (syncAgain && !closed); })();
173
- 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
+ }
174
484
  }
175
- async function performClientSync(targets) {
176
- if (!managed || closed) return;
177
- if (options.preserveClientConfiguration?.()) { for (const id of targets) setup[id] = "preserved";return; }
178
- const codex = binding("codex"), compiledCodex = plan("codex");
179
- const explicit = Array.isArray(codex.deployments), mode = codexAccessMode(), native = mode === "native";
180
- 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 {
181
489
  if (mode === "paused" || mode === "disabled") {
182
- if (mode === "disabled" || codex.auto_sync !== false) configureCodex({ ...options, restore: true });
490
+ if (mode === "disabled" || codex.auto_sync !== false || requested.has("codex"))
491
+ configureCodex({ ...options, restore: true });
183
492
  setup.codex = mode;
184
- } else if (codex.auto_sync === false) setup.codex = "manual_sync";
185
- else if (codex.enabled && compiledCodex.defaultUnavailable && !native) setup.codex = "default_unavailable";
493
+ } else if (codex.auto_sync === false && !requested.has("codex")) setup.codex = "manual_sync";
494
+ else if (codex.enabled && compiledCodex.defaultUnavailable && !native)
495
+ setup.codex = "default_unavailable";
186
496
  else {
187
- setup.codex = configureCodex({ ...options, ...(codex.enabled && (native || explicit && codex.deployments.length || codex.source?.startsWith("api_"))
188
- ? { baseUrl: `http://127.0.0.1:${corePort}/v1`, native, ...(native ? { nativeModels: compiledCodex.models } : {}), ...(!native ? { apiKey: identities().codex } : {}),
189
- ...(explicit || !native ? { model: compiledCodex.defaultModel || (!compiledCodex.defaultUnavailable ? codex.model : undefined) } : {}) } : { restore: true }) }).state;
190
- 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";
191
518
  }
192
- } catch { setup.codex = "configuration_unavailable"; }
193
- if (!settings.claude_private_keys || !["claude_app", "claude_code"].some(id => targets.has(id))) return;
194
- let desktopManaged;
195
- for (const id of ["claude_app", "claude_code"]) {
196
- if (!targets.has(id)) continue;
197
- const selected = binding(id), compiled = plan(id), source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
198
- try {
199
- if (selected.enabled && compiled.defaultUnavailable) { setup[id] = "default_unavailable";continue; }
200
- if (!selected.enabled || !compiled.models.length) { const result = restoreClaude({ ...options, client: id });setup[id] = result.preserved ? "preserved" : "not_configured";continue; }
201
- if (selected.auto_sync === false) { setup[id] = "manual_sync";continue; }
202
- if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
203
- const m365Only = compiled.models.every(model => model.source_id === "m365");
204
- if (id === "claude_code" && !m365Only) restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
205
- const result = configureClaude({ ...options, client: id, profileName: "CCDX", desktopAliases: id === "claude_app" && source?.id.startsWith("api_"), disableExperimentalBetas: m365Only, desktopManaged: id === "claude_app" ? desktopManaged : false,
206
- baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: identities()[id], models: compiled.models, defaultModel: Array.isArray(selected.deployments) ? compiled.defaultModel : undefined });
207
- setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
208
- } catch { setup[id] = "configuration_unavailable"; }
519
+ } catch {
520
+ setup.codex = "configuration_unavailable";
209
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;
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) {
210
566
  if (["claude_app", "claude_code"].some(id => setup[id] === "default_unavailable")) {
211
- 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;
212
573
  }
213
574
  if (!["claude_app", "claude_code"].some(id => targets.has(id))) return;
214
- if (["claude_app", "claude_code"].some(id => !targets.has(id) && !setup[id] && binding(id).enabled && plan(id).models.length)) {
215
- 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;
216
582
  }
217
- const shared = claudeSharedCapabilityPlan({ app: setup.claude_app === "configured" ? plan("claude_app").models : [],
218
- 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
+ });
219
588
  if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
220
- 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 };
600
+ }
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
+ }
221
624
  }
222
- try { sharedSync = { ...shared, ...syncClaudeCapabilities(shared, options) }; }
223
- catch { sharedSync = { state: "configuration_unavailable", limitations: shared.limitations }; }
625
+ syncSharedClaudeCapabilities(targets);
224
626
  }
225
627
  function requireSource(clientId, id) {
226
628
  if (!permitted(clientId, id)) throw accessError("ccdx_client_source_disabled", 503);
227
- if (id === "m365" && legacy.snapshot().m365.account_change_in_flight) throw accessError("m365_account_busy", 409);
228
- 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;
229
634
  }
230
635
  function validateConversation(body, headers, source, client = "codex") {
231
636
  if (!body || typeof body !== "object" || Array.isArray(body)) return;
232
- if (managed && (binding(client).history_isolation || source?.id.startsWith("api_") || client === "claude_app")) {
233
- const transfer = client === "claude_app" ? {
234
- profiles: [...new Set(plan(client).models.map(model => model.source_id))].map(id => getSource(id).profileId("messages")),
235
- prepare: input => messagesTransfer.prepare({ ...input, countTokens: currentRequestContext()?.route === "messages_count_tokens" }),
236
- } : undefined;
237
- 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
+ );
238
662
  }
239
663
  }
240
664
  async function applyCatalog(id, models, revision, checkedAt, active) {
241
665
  if (!active()) throw accessError("ccdx_connections_conflict", 409);
242
- const next = editable(), current = next.apis.find(api => api.id === id);
243
- 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);
244
670
  const byId = new Map(models.map(model => [model.id, model]));
245
671
  let displayChanged = false;
246
- try { displayChanged = modelDisplay.set(id, revision, models); } catch { log("warn", "Model display metadata could not be saved; routing is unchanged"); }
247
- 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;
248
679
  current.checked_at = checkedAt;
249
680
  const changed = JSON.stringify(current) !== JSON.stringify(settings.apis.find(api => api.id === id));
250
681
  if (changed) save(next);
251
682
  if (changed || displayChanged) {
252
- 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
+ );
253
690
  }
254
691
  }
255
- function enqueue(work) { operations++;const job = serial.then(work).finally(() => { operations--; });serial = job.catch(() => {});return job; }
256
- const refreshApis = () => !closed && managed && !preserveClientConfiguration?.() ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id)) : Promise.resolve();
257
- async function change(input) {
258
- if (closed) throw accessError("ccdx_connections_closed", 503);
259
- 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"])) throw accessError("ccdx_connections_action_invalid");
260
- const next = editable();let freshRef, previousRef;
261
- if (input.operation === "source_access") {
262
- if (input.id !== "m365" || !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");
263
- const affected = CLIENT_IDS.filter(id => next.clients[id].allowed.includes(input.id) !== input.allowed.includes(id));
264
- const sharedClaude = ["claude_app", "claude_code"].filter(id => next.clients[id].enabled && next.clients[id].source === "m365");
265
- const migrateClaude = !next.claude_private_keys && sharedClaude.length > 0 && affected.some(id => id !== "codex");
266
- const targets = new Set();
267
- for (const id of affected) {
268
- const c = next.clients[id];
269
- c.allowed = [...c.allowed.filter(source => source !== input.id), ...(input.allowed.includes(id) ? [input.id] : [])];
270
- if (!input.allowed.includes(id)) {
271
- if (c.source === input.id || c.deployments?.some(item => item.source === input.id)) targets.add(id);
272
- if (c.source === input.id) c.source = null;
273
- if (Array.isArray(c.deployments)) c.deployments = c.deployments.filter(item => item.source !== input.id);
274
- c.history_isolation = true;
275
- }
276
- }
277
- if (migrateClaude) next.claude_private_keys = true;
278
- if (migrateClaude) for (const id of ["claude_app", "claude_code"]) if (next.clients[id].source === "m365") targets.add(id);
279
- save(next);await syncClients([...targets]);
280
- const retained = migrateClaude ? [...targets].filter(id => id !== "codex" && next.clients[id].enabled && next.clients[id].source === "m365") : [];
281
- return { ...snapshot(), client_refresh: retained.filter(id => setup[id] === "configured"),
282
- client_review: retained.filter(id => ["preserved", "partially_preserved", "manual_sync", "configuration_unavailable"].includes(setup[id])) };
283
- } else if (input.operation === "save_api") {
284
- const existing = next.apis.find(api => api.id === input.id);
285
- if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
286
- if (!validObject(input.config, ["name", "base_url", "endpoints", "auth_header", "models", "key_env", "model_display"])) throw accessError("ccdx_api_config_invalid");
287
- // Existing clients round-trip catalog data. New display-only fields must
288
- // remain readable without becoming editable connection configuration.
289
- const { model_display, ...editableConfig } = input.config;
290
- input = { ...input, config: { ...editableConfig, models: Array.isArray(editableConfig.models) ? editableConfig.models.map(model => {
291
- if (!model || typeof model !== "object" || Array.isArray(model)) return model;
292
- const { display, ...editable } = model;return editable;
293
- }) : editableConfig.models } };
294
- const id = existing?.id || "api_" + randomBytes(8).toString("hex");
295
- if (input.key !== undefined && input.key !== "") { checkedApiKey(input.key);freshRef = randomBytes(16).toString("hex"); }
296
- if (input.config.key_env && freshRef || !input.config.key_env && !freshRef && !existing?.secret_ref) throw accessError("ccdx_api_key_invalid");
297
- const config = checkedApi({ ...input.config, id, enabled: existing?.enabled ?? true, ...(!input.config.key_env ? { secret_ref: freshRef || existing.secret_ref } : {}) });
298
- if (!Array.isArray(input.allowed) || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
299
- for (const id of CLIENT_IDS) {
300
- const c = next.clients[id];if (c.deployments?.some(item => item.source === config.id && (!input.allowed.includes(id)
301
- || !config.models.some(model => model.id === item.model && model.protocols.includes(id === "codex" ? "responses" : "messages"))))) throw accessError("ccdx_source_in_use", 409);
302
- if (c.source === config.id && !input.allowed.includes(id)) throw accessError("ccdx_source_in_use", 409);
303
- if (c.source === config.id && c.enabled && !Array.isArray(c.deployments) && (!config.models.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages"))
304
- || 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");
305
- if (input.allowed.includes(id) && !config.endpoints[id === "codex" ? "responses" : "messages"]) throw accessError("ccdx_api_protocol_required");
306
- c.allowed = [...new Set([...c.allowed.filter(value => value !== config.id), ...(input.allowed.includes(id) ? [config.id] : [])])];
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;
307
745
  }
308
- if (existing) { previousRef = existing.secret_ref;next.apis[next.apis.indexOf(existing)] = config; } else next.apis.push(config);
746
+ }
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");
809
+ }
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)) {
309
900
  checkedAccessSettings(next);
310
- try { if (freshRef) await secrets.set(freshRef, input.key);save(next); } catch (error) { if (freshRef) await secrets.remove(freshRef).catch(() => {});throw error; }
311
- } else if (["client", "preview_client"].includes(input.operation)) {
312
- if (!CLIENT_IDS.includes(input.id) || typeof input.enabled !== "boolean" || !Array.isArray(input.allowed)
313
- || input.source !== null && input.source !== undefined && !input.allowed.includes(input.source)) throw accessError("ccdx_connections_action_invalid");
314
- 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];
315
- next.clients[input.id] = { ...retained, enabled: input.enabled, allowed: input.allowed, source: input.enabled ? input.source ?? old.source : null,
316
- ...(input.deployments !== undefined ? { deployments: input.deployments, default_model: input.default_model ?? null, auto_sync: input.auto_sync ?? true }
317
- : old.source !== input.source ? { deployments: null, default_model: null } : {}),
318
- ...(input.model ? { model: input.model } : {}), ...(input.auto_review_model ? { auto_review_model: input.auto_review_model } : {}),
319
- ...(input.auto_review_effort !== undefined ? { auto_review_effort: input.auto_review_effort } : {}) };
320
- if (input.id !== "codex") next.claude_private_keys = true;
321
- if (old.source !== input.source) next.clients[input.id].history_isolation = true;
322
- const c = next.clients[input.id];
323
- if (Array.isArray(input.deployments)) {
324
- checkedAccessSettings(next);
325
- for (const item of c.deployments || []) {
326
- if (!enabled(item.source) || !sourceModels(getSource(item.source), input.id).some(model => model.id === item.model)) throw accessError("ccdx_api_model_unavailable");
327
- }
328
- const names = Object.fromEntries(next.apis.map(api => [api.id, api.name]));
329
- const compiled = compileClientModels({ client: input.id, binding: c, source: getSource, enabled, names, desktopEffortAliases: capabilitySupport.app });
330
- if (c.default_model && !compiled.routes.has(c.default_model)) throw accessError("ccdx_api_model_unavailable");
331
- 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;
332
- c.history_isolation = true;
333
- if (input.id === "codex") {
334
- c.model = compiled.routes.get(c.default_model)?.upstreamModel;
335
- const review = compiled.routes.get(old.auto_review_model) || [...compiled.routes.values()].find(record => record.source === old.source && record.upstreamModel === old.auto_review_model);
336
- 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;
337
- if (review?.source === c.source && old.auto_review_effort !== undefined) c.auto_review_effort = old.auto_review_effort;else delete c.auto_review_effort;
338
- }
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");
339
907
  }
340
- if (c.source && !Array.isArray(input.deployments)) {
341
- if (!enabled(c.source)) throw accessError("ccdx_client_source_disabled", 503);
342
- const target = getSource(c.source), family = input.id === "codex" ? "gpt" : "claude";
343
- 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);
344
- if (input.id !== "codex" && c.source === "github" || c.source !== "github" && !target?.models(family).length) throw accessError("ccdx_api_model_unavailable");
345
- if (input.id === "codex" && c.source !== "github") {
346
- const previous = c.source === "m365" ? legacy.selection().m365 : null;
347
- 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;
348
- if (![c.model, c.auto_review_model].every(id => target.models("gpt").some(model => model.id === id))) throw accessError("ccdx_api_model_unavailable");
349
- const efforts = api ? sourceModels(target, "codex").find(model => model.id === c.auto_review_model)?.capability.values.reasoning_efforts || []
350
- : autoReviewReasoningEfforts(target.models("gpt").find(model => model.id === c.auto_review_model));
351
- if (c.auto_review_effort !== undefined && c.auto_review_effort !== null && !efforts.includes(c.auto_review_effort)) throw accessError("ccdx_api_effort_unavailable");
352
- }
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;
353
935
  }
354
- if (input.operation === "preview_client") {
355
- const proposed = compileClientModels({ client: input.id, binding: c, source: getSource, enabled, desktopEffortAliases: capabilitySupport.app });
356
- const shared = input.id === "codex" ? null : claudeSharedCapabilityPlan({ app: input.id === "claude_app" ? proposed.models : plan("claude_app").models,
357
- code: input.id === "claude_code" ? proposed.models : plan("claude_code").models, support: capabilitySupport });
358
- return { ...snapshot(), preview: { models: proposed.models.map(model => ({ source: model.source_id, id: model.id, public_id: model.public_id, capability: model.capability })),
359
- 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");
360
964
  }
361
- save(next);
362
- } else if (input.operation === "provider") {
363
- if (typeof input.enabled !== "boolean" || !["github", "m365", ...next.apis.map(api => api.id)].includes(input.id)) throw accessError("ccdx_connections_action_invalid");
364
- if (input.id === "m365" && input.enabled && env.CCDX_M365 === "0") throw accessError("ccdx_provider_environment_disabled", 409);
365
- if (input.id === "m365" && !input.enabled && legacy.snapshot().m365.claude.requests?.active > 0) throw accessError("ccdx_source_busy", 409);
366
- if (!input.enabled) {
367
- const impact = sourceImpact(input.id);
368
- if (input.impact_revision !== undefined && input.impact_revision !== impact.revision) throw accessError("ccdx_connections_conflict", 409);
369
- const affected = impact.clients.filter(client => client.needs_replacement).map(client => client.id);
370
- if (affected.some(id => id !== "codex")) next.claude_private_keys = true;
371
- if (affected.length && !validObject(input.replacements, affected)) throw accessError("ccdx_source_in_use", 409);
372
- for (const id of affected) {
373
- const replacement = input.replacements[id];
374
- 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");
375
- next.clients[id].source = replacement;
376
- next.clients[id].history_isolation = true;
377
- }
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;
378
1030
  }
379
- if (!input.enabled) for (const id of CLIENT_IDS) {
380
- const c = next.clients[id];if (!Array.isArray(c.deployments)) continue;
381
- 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;
382
1038
  c.deployments = c.deployments.filter(item => item.source !== input.id);
383
1039
  if (input.replacements && Object.hasOwn(input.replacements, id)) {
384
1040
  const replacement = input.replacements[id];
385
1041
  if (!replacement) c.deployments = [];
386
1042
  else if (!c.deployments.some(item => item.source === replacement)) {
387
- 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 });
388
1045
  }
389
- 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;
390
1049
  }
391
1050
  }
392
- 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;
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);
393
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);
394
1149
  if (input.id === "m365") {
395
1150
  if (input.enabled) await legacy.action({ action: "on" });
396
1151
  else {
397
- const source = await legacy.pauseM365();if (source) retire(source);
1152
+ const source = await legacy.pauseM365();
1153
+ if (source) retire(source);
398
1154
  }
399
1155
  }
400
1156
  } else throw accessError("ccdx_connections_action_invalid");
401
1157
  await syncClients();
402
- if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
403
- if (previousRef && (freshRef || input.config?.key_env)) { 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
+ }
404
1165
  return snapshot();
405
1166
  }
406
1167
  return {
407
1168
  ...legacy,
408
- managesClaude() { return !managed ? !legacyClaudeAccess : settings.claude_private_keys
409
- || !["claude_app", "claude_code"].every(id => binding(id).enabled && binding(id).source === "m365" && binding(id).allowed.includes("m365")); },
410
- 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
+ },
411
1185
  source: getSource,
412
1186
  connections: snapshot,
413
- 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")]),
414
1191
  validateLocalKeys() {
415
- 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 });
416
1203
  },
417
1204
  exportPrivateState: () => {
418
- const credentials = secrets.exportState?.(settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)) || [];
419
- 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
+ };
420
1213
  },
421
- importPrivateState: state => secrets.importState?.(state?.credentials || [], settings.apis.filter(api => api.enabled && api.secret_ref).map(api => api.secret_ref)),
422
- 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",
423
1226
  syncClients,
424
1227
  async manageConnections(input) {
425
- 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
+ }
1232
+ if (validObject(input, ["operation", "id"]) && input.operation === "source_catalog") {
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
+ };
1244
+ }
426
1245
  if (validObject(input, ["operation", "id"]) && input.operation === "discover") {
427
- 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();
428
1252
  }
429
- if (validObject(input, ["operation", "id"]) && input.operation === "cancel_discovery") { catalogRefresh.cancel(input.id);return snapshot(); }
430
1253
  const result = await enqueue(() => change(input));
431
1254
  if (input.operation === "save_api") {
432
- 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;
433
1257
  if (enabled(id)) void catalogRefresh.refresh(id).catch(() => {});
434
- } 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(() => {});
435
1260
  return input.operation === "save_api" ? snapshot() : result;
436
1261
  },
437
- 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; },
438
- 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; },
439
- 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
+ },
440
1281
  providerPreference(id) {
441
1282
  const c = settings.clients.codex;
442
- 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;
443
1290
  },
444
1291
  snapshot() {
445
- const result = legacy.snapshot();if (!managed) return result;
446
- 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;
447
1296
  const ms = performance.by_route.messages.by_provider.m365;
448
- const m365Requests = ms ? { ...ms.terminal_outcomes.totals, active: ms.active, total: ms.requests,
449
- performance: { by_route: { messages: { by_provider: { m365: ms }, terminal_outcomes: ms.terminal_outcomes } },
450
- active_total: ms.active, active_requests: performance.active_requests.filter(row => row.provider === "m365"),
451
- recent_requests: performance.recent_requests.filter(row => row.provider === "m365") } } : null;
452
- return { ...result, codex_provider: this.selection().codex, connections: snapshot(true),
453
- m365: { ...result.m365, ...(binding("codex").source === "m365" ? { preference: this.providerPreference(binding("codex").source) } : {}), claude: { ...result.m365.claude, requests: m365Requests,
454
- 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"])) } },
455
- 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",
456
1342
  clients: { app: setup.claude_app || "not_configured", code: setup.claude_code || "not_configured" },
457
- requests: { ...totals, active: performance.active_total, total: Object.values(totals).reduce((sum, value) => sum + value, 0) + performance.active_total, performance } },
458
- ...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
+ };
459
1354
  },
460
1355
  current(req) {
461
1356
  if (!managed) return legacy.current();
462
1357
  const mode = codexAccessMode();
463
1358
  if (mode === "paused" || mode === "disabled") throw accessError("ccdx_client_source_disabled", 503);
464
- const c = binding("codex"), compiled = plan("codex");
1359
+ const c = binding("codex"),
1360
+ compiled = plan("codex");
465
1361
  if (Array.isArray(c.deployments) && req?.method === "GET") {
466
1362
  if (codexRequiresKey()) requireCodexKey(req);
467
- return { id: "connections", registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
468
- client: { listModels: async () => ({ status: 200, body: JSON.stringify({ data: compiled.models.map(model => ({ ...model, id: model.public_id })) }) }) },
469
- 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
+ };
470
1376
  }
471
1377
  if (Array.isArray(c.deployments) && compiled.defaultUnavailable) {
472
1378
  if (req && codexRequiresKey()) requireCodexKey(req);
@@ -474,29 +1380,44 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
474
1380
  // explicitly requested model before any provider request is opened.
475
1381
  return null;
476
1382
  }
477
- 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
+ );
478
1387
  if (source?.id.startsWith("api_") && req) requireCodexKey(req);
479
- 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);
480
1394
  },
481
- hasModelBindings(client = "codex") { return managed && Array.isArray(binding(client).deployments); },
482
1395
  resolveCodex(body, req) {
483
1396
  if (!managed) return null;
484
1397
  const mode = codexAccessMode();
485
1398
  if (mode === "paused" || mode === "disabled") throw accessError("ccdx_client_source_disabled", 503);
486
1399
  if (!Array.isArray(binding("codex").deployments)) return null;
487
1400
  if (codexRequiresKey()) requireCodexKey(req);
488
- 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;
489
1405
  if (body.model === "codex-auto-review") {
490
1406
  delete body.service_tier;
491
- 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 };
492
1409
  }
493
- const record = resolveDeployment("codex", requested), context = currentRequestContext();
1410
+ const record = resolveDeployment("codex", requested),
1411
+ context = currentRequestContext();
494
1412
  if (context) {
495
- 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;
496
1416
  context.streamPerformance?.setProvider?.(record.provider.id);
497
1417
  Object.assign(context, this.historyContext(req.headers, record.provider));
498
1418
  }
499
- body.model = record.upstreamModel;return record.provider;
1419
+ body.model = record.upstreamModel;
1420
+ return record.provider;
500
1421
  },
501
1422
  track,
502
1423
  validateConversation,
@@ -507,81 +1428,224 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
507
1428
  return { historyNamespace: target.profileId() };
508
1429
  },
509
1430
  async handleClaude(req, res) {
510
- 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
+ }
511
1435
  if (!settings.claude_private_keys) {
512
- 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);
513
1438
  throw accessError("ccdx_client_source_disabled", 503);
514
1439
  }
515
1440
  const id = gatewayClient(req.headers, identities());
516
1441
  if (!id || id === "codex") throw accessError("ccdx_client_credential_required", 401);
517
- 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);
518
1445
  // A request resolves once after its bounded body read. Its source and
519
1446
  // capability snapshot stay pinned while catalogs/configuration change.
520
1447
  const catalog = { id: "connections", configuredModels: true, models: () => compiled.models };
521
1448
  let cached = handlers.get(id);
522
1449
  if (cached?.compiled !== compiled) {
523
- const handler = createClaudeGatewayHandler({ provider: catalog, acquireRequest: acquireClaudeRequest, apiKey: identities()[id], env, log, performance: legacy.claudePerformance,
524
- desktopAliases: id === "claude_app",
525
- resolveRequest(body) {
526
- const record = resolveDeployment(id, body.model), finish = track(record.provider);
527
- return { provider: record.provider, model: record.upstreamModel, capability: record.model.capability, finish };
528
- },
529
- validateConversation: (body, headers, source) => validateConversation(body, headers, source, id),
530
- onRequest() { lastClients[id] = new Date().toISOString(); } });
531
- 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;
532
1482
  }
533
- const headers = req.headers;req.headers = { ...headers, "x-ccdx-client": id === "claude_app" ? "claude-app" : "claude-code" };
534
- try { return await cached.handler(req, res); } finally { req.headers = headers; }
535
1483
  },
536
1484
  dashboardProviders() {
537
- const builtins = legacy.dashboardProviders();if (!managed) return builtins.filter(source => source.enabled);
538
- const definitions = snapshot(true).providers, performance = legacy.claudePerformance.snapshot();
539
- return definitions.filter(item => item.enabled).map(item => {
540
- const old = builtins.find(source => source.id === item.id), source = item.builtin ? null : getSource(item.id);
541
- const clients = CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(item.id)
542
- && (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,
543
- 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 }));
544
- return { ...old, id: item.id, name: item.name, enabled: true, generation: old?.generation || source?.registry.generation || 1,
545
- state: old?.state || "configured", auth: old?.auth || { state: "saved", token_cached: false },
546
- selection: { codex: clients.some(client => client.id === "codex"), models_required: item.id !== "github" }, clients,
547
- models: old?.models || { count: item.model_count, source: "configured" },
548
- requests: performance.by_route.messages.by_provider[item.id] ? { ...performance.by_route.messages.by_provider[item.id].terminal_outcomes.totals,
549
- active: performance.by_route.messages.by_provider[item.id].active, total: performance.by_route.messages.by_provider[item.id].requests } : null };
550
- });
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
+ });
551
1536
  },
552
1537
  dashboardCatalog(input = {}) {
553
1538
  if (!input.provider?.startsWith("api_")) return legacy.dashboardCatalog(input);
554
1539
  if (!enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
555
- 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
+ );
556
1543
  },
557
1544
  async action(input) {
558
1545
  if (managed && input.action === "auto-review" && Array.isArray(binding("codex").deployments)) {
559
- const c = binding("codex"), compiled = plan("codex");
1546
+ const c = binding("codex"),
1547
+ compiled = plan("codex");
560
1548
  if (!c.enabled || input.provider !== c.source) throw accessError("ccdx_client_source_mismatch", 409);
561
- 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
+ );
562
1552
  if (!record) throw accessError("ccdx_api_model_unavailable");
563
- if (input.effort && !record.model.capability.values.reasoning_efforts?.includes(input.effort)) throw accessError("ccdx_api_effort_unavailable");
564
- 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();
565
1560
  }
566
- if (managed && input.action === "auto-review" && input.provider && input.provider !== this.selection().codex) throw accessError("ccdx_client_source_mismatch", 409);
567
- 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);
568
1574
  if (managed && ["on", "off", "remove"].includes(input.action)) {
569
- if (input.action === "remove" && legacy.snapshot().m365.active_requests > 0) throw accessError("ccdx_source_busy", 409);
570
- const replacements = Object.fromEntries(CLIENT_IDS.filter(id => binding(id).source === "m365" && binding(id).enabled).map(id => [id, null]));
571
- await this.manageConnections({ operation: "provider", id: "m365", enabled: input.action === "on", replacements });
572
- 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();
573
1588
  }
574
- 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);
575
1591
  const { history_isolation, ...clientInput } = binding("codex");
576
- if (input.action === "switch" && input.provider?.startsWith("api_")) { await this.manageConnections({ operation: "client", id: "codex", ...clientInput, deployments: null, default_model: null, source: input.provider,
577
- model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort });return this.snapshot(); }
578
- 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(); }
579
- if (input.action === "auto-review" && managed && legacy.selection().codex !== "github") await legacy.action({ action: "switch", provider: "github" });
580
- 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);
581
1620
  const result = await legacy.action(input);
582
- 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
+ }
583
1634
  return result;
584
1635
  },
585
- 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
+ },
586
1650
  };
587
1651
  }