codex-copilot-dx 1.3.19 → 1.3.21

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