codex-copilot-dx 1.2.15 → 1.2.17
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 +49 -5
- package/docs/REFERENCE.md +99 -11
- package/package.json +1 -1
- package/src/access-settings.mjs +22 -4
- package/src/adapter.mjs +11 -2
- package/src/claude-capability-config.mjs +89 -0
- package/src/claude-client-config.mjs +20 -10
- package/src/claude-gateway.mjs +71 -26
- package/src/claude-models.mjs +21 -9
- package/src/client-model-plan.mjs +75 -0
- package/src/connection-runtime.mjs +176 -41
- package/src/dashboard/connections.js +137 -51
- package/src/dashboard/index.html +51 -49
- package/src/dashboard/language.js +60 -2
- 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) {
|
|
@@ -41,6 +48,22 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
41
48
|
const source = createApi({ config, secrets, env, platform });instances.set(id, { signature, source, config });sourceSecrets.set(source, config.secret_ref);
|
|
42
49
|
if (previous) retire(previous.source);return source;
|
|
43
50
|
}
|
|
51
|
+
function plan(id) {
|
|
52
|
+
const selected = binding(id), definitions = selected.allowed.filter(enabled).map(source => getSource(source)).filter(Boolean);
|
|
53
|
+
const cached = plans.get(id), stamps = definitions.map(source => [source, source.registry?.generation, source.registry?.models, source.profileId()]);
|
|
54
|
+
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;
|
|
55
|
+
const value = compileClientModels({ client: id, binding: selected, source: getSource, enabled,
|
|
56
|
+
names: Object.fromEntries([["github", "GitHub Copilot"], ["m365", "Microsoft 365"], ...settings.apis.map(api => [api.id, api.name])]),
|
|
57
|
+
desktopEffortAliases: capabilitySupport.app });
|
|
58
|
+
plans.set(id, { binding: selected, stamps, value });return value;
|
|
59
|
+
}
|
|
60
|
+
function resolveDeployment(id, model) {
|
|
61
|
+
const value = plan(id), record = value.routes.get(model);
|
|
62
|
+
if (!record) throw accessError("ccdx_api_model_unavailable");
|
|
63
|
+
const provider = requireSource(id, record.source);
|
|
64
|
+
if (provider !== record.provider) { plans.delete(id);return resolveDeployment(id, model); }
|
|
65
|
+
return record;
|
|
66
|
+
}
|
|
44
67
|
function retire(source) { if (active.get(source)) retired.add(source);else source.close(); }
|
|
45
68
|
function track(source) {
|
|
46
69
|
const finishLegacy = legacy.track(source);active.set(source, (active.get(source) || 0) + 1);let done = false;
|
|
@@ -56,6 +79,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
56
79
|
return next;
|
|
57
80
|
}
|
|
58
81
|
function save(next) {
|
|
82
|
+
plans.clear();
|
|
59
83
|
settings = structuredClone(updateAccessSettings(current => {
|
|
60
84
|
if (JSON.stringify(current) !== JSON.stringify(settings)) throw accessError("ccdx_connections_conflict", 409);return next;
|
|
61
85
|
}, options));managed = true;
|
|
@@ -74,30 +98,46 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
74
98
|
{ id: "github", name: "GitHub Copilot", enabled: config.providers.github, builtin: true, protocols: ["responses"] },
|
|
75
99
|
{ id: "m365", name: "Microsoft 365", enabled: config.providers.m365, builtin: true, protocols: ["messages", "responses"] },
|
|
76
100
|
...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) }; }),
|
|
101
|
+
...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
102
|
], clients: CLIENT_IDS.map(id => ({ id, name: CLIENT_NAMES[id], ...config.clients[id], setup: setup[id] || null,
|
|
79
|
-
observed_at: lastClients[id] || null }
|
|
103
|
+
observed_at: lastClients[id] || null, ...(compact ? {} : { model_plan: { default_model: plan(id).defaultModel,
|
|
104
|
+
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 })),
|
|
105
|
+
available: config.clients[id].allowed.filter(enabled).flatMap(source => sourceModels(getSource(source), id).map(model => ({ source, id: model.id,
|
|
106
|
+
route_id: deploymentModelId(source, model.id), capability: model.capability || resolveModelCapabilities(model, { builtin: true }) }))), sync: sharedSync, support: capabilitySupport } }) })), managed, m365_state: state.m365.state });
|
|
80
107
|
}
|
|
81
108
|
async function syncClients() {
|
|
109
|
+
syncAgain = true;if (syncFlight) return syncFlight;
|
|
110
|
+
syncFlight = (async () => { do { syncAgain = false;await performClientSync(); } while (syncAgain && !closed); })();
|
|
111
|
+
try { return await syncFlight; } finally { syncFlight = null; }
|
|
112
|
+
}
|
|
113
|
+
async function performClientSync() {
|
|
82
114
|
if (!managed || closed) return;
|
|
83
115
|
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; }
|
|
116
|
+
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_"))
|
|
117
|
+
? { baseUrl: `http://127.0.0.1:${corePort}/v1`, apiKey: identities().codex, model: plan("codex").defaultModel || codex.model } : { restore: true }) }).state; }
|
|
86
118
|
catch { setup.codex = "configuration_unavailable"; }
|
|
87
119
|
if (!settings.claude_private_keys) return;
|
|
88
120
|
let desktopManaged;
|
|
89
121
|
for (const id of ["claude_app", "claude_code"]) {
|
|
90
|
-
const selected = binding(id), source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
|
|
122
|
+
const selected = binding(id), compiled = plan(id), source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
|
|
91
123
|
try {
|
|
92
|
-
if (!selected.enabled || !
|
|
93
|
-
if (
|
|
124
|
+
if (!selected.enabled || !compiled.models.length) { const result = restoreClaude({ ...options, client: id });setup[id] = result.preserved ? "preserved" : "not_configured";continue; }
|
|
125
|
+
if (selected.auto_sync === false) { setup[id] = "manual_sync";continue; }
|
|
94
126
|
if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
127
|
+
const m365Only = compiled.models.every(model => model.source_id === "m365");
|
|
128
|
+
if (id === "claude_code" && !m365Only) restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
|
|
129
|
+
const result = configureClaude({ ...options, client: id, profileName: "CCDX", desktopAliases: id === "claude_app" && source?.id.startsWith("api_"), disableExperimentalBetas: m365Only, desktopManaged: id === "claude_app" ? desktopManaged : false,
|
|
130
|
+
baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: identities()[id], models: compiled.models, defaultModel: Array.isArray(selected.deployments) ? compiled.defaultModel : undefined });
|
|
98
131
|
setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
|
|
99
132
|
} catch { setup[id] = "configuration_unavailable"; }
|
|
100
133
|
}
|
|
134
|
+
const shared = claudeSharedCapabilityPlan({ app: setup.claude_app === "configured" ? plan("claude_app").models : [],
|
|
135
|
+
code: setup.claude_code === "configured" ? plan("claude_code").models : [], support: capabilitySupport });
|
|
136
|
+
if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
|
|
137
|
+
sharedSync = { ...shared, state: "partially_preserved", limitations: [...shared.limitations, { code: "manual_sync" }] };return;
|
|
138
|
+
}
|
|
139
|
+
try { sharedSync = { ...shared, ...syncClaudeCapabilities(shared, options) }; }
|
|
140
|
+
catch { sharedSync = { state: "configuration_unavailable", limitations: shared.limitations }; }
|
|
101
141
|
}
|
|
102
142
|
function requireSource(clientId, id) {
|
|
103
143
|
if (!permitted(clientId, id)) throw accessError("ccdx_client_source_disabled", 503);
|
|
@@ -106,11 +146,11 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
106
146
|
}
|
|
107
147
|
function validateConversation(body, headers, source, client = "codex") {
|
|
108
148
|
if (!body || typeof body !== "object" || Array.isArray(body)) return;
|
|
109
|
-
if (managed && (binding(client).history_isolation || source
|
|
149
|
+
if (managed && (binding(client).history_isolation || source?.id.startsWith("api_"))) guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client]);
|
|
110
150
|
}
|
|
111
151
|
async function change(input) {
|
|
112
152
|
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");
|
|
153
|
+
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
154
|
const next = editable();let freshRef, previousRef;
|
|
115
155
|
if (input.operation === "save_api") {
|
|
116
156
|
const existing = next.apis.find(api => api.id === input.id);
|
|
@@ -122,8 +162,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
122
162
|
const config = checkedApi({ ...input.config, id, enabled: existing?.enabled ?? true, ...(!input.config.key_env ? { secret_ref: freshRef || existing.secret_ref } : {}) });
|
|
123
163
|
if (!Array.isArray(input.allowed) || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
|
|
124
164
|
for (const id of CLIENT_IDS) {
|
|
125
|
-
const c = next.clients[id];if (c.source === config.id && !input.allowed.includes(id)
|
|
126
|
-
|
|
165
|
+
const c = next.clients[id];if (c.deployments?.some(item => item.source === config.id && (!input.allowed.includes(id)
|
|
166
|
+
|| !config.models.some(model => model.id === item.model && model.protocols.includes(id === "codex" ? "responses" : "messages"))))) throw accessError("ccdx_source_in_use", 409);
|
|
167
|
+
if (c.source === config.id && !input.allowed.includes(id)) throw accessError("ccdx_source_in_use", 409);
|
|
168
|
+
if (c.source === config.id && c.enabled && !Array.isArray(c.deployments) && (!config.models.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages"))
|
|
127
169
|
|| 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
170
|
if (input.allowed.includes(id) && !config.endpoints[id === "codex" ? "responses" : "messages"]) throw accessError("ccdx_api_protocol_required");
|
|
129
171
|
c.allowed = [...new Set([...c.allowed.filter(value => value !== config.id), ...(input.allowed.includes(id) ? [config.id] : [])])];
|
|
@@ -131,17 +173,36 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
131
173
|
if (existing) { previousRef = existing.secret_ref;next.apis[next.apis.indexOf(existing)] = config; } else next.apis.push(config);
|
|
132
174
|
checkedAccessSettings(next);
|
|
133
175
|
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
|
|
176
|
+
} else if (["client", "preview_client"].includes(input.operation)) {
|
|
135
177
|
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,
|
|
178
|
+
|| input.source !== null && input.source !== undefined && !input.allowed.includes(input.source)) throw accessError("ccdx_connections_action_invalid");
|
|
179
|
+
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];
|
|
180
|
+
next.clients[input.id] = { ...retained, enabled: input.enabled, allowed: input.allowed, source: input.enabled ? input.source ?? old.source : null,
|
|
181
|
+
...(input.deployments !== undefined ? { deployments: input.deployments, default_model: input.default_model ?? null, auto_sync: input.auto_sync ?? true }
|
|
182
|
+
: old.source !== input.source ? { deployments: null, default_model: null } : {}),
|
|
139
183
|
...(input.model ? { model: input.model } : {}), ...(input.auto_review_model ? { auto_review_model: input.auto_review_model } : {}),
|
|
140
184
|
...(input.auto_review_effort !== undefined ? { auto_review_effort: input.auto_review_effort } : {}) };
|
|
141
185
|
if (input.id !== "codex") next.claude_private_keys = true;
|
|
142
186
|
if (old.source !== input.source) next.clients[input.id].history_isolation = true;
|
|
143
187
|
const c = next.clients[input.id];
|
|
144
|
-
if (
|
|
188
|
+
if (Array.isArray(input.deployments)) {
|
|
189
|
+
checkedAccessSettings(next);
|
|
190
|
+
for (const item of c.deployments || []) {
|
|
191
|
+
if (!enabled(item.source) || !sourceModels(getSource(item.source), input.id).some(model => model.id === item.model)) throw accessError("ccdx_api_model_unavailable");
|
|
192
|
+
}
|
|
193
|
+
const names = Object.fromEntries(next.apis.map(api => [api.id, api.name]));
|
|
194
|
+
const compiled = compileClientModels({ client: input.id, binding: c, source: getSource, enabled, names, desktopEffortAliases: capabilitySupport.app });
|
|
195
|
+
if (c.default_model && !compiled.routes.has(c.default_model)) throw accessError("ccdx_api_model_unavailable");
|
|
196
|
+
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;
|
|
197
|
+
c.history_isolation = true;
|
|
198
|
+
if (input.id === "codex") {
|
|
199
|
+
c.model = compiled.routes.get(c.default_model)?.upstreamModel;
|
|
200
|
+
const review = compiled.routes.get(old.auto_review_model) || [...compiled.routes.values()].find(record => record.source === old.source && record.upstreamModel === old.auto_review_model);
|
|
201
|
+
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;
|
|
202
|
+
if (review?.source === c.source && old.auto_review_effort !== undefined) c.auto_review_effort = old.auto_review_effort;else delete c.auto_review_effort;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (c.source && !Array.isArray(input.deployments)) {
|
|
145
206
|
if (!enabled(c.source)) throw accessError("ccdx_client_source_disabled", 503);
|
|
146
207
|
const target = getSource(c.source), family = input.id === "codex" ? "gpt" : "claude";
|
|
147
208
|
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 +216,13 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
155
216
|
if (c.auto_review_effort !== undefined && c.auto_review_effort !== null && !efforts.includes(c.auto_review_effort)) throw accessError("ccdx_api_effort_unavailable");
|
|
156
217
|
}
|
|
157
218
|
}
|
|
219
|
+
if (input.operation === "preview_client") {
|
|
220
|
+
const proposed = compileClientModels({ client: input.id, binding: c, source: getSource, enabled, desktopEffortAliases: capabilitySupport.app });
|
|
221
|
+
const shared = input.id === "codex" ? null : claudeSharedCapabilityPlan({ app: input.id === "claude_app" ? proposed.models : plan("claude_app").models,
|
|
222
|
+
code: input.id === "claude_code" ? proposed.models : plan("claude_code").models, support: capabilitySupport });
|
|
223
|
+
return { ...snapshot(), preview: { models: proposed.models.map(model => ({ source: model.source_id, id: model.id, public_id: model.public_id, capability: model.capability })),
|
|
224
|
+
shared, current: input.id === "codex" ? null : inspectClaudeCapabilityConfiguration(proposed.models, options), saved: false } };
|
|
225
|
+
}
|
|
158
226
|
save(next);
|
|
159
227
|
} else if (input.operation === "provider") {
|
|
160
228
|
if (typeof input.enabled !== "boolean" || !["github", "m365", ...next.apis.map(api => api.id)].includes(input.id)) throw accessError("ccdx_connections_action_invalid");
|
|
@@ -171,6 +239,19 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
171
239
|
next.clients[id].history_isolation = true;
|
|
172
240
|
}
|
|
173
241
|
}
|
|
242
|
+
if (!input.enabled) for (const id of CLIENT_IDS) {
|
|
243
|
+
const c = next.clients[id];if (!Array.isArray(c.deployments)) continue;
|
|
244
|
+
const had = c.deployments.some(item => item.source === input.id);if (!had) continue;
|
|
245
|
+
c.deployments = c.deployments.filter(item => item.source !== input.id);
|
|
246
|
+
if (input.replacements && Object.hasOwn(input.replacements, id)) {
|
|
247
|
+
const replacement = input.replacements[id];
|
|
248
|
+
if (!replacement) c.deployments = [];
|
|
249
|
+
else if (!c.deployments.some(item => item.source === replacement)) {
|
|
250
|
+
const model = sourceModels(getSource(replacement), id)[0];if (model) c.deployments.push({ source: replacement, model: model.id });
|
|
251
|
+
}
|
|
252
|
+
c.default_model = c.deployments.find(item => item.source === replacement) ? deploymentModelId(replacement, c.deployments.find(item => item.source === replacement).model) : null;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
174
255
|
if (input.id.startsWith("api_")) next.apis.find(api => api.id === input.id).enabled = input.enabled;else next.providers[input.id] = input.enabled;
|
|
175
256
|
save(next);
|
|
176
257
|
if (input.id === "m365") {
|
|
@@ -181,7 +262,15 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
181
262
|
}
|
|
182
263
|
} else if (input.operation === "discover") {
|
|
183
264
|
if (!settings.apis.some(api => api.id === input.id && api.enabled)) throw accessError("ccdx_client_source_disabled", 503);
|
|
184
|
-
|
|
265
|
+
try {
|
|
266
|
+
const models = await getSource(input.id).discover({ signal: AbortSignal.timeout(20000) });
|
|
267
|
+
const byId = new Map(models.map(model => [model.id, model]));
|
|
268
|
+
const config = next.apis.find(api => api.id === input.id);
|
|
269
|
+
for (const model of config.models) if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
|
|
270
|
+
config.checked_at = new Date().toISOString();save(next);
|
|
271
|
+
discoveries.set(input.id, { state: "ready", checked_at: config.checked_at });await syncClients();
|
|
272
|
+
return { ...snapshot(), discovered: models };
|
|
273
|
+
} catch (error) { discoveries.set(input.id, { state: "stale", code: error.code || "ccdx_api_catalog_unavailable", checked_at: new Date().toISOString() });throw error; }
|
|
185
274
|
} else throw accessError("ccdx_connections_action_invalid");
|
|
186
275
|
await syncClients();
|
|
187
276
|
if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
|
|
@@ -197,7 +286,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
197
286
|
async start() { const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();return result; },
|
|
198
287
|
refresh() { return !managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(); },
|
|
199
288
|
selection() { return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null }; },
|
|
200
|
-
providerPreference(id) {
|
|
289
|
+
providerPreference(id) {
|
|
290
|
+
const c = settings.clients.codex;
|
|
291
|
+
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;
|
|
292
|
+
},
|
|
201
293
|
snapshot() {
|
|
202
294
|
const result = legacy.snapshot();if (!managed) return result;
|
|
203
295
|
const performance = legacy.claudePerformance.snapshot(), totals = performance.by_route.messages.terminal_outcomes.totals;
|
|
@@ -207,19 +299,43 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
207
299
|
active_total: ms.active, active_requests: performance.active_requests.filter(row => row.provider === "m365"),
|
|
208
300
|
recent_requests: performance.recent_requests.filter(row => row.provider === "m365") } } : null;
|
|
209
301
|
return { ...result, codex_provider: this.selection().codex, connections: snapshot(true),
|
|
210
|
-
m365: { ...result.m365, ...(binding("codex").source === "m365" ? { preference:
|
|
302
|
+
m365: { ...result.m365, ...(binding("codex").source === "m365" ? { preference: this.providerPreference(binding("codex").source) } : {}), claude: { ...result.m365.claude, requests: m365Requests,
|
|
211
303
|
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
304
|
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
305
|
clients: { app: setup.claude_app || "not_configured", code: setup.claude_code || "not_configured" },
|
|
214
306
|
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:
|
|
307
|
+
...Object.fromEntries(settings.apis.map(api => [api.id, { preference: this.providerPreference(binding("codex").source) }])) };
|
|
216
308
|
},
|
|
217
309
|
current(req) {
|
|
218
310
|
if (!managed) return legacy.current();
|
|
219
|
-
const c = binding("codex"),
|
|
220
|
-
|
|
311
|
+
const c = binding("codex"), compiled = plan("codex");
|
|
312
|
+
const source = requireSource("codex", Array.isArray(c.deployments) ? compiled.routes.get(compiled.defaultModel)?.source : c.source);
|
|
313
|
+
if (Array.isArray(c.deployments) && req?.method === "GET") {
|
|
314
|
+
if (gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
|
|
315
|
+
return { ...source, registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
|
|
316
|
+
client: { ...source.client, listModels: async () => ({ status: 200, body: JSON.stringify({ data: compiled.models.map(model => ({ ...model, id: model.public_id })) }) }) },
|
|
317
|
+
codexCatalog: codexClientCatalog(compiled, getSource) };
|
|
318
|
+
}
|
|
319
|
+
if (source?.id.startsWith("api_") && req && gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
|
|
221
320
|
return source;
|
|
222
321
|
},
|
|
322
|
+
hasModelBindings(client = "codex") { return managed && Array.isArray(binding(client).deployments); },
|
|
323
|
+
resolveCodex(body, req) {
|
|
324
|
+
if (!managed || !Array.isArray(binding("codex").deployments)) return null;
|
|
325
|
+
if (gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
|
|
326
|
+
const requested = body.model === "codex-auto-review" ? binding("codex").auto_review_model || plan("codex").defaultModel : body.model;
|
|
327
|
+
if (body.model === "codex-auto-review") {
|
|
328
|
+
delete body.service_tier;
|
|
329
|
+
if (binding("codex").auto_review_effort) body.reasoning = { ...body.reasoning, effort: binding("codex").auto_review_effort };
|
|
330
|
+
}
|
|
331
|
+
const record = resolveDeployment("codex", requested), context = currentRequestContext();
|
|
332
|
+
if (context) {
|
|
333
|
+
context.finishProvider?.();context.finishProvider = track(record.provider);context.provider = record.provider.id;
|
|
334
|
+
context.streamPerformance?.setProvider?.(record.provider.id);
|
|
335
|
+
Object.assign(context, this.historyContext(req.headers, record.provider));
|
|
336
|
+
}
|
|
337
|
+
body.model = record.upstreamModel;return record.provider;
|
|
338
|
+
},
|
|
223
339
|
track,
|
|
224
340
|
validateConversation,
|
|
225
341
|
historyContext(headers, target) {
|
|
@@ -235,14 +351,24 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
235
351
|
}
|
|
236
352
|
const id = gatewayClient(req.headers, identities());
|
|
237
353
|
if (!id || id === "codex") throw accessError("ccdx_client_credential_required", 401);
|
|
238
|
-
const
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
354
|
+
const compiled = plan(id);if (!binding(id).enabled || !compiled.models.length) throw accessError("ccdx_client_source_disabled", 503);
|
|
355
|
+
// A request resolves once after its bounded body read. Its source and
|
|
356
|
+
// capability snapshot stay pinned while catalogs/configuration change.
|
|
357
|
+
const catalog = { id: "connections", configuredModels: true, models: () => compiled.models };
|
|
358
|
+
let cached = handlers.get(id);
|
|
359
|
+
if (cached?.compiled !== compiled) {
|
|
360
|
+
const handler = createClaudeGatewayHandler({ provider: catalog, acquireRequest: acquireClaudeRequest, apiKey: identities()[id], env, log, performance: legacy.claudePerformance,
|
|
361
|
+
desktopAliases: id === "claude_app",
|
|
362
|
+
resolveRequest(body) {
|
|
363
|
+
const record = resolveDeployment(id, body.model), finish = track(record.provider);
|
|
364
|
+
return { provider: record.provider, model: record.upstreamModel, capability: record.model.capability, finish };
|
|
365
|
+
},
|
|
366
|
+
validateConversation: (body, headers, source) => validateConversation(body, headers, source, id),
|
|
367
|
+
onRequest() { lastClients[id] = new Date().toISOString(); } });
|
|
368
|
+
cached = { compiled, handler };handlers.set(id, cached);
|
|
369
|
+
}
|
|
370
|
+
const headers = req.headers;req.headers = { ...headers, "x-ccdx-client": id === "claude_app" ? "claude-app" : "claude-code" };
|
|
371
|
+
try { return await cached.handler(req, res); } finally { req.headers = headers; }
|
|
246
372
|
},
|
|
247
373
|
dashboardProviders() {
|
|
248
374
|
const builtins = legacy.dashboardProviders();if (!managed) return builtins.filter(source => source.enabled);
|
|
@@ -250,8 +376,8 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
250
376
|
return definitions.filter(item => item.enabled).map(item => {
|
|
251
377
|
const old = builtins.find(source => source.id === item.id), source = item.builtin ? null : getSource(item.id);
|
|
252
378
|
const clients = CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(item.id)
|
|
253
|
-
&& (id === "codex" ? item.protocols.includes("responses") : item.protocols.includes("messages"))).map(id => ({ id, name: CLIENT_NAMES[id], selected: binding(id).source === item.id,
|
|
254
|
-
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 }));
|
|
379
|
+
&& (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,
|
|
380
|
+
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 }));
|
|
255
381
|
return { ...old, id: item.id, name: item.name, enabled: true, generation: old?.generation || source?.registry.generation || 1,
|
|
256
382
|
state: old?.state || "configured", auth: old?.auth || { state: "saved", token_cached: false },
|
|
257
383
|
selection: { codex: clients.some(client => client.id === "codex"), models_required: item.id !== "github" }, clients,
|
|
@@ -266,6 +392,14 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
266
392
|
return getSource(input.provider).publicCatalog(CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider)));
|
|
267
393
|
},
|
|
268
394
|
async action(input) {
|
|
395
|
+
if (managed && input.action === "auto-review" && Array.isArray(binding("codex").deployments)) {
|
|
396
|
+
const c = binding("codex"), compiled = plan("codex");
|
|
397
|
+
if (!c.enabled || input.provider !== c.source) throw accessError("ccdx_client_source_mismatch", 409);
|
|
398
|
+
const record = [...compiled.routes.values()].find(record => record.source === input.provider && record.upstreamModel === input.model);
|
|
399
|
+
if (!record) throw accessError("ccdx_api_model_unavailable");
|
|
400
|
+
if (input.effort && !record.model.capability.values.reasoning_efforts?.includes(input.effort)) throw accessError("ccdx_api_effort_unavailable");
|
|
401
|
+
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();
|
|
402
|
+
}
|
|
269
403
|
if (managed && input.action === "auto-review" && input.provider && input.provider !== this.selection().codex) throw accessError("ccdx_client_source_mismatch", 409);
|
|
270
404
|
if (managed && input.action === "auto-review" && (!binding("codex").enabled || !binding("codex").source)) throw accessError("ccdx_client_source_disabled", 503);
|
|
271
405
|
if (managed && ["on", "off", "remove"].includes(input.action)) {
|
|
@@ -276,14 +410,15 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
276
410
|
}
|
|
277
411
|
if (managed && input.action === "switch" && !binding("codex").enabled) throw accessError("ccdx_client_source_disabled", 503);
|
|
278
412
|
const { history_isolation, ...clientInput } = binding("codex");
|
|
279
|
-
if (input.action === "switch" && input.provider?.startsWith("api_")) { await this.manageConnections({ operation: "client", id: "codex", ...clientInput, source: input.provider,
|
|
413
|
+
if (input.action === "switch" && input.provider?.startsWith("api_")) { await this.manageConnections({ operation: "client", id: "codex", ...clientInput, deployments: null, default_model: null, source: input.provider,
|
|
280
414
|
model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort });return this.snapshot(); }
|
|
281
415
|
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(); }
|
|
282
416
|
if (input.action === "auto-review" && managed && legacy.selection().codex !== "github") await legacy.action({ action: "switch", provider: "github" });
|
|
417
|
+
if (managed && input.action === "switch" && !permitted("codex", input.provider)) throw accessError("ccdx_client_source_disabled", 503);
|
|
283
418
|
const result = await legacy.action(input);
|
|
284
|
-
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(); }
|
|
419
|
+
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(); }
|
|
285
420
|
return result;
|
|
286
421
|
},
|
|
287
|
-
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(); },
|
|
422
|
+
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(); },
|
|
288
423
|
};
|
|
289
424
|
}
|