codex-copilot-dx 1.3.20 → 1.3.22

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