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