codex-copilot-dx 1.2.11 → 1.2.13
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 +14 -14
- package/bin/cli.mjs +12 -8
- package/docs/ARCHITECTURE.md +75 -5
- package/docs/REFERENCE.md +117 -4
- package/package.json +2 -2
- package/src/access-settings.mjs +98 -0
- package/src/adapter.mjs +19 -7
- package/src/api-secrets.mjs +69 -0
- package/src/auto-review-model.mjs +4 -3
- package/src/claude-client-config.mjs +16 -11
- package/src/claude-gateway.mjs +11 -8
- package/src/cli-m365.mjs +48 -8
- package/src/cli-models.mjs +2 -1
- package/src/cli-options.mjs +1 -1
- package/src/cli-status.mjs +1 -1
- package/src/client-gateway-keys.mjs +29 -0
- package/src/codex-api-config.mjs +51 -0
- package/src/connection-runtime.mjs +289 -0
- package/src/conversation-source-guard.mjs +42 -0
- package/src/dashboard/connections.js +163 -0
- package/src/dashboard/console.js +6 -4
- package/src/dashboard/flow.js +17 -18
- package/src/dashboard/index.html +46 -3
- package/src/dashboard/language.js +88 -3
- package/src/dashboard/status.js +1 -1
- package/src/dashboard/ui.css +54 -26
- package/src/dashboard/ui.js +5 -3
- package/src/dashboard-api.mjs +19 -4
- package/src/dashboard.mjs +1 -0
- package/src/optional-routes.mjs +2 -2
- package/src/private-helper-environment.mjs +7 -0
- package/src/provider-management.mjs +1 -1
- package/src/provider-runtime.mjs +37 -5
- package/src/providers/api-network.mjs +51 -0
- package/src/providers/api.mjs +129 -0
- package/src/proxy-tunnel.mjs +6 -4
- package/src/request-application.mjs +12 -6
- package/src/responses-handler.mjs +6 -4
- package/src/startup-ui.mjs +9 -0
- package/src/stream-performance.mjs +7 -6
- package/src/terminal-console.mjs +1 -1
- package/src/usage-store.mjs +1 -1
- package/src/windows-http-network.mjs +11 -6
- package/src/windows-prediction-network.cs +6 -4
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { accessSettingsPath, readAccessSettings, updateAccessSettings, checkedApi, checkedAccessSettings, accessError, CLIENT_IDS, CLIENT_NAMES } from "./access-settings.mjs";
|
|
4
|
+
import { createApiSecretStore, checkedApiKey } from "./api-secrets.mjs";
|
|
5
|
+
import { createApiProvider } from "./providers/api.mjs";
|
|
6
|
+
import { readClientGatewayKeys, gatewayClient } from "./client-gateway-keys.mjs";
|
|
7
|
+
import { createClaudeGatewayHandler } from "./claude-gateway.mjs";
|
|
8
|
+
import { configureClaudeClients, restoreClaudeClients, inspectClaudeDesktopPolicy } from "./claude-client-config.mjs";
|
|
9
|
+
import { configureCodexApi } from "./codex-api-config.mjs";
|
|
10
|
+
import { autoReviewReasoningEfforts } from "./models.mjs";
|
|
11
|
+
import { createConversationSourceGuard } from "./conversation-source-guard.mjs";
|
|
12
|
+
|
|
13
|
+
const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
|
|
14
|
+
export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
|
|
15
|
+
secretStore, createApi = createApiProvider, configureClaude = configureClaudeClients, restoreClaude = restoreClaudeClients,
|
|
16
|
+
configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, log = () => {} } = {}) {
|
|
17
|
+
const options = { home, env, platform }, secrets = secretStore || createApiSecretStore(options);
|
|
18
|
+
const guardConversation = createConversationSourceGuard(options);
|
|
19
|
+
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 WeakMap(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
|
|
21
|
+
const retiredSecrets = new Map(), cleanups = new Set();
|
|
22
|
+
function cleanSecrets(id) {
|
|
23
|
+
const refs = retiredSecrets.get(id);if (!refs) return;
|
|
24
|
+
for (const ref of refs) {
|
|
25
|
+
if ([...active.keys()].some(source => sourceSecrets.get(source) === ref)) continue;
|
|
26
|
+
refs.delete(ref);
|
|
27
|
+
const task = secrets.remove(ref).catch(() => { log("warn", "Previous API credential cleanup needs review"); }).finally(() => cleanups.delete(task));cleanups.add(task);
|
|
28
|
+
}
|
|
29
|
+
if (!refs.size) retiredSecrets.delete(id);
|
|
30
|
+
}
|
|
31
|
+
const identities = () => keys ||= readClientGatewayKeys(options);
|
|
32
|
+
const enabled = id => id?.startsWith("api_") ? settings.apis.find(api => api.id === id)?.enabled === true : settings.providers[id] === true;
|
|
33
|
+
const binding = id => managed ? settings.clients[id] : { ...settings.clients[id], source: id === "codex" ? legacy.selection().codex : legacy.snapshot().m365.enabled ? "m365" : null };
|
|
34
|
+
const permitted = (id, source) => binding(id)?.enabled && binding(id).allowed.includes(source) && enabled(source);
|
|
35
|
+
function getSource(id) {
|
|
36
|
+
if (!id?.startsWith("api_")) return legacy.source(id);
|
|
37
|
+
const config = settings.apis.find(value => value.id === id);if (!config) return null;
|
|
38
|
+
const previous = instances.get(id);if (previous?.config === config) return previous.source;
|
|
39
|
+
const signature = JSON.stringify(config);
|
|
40
|
+
if (previous?.signature === signature) return previous.source;
|
|
41
|
+
const source = createApi({ config, secrets, env, platform });instances.set(id, { signature, source, config });sourceSecrets.set(source, config.secret_ref);
|
|
42
|
+
if (previous) retire(previous.source);return source;
|
|
43
|
+
}
|
|
44
|
+
function retire(source) { if (active.get(source)) retired.add(source);else source.close(); }
|
|
45
|
+
function track(source) {
|
|
46
|
+
const finishLegacy = legacy.track(source);active.set(source, (active.get(source) || 0) + 1);let done = false;
|
|
47
|
+
return () => {
|
|
48
|
+
if (done) return;done = true;finishLegacy?.();const count = (active.get(source) || 1) - 1;
|
|
49
|
+
if (count) active.set(source, count);else { active.delete(source);if (retired.delete(source)) source.close();cleanSecrets(source.id); }
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function editable() {
|
|
53
|
+
if (managed) return structuredClone(settings);
|
|
54
|
+
const next = structuredClone(settings);next.providers.m365 = legacy.snapshot().m365.enabled === true;
|
|
55
|
+
for (const id of CLIENT_IDS) next.clients[id].source = binding(id).source;
|
|
56
|
+
return next;
|
|
57
|
+
}
|
|
58
|
+
function save(next) {
|
|
59
|
+
settings = structuredClone(updateAccessSettings(current => {
|
|
60
|
+
if (JSON.stringify(current) !== JSON.stringify(settings)) throw accessError("ccdx_connections_conflict", 409);return next;
|
|
61
|
+
}, options));managed = true;
|
|
62
|
+
for (const [id, item] of instances) {
|
|
63
|
+
const current = settings.apis.find(api => api.id === id);
|
|
64
|
+
if (!current?.enabled || JSON.stringify(current) !== item.signature) { instances.delete(id);retire(item.source); }else item.config = current;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function summary(api) {
|
|
68
|
+
if (!summaries.has(api)) summaries.set(api, { model_count: api.models.length, codex_model_count: api.models.filter(model => model.protocols.includes("responses")).length, protocols: Object.keys(api.endpoints) });
|
|
69
|
+
return summaries.get(api);
|
|
70
|
+
}
|
|
71
|
+
function snapshot(compact = false) {
|
|
72
|
+
const state = legacy.snapshot(), config = managed ? settings : editable();
|
|
73
|
+
return structuredClone({ source: "connections", providers: [
|
|
74
|
+
{ id: "github", name: "GitHub Copilot", enabled: config.providers.github, builtin: true, protocols: ["responses"] },
|
|
75
|
+
{ id: "m365", name: "Microsoft 365", enabled: config.providers.m365, builtin: true, protocols: ["messages", "responses"] },
|
|
76
|
+
...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) }; }),
|
|
78
|
+
], clients: CLIENT_IDS.map(id => ({ id, name: CLIENT_NAMES[id], ...config.clients[id], setup: setup[id] || null,
|
|
79
|
+
observed_at: lastClients[id] || null })), managed, m365_state: state.m365.state });
|
|
80
|
+
}
|
|
81
|
+
async function syncClients() {
|
|
82
|
+
if (!managed || closed) return;
|
|
83
|
+
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; }
|
|
86
|
+
catch { setup.codex = "configuration_unavailable"; }
|
|
87
|
+
if (!settings.claude_private_keys) return;
|
|
88
|
+
let desktopManaged;
|
|
89
|
+
for (const id of ["claude_app", "claude_code"]) {
|
|
90
|
+
const selected = binding(id), source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
|
|
91
|
+
try {
|
|
92
|
+
if (!selected.enabled || !selected.source || !permitted(id, selected.source)) { const result = restoreClaude({ ...options, client: id });setup[id] = result.preserved ? "preserved" : "not_configured";continue; }
|
|
93
|
+
if (!source?.models?.("claude").length) { setup[id] = "unavailable";continue; }
|
|
94
|
+
if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
|
|
95
|
+
if (id === "claude_code" && source.id !== "m365") restoreClaude({ ...options, client: id, fields: ["env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] });
|
|
96
|
+
const result = configureClaude({ ...options, client: id, profileName: "CCDX", disableExperimentalBetas: source.id === "m365", desktopManaged: id === "claude_app" ? desktopManaged : false,
|
|
97
|
+
baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: identities()[id], models: source.models("claude") });
|
|
98
|
+
setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
|
|
99
|
+
} catch { setup[id] = "configuration_unavailable"; }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function requireSource(clientId, id) {
|
|
103
|
+
if (!permitted(clientId, id)) throw accessError("ccdx_client_source_disabled", 503);
|
|
104
|
+
if (id === "m365" && legacy.snapshot().m365.account_change_in_flight) throw accessError("m365_account_busy", 409);
|
|
105
|
+
const source = getSource(id);if (!source) throw accessError("ccdx_api_not_ready", 503);return source;
|
|
106
|
+
}
|
|
107
|
+
function validateConversation(body, headers, source, client = "codex") {
|
|
108
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return;
|
|
109
|
+
if (managed && (binding(client).history_isolation || source.id.startsWith("api_"))) guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client]);
|
|
110
|
+
}
|
|
111
|
+
async function change(input) {
|
|
112
|
+
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");
|
|
114
|
+
const next = editable();let freshRef, previousRef;
|
|
115
|
+
if (input.operation === "save_api") {
|
|
116
|
+
const existing = next.apis.find(api => api.id === input.id);
|
|
117
|
+
if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
|
|
118
|
+
if (!validObject(input.config, ["name", "base_url", "endpoints", "auth_header", "models", "key_env"])) throw accessError("ccdx_api_config_invalid");
|
|
119
|
+
const id = existing?.id || "api_" + randomBytes(8).toString("hex");
|
|
120
|
+
if (input.key !== undefined && input.key !== "") { checkedApiKey(input.key);freshRef = randomBytes(16).toString("hex"); }
|
|
121
|
+
if (input.config.key_env && freshRef || !input.config.key_env && !freshRef && !existing?.secret_ref) throw accessError("ccdx_api_key_invalid");
|
|
122
|
+
const config = checkedApi({ ...input.config, id, enabled: existing?.enabled ?? true, ...(!input.config.key_env ? { secret_ref: freshRef || existing.secret_ref } : {}) });
|
|
123
|
+
if (!Array.isArray(input.allowed) || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
|
|
124
|
+
for (const id of CLIENT_IDS) {
|
|
125
|
+
const c = next.clients[id];if (c.source === config.id && !input.allowed.includes(id)) throw accessError("ccdx_source_in_use", 409);
|
|
126
|
+
if (c.source === config.id && c.enabled && (!config.models.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages"))
|
|
127
|
+
|| 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
|
+
if (input.allowed.includes(id) && !config.endpoints[id === "codex" ? "responses" : "messages"]) throw accessError("ccdx_api_protocol_required");
|
|
129
|
+
c.allowed = [...new Set([...c.allowed.filter(value => value !== config.id), ...(input.allowed.includes(id) ? [config.id] : [])])];
|
|
130
|
+
}
|
|
131
|
+
if (existing) { previousRef = existing.secret_ref;next.apis[next.apis.indexOf(existing)] = config; } else next.apis.push(config);
|
|
132
|
+
checkedAccessSettings(next);
|
|
133
|
+
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 === "client") {
|
|
135
|
+
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,
|
|
139
|
+
...(input.model ? { model: input.model } : {}), ...(input.auto_review_model ? { auto_review_model: input.auto_review_model } : {}),
|
|
140
|
+
...(input.auto_review_effort !== undefined ? { auto_review_effort: input.auto_review_effort } : {}) };
|
|
141
|
+
if (input.id !== "codex") next.claude_private_keys = true;
|
|
142
|
+
if (old.source !== input.source) next.clients[input.id].history_isolation = true;
|
|
143
|
+
const c = next.clients[input.id];
|
|
144
|
+
if (c.source) {
|
|
145
|
+
if (!enabled(c.source)) throw accessError("ccdx_client_source_disabled", 503);
|
|
146
|
+
const target = getSource(c.source), family = input.id === "codex" ? "gpt" : "claude";
|
|
147
|
+
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);
|
|
148
|
+
if (input.id !== "codex" && c.source === "github" || c.source !== "github" && !target?.models(family).length) throw accessError("ccdx_api_model_unavailable");
|
|
149
|
+
if (input.id === "codex" && c.source !== "github") {
|
|
150
|
+
const previous = c.source === "m365" ? legacy.selection().m365 : null;
|
|
151
|
+
c.model = input.model || previous?.model || target.models("gpt")[0].id;c.auto_review_model = input.auto_review_model || previous?.auto_review_model || c.model;
|
|
152
|
+
if (![c.model, c.auto_review_model].every(id => target.models("gpt").some(model => model.id === id))) throw accessError("ccdx_api_model_unavailable");
|
|
153
|
+
const efforts = api ? api.models.find(model => model.id === c.auto_review_model)?.reasoning_efforts || []
|
|
154
|
+
: autoReviewReasoningEfforts(target.models("gpt").find(model => model.id === c.auto_review_model));
|
|
155
|
+
if (c.auto_review_effort !== undefined && c.auto_review_effort !== null && !efforts.includes(c.auto_review_effort)) throw accessError("ccdx_api_effort_unavailable");
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
save(next);
|
|
159
|
+
} else if (input.operation === "provider") {
|
|
160
|
+
if (typeof input.enabled !== "boolean" || !["github", "m365", ...next.apis.map(api => api.id)].includes(input.id)) throw accessError("ccdx_connections_action_invalid");
|
|
161
|
+
if (input.id === "m365" && input.enabled && env.CCDX_M365 === "0") throw accessError("ccdx_provider_environment_disabled", 409);
|
|
162
|
+
if (input.id === "m365" && !input.enabled && legacy.snapshot().m365.claude.requests?.active > 0) throw accessError("ccdx_source_busy", 409);
|
|
163
|
+
if (!input.enabled) {
|
|
164
|
+
const affected = CLIENT_IDS.filter(id => next.clients[id].source === input.id && next.clients[id].enabled);
|
|
165
|
+
if (affected.some(id => id !== "codex")) next.claude_private_keys = true;
|
|
166
|
+
if (affected.length && !validObject(input.replacements, affected)) throw accessError("ccdx_source_in_use", 409);
|
|
167
|
+
for (const id of affected) {
|
|
168
|
+
const replacement = input.replacements[id];
|
|
169
|
+
if (replacement !== null && (replacement === input.id || !permitted(id, replacement) || replacement !== "github" && !getSource(replacement)?.models(id === "codex" ? "gpt" : "claude").length)) throw accessError("ccdx_connections_action_invalid");
|
|
170
|
+
next.clients[id].source = replacement;
|
|
171
|
+
next.clients[id].history_isolation = true;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (input.id.startsWith("api_")) next.apis.find(api => api.id === input.id).enabled = input.enabled;else next.providers[input.id] = input.enabled;
|
|
175
|
+
save(next);
|
|
176
|
+
if (input.id === "m365") {
|
|
177
|
+
if (input.enabled) await legacy.action({ action: "on" });
|
|
178
|
+
else {
|
|
179
|
+
const source = await legacy.pauseM365();if (source) retire(source);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
} else if (input.operation === "discover") {
|
|
183
|
+
if (!settings.apis.some(api => api.id === input.id && api.enabled)) throw accessError("ccdx_client_source_disabled", 503);
|
|
184
|
+
const models = await getSource(input.id).discover({ signal: AbortSignal.timeout(20000) });return { ...snapshot(), discovered: models };
|
|
185
|
+
} else throw accessError("ccdx_connections_action_invalid");
|
|
186
|
+
await syncClients();
|
|
187
|
+
if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
|
|
188
|
+
if (previousRef && (freshRef || input.config?.key_env)) { if (!retiredSecrets.has(input.id)) retiredSecrets.set(input.id, new Set());retiredSecrets.get(input.id).add(previousRef);cleanSecrets(input.id); }
|
|
189
|
+
return snapshot();
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
...legacy,
|
|
193
|
+
source: getSource,
|
|
194
|
+
connections: snapshot,
|
|
195
|
+
syncClients,
|
|
196
|
+
manageConnections(input) { if (!input) return Promise.resolve(snapshot());const job = serial.then(() => change(input));serial = job.catch(() => {});return job; },
|
|
197
|
+
async start() { const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();return result; },
|
|
198
|
+
refresh() { return !managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(); },
|
|
199
|
+
selection() { return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null }; },
|
|
200
|
+
providerPreference(id) { return managed && settings.clients.codex.source === id && settings.clients.codex.auto_review_model ? settings.clients.codex : legacy.selection().m365; },
|
|
201
|
+
snapshot() {
|
|
202
|
+
const result = legacy.snapshot();if (!managed) return result;
|
|
203
|
+
const performance = legacy.claudePerformance.snapshot(), totals = performance.by_route.messages.terminal_outcomes.totals;
|
|
204
|
+
const ms = performance.by_route.messages.by_provider.m365;
|
|
205
|
+
const m365Requests = ms ? { ...ms.terminal_outcomes.totals, active: ms.active, total: ms.requests,
|
|
206
|
+
performance: { by_route: { messages: { by_provider: { m365: ms }, terminal_outcomes: ms.terminal_outcomes } },
|
|
207
|
+
active_total: ms.active, active_requests: performance.active_requests.filter(row => row.provider === "m365"),
|
|
208
|
+
recent_requests: performance.recent_requests.filter(row => row.provider === "m365") } } : null;
|
|
209
|
+
return { ...result, codex_provider: this.selection().codex, connections: snapshot(true),
|
|
210
|
+
m365: { ...result.m365, ...(binding("codex").source === "m365" ? { preference: settings.clients.codex } : {}), claude: { ...result.m365.claude, requests: m365Requests,
|
|
211
|
+
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
|
+
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
|
+
clients: { app: setup.claude_app || "not_configured", code: setup.claude_code || "not_configured" },
|
|
214
|
+
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: settings.clients.codex }])) };
|
|
216
|
+
},
|
|
217
|
+
current(req) {
|
|
218
|
+
if (!managed) return legacy.current();
|
|
219
|
+
const c = binding("codex"), source = requireSource("codex", c.source);
|
|
220
|
+
if (source.id.startsWith("api_") && req && gatewayClient(req.headers, identities()) !== "codex") throw accessError("ccdx_client_credential_required", 401);
|
|
221
|
+
return source;
|
|
222
|
+
},
|
|
223
|
+
track,
|
|
224
|
+
validateConversation,
|
|
225
|
+
historyContext(headers, target) {
|
|
226
|
+
if (!target.id.startsWith("api_")) return legacy.historyContext(headers, target);
|
|
227
|
+
// Opaque Responses state never transfers to another API/key/configuration.
|
|
228
|
+
return { historyNamespace: target.profileId() };
|
|
229
|
+
},
|
|
230
|
+
async handleClaude(req, res) {
|
|
231
|
+
if (!managed) return legacy.handleClaude(req, res);
|
|
232
|
+
if (!settings.claude_private_keys) {
|
|
233
|
+
if (["claude_app", "claude_code"].every(id => permitted(id, "m365") && binding(id).source === "m365")) return legacy.handleClaude(req, res);
|
|
234
|
+
throw accessError("ccdx_client_source_disabled", 503);
|
|
235
|
+
}
|
|
236
|
+
const id = gatewayClient(req.headers, identities());
|
|
237
|
+
if (!id || id === "codex") throw accessError("ccdx_client_credential_required", 401);
|
|
238
|
+
const source = requireSource(id, binding(id).source);let byClient = handlers.get(source);
|
|
239
|
+
if (!byClient) { byClient = new Map();handlers.set(source, byClient); }
|
|
240
|
+
if (!byClient.has(id)) byClient.set(id, createClaudeGatewayHandler({ provider: source, apiKey: identities()[id], env, log, performance: legacy.claudePerformance,
|
|
241
|
+
validateConversation: (body, headers) => validateConversation(body, headers, source, id),
|
|
242
|
+
onRequest() { lastClients[id] = new Date().toISOString(); } }));
|
|
243
|
+
const finish = track(source), headers = req.headers;
|
|
244
|
+
req.headers = { ...headers, "x-ccdx-client": id === "claude_app" ? "claude-app" : "claude-code" };
|
|
245
|
+
try { return await byClient.get(id)(req, res); } finally { req.headers = headers;finish(); }
|
|
246
|
+
},
|
|
247
|
+
dashboardProviders() {
|
|
248
|
+
const builtins = legacy.dashboardProviders();if (!managed) return builtins.filter(source => source.enabled);
|
|
249
|
+
const definitions = snapshot(true).providers, performance = legacy.claudePerformance.snapshot();
|
|
250
|
+
return definitions.filter(item => item.enabled).map(item => {
|
|
251
|
+
const old = builtins.find(source => source.id === item.id), source = item.builtin ? null : getSource(item.id);
|
|
252
|
+
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 }));
|
|
255
|
+
return { ...old, id: item.id, name: item.name, enabled: true, generation: old?.generation || source?.registry.generation || 1,
|
|
256
|
+
state: old?.state || "configured", auth: old?.auth || { state: "saved", token_cached: false },
|
|
257
|
+
selection: { codex: clients.some(client => client.id === "codex"), models_required: item.id !== "github" }, clients,
|
|
258
|
+
models: old?.models || { count: item.model_count, source: "configured" },
|
|
259
|
+
requests: performance.by_route.messages.by_provider[item.id] ? { ...performance.by_route.messages.by_provider[item.id].terminal_outcomes.totals,
|
|
260
|
+
active: performance.by_route.messages.by_provider[item.id].active, total: performance.by_route.messages.by_provider[item.id].requests } : null };
|
|
261
|
+
});
|
|
262
|
+
},
|
|
263
|
+
dashboardCatalog(input = {}) {
|
|
264
|
+
if (!input.provider?.startsWith("api_")) return legacy.dashboardCatalog(input);
|
|
265
|
+
if (!enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
|
|
266
|
+
return getSource(input.provider).publicCatalog(CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider)));
|
|
267
|
+
},
|
|
268
|
+
async action(input) {
|
|
269
|
+
if (managed && input.action === "auto-review" && input.provider && input.provider !== this.selection().codex) throw accessError("ccdx_client_source_mismatch", 409);
|
|
270
|
+
if (managed && input.action === "auto-review" && (!binding("codex").enabled || !binding("codex").source)) throw accessError("ccdx_client_source_disabled", 503);
|
|
271
|
+
if (managed && ["on", "off", "remove"].includes(input.action)) {
|
|
272
|
+
if (input.action === "remove" && legacy.snapshot().m365.active_requests > 0) throw accessError("ccdx_source_busy", 409);
|
|
273
|
+
const replacements = Object.fromEntries(CLIENT_IDS.filter(id => binding(id).source === "m365" && binding(id).enabled).map(id => [id, null]));
|
|
274
|
+
await this.manageConnections({ operation: "provider", id: "m365", enabled: input.action === "on", replacements });
|
|
275
|
+
if (input.action === "remove") legacy.removeM365SavedProfile();return this.snapshot();
|
|
276
|
+
}
|
|
277
|
+
if (managed && input.action === "switch" && !binding("codex").enabled) throw accessError("ccdx_client_source_disabled", 503);
|
|
278
|
+
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,
|
|
280
|
+
model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort });return this.snapshot(); }
|
|
281
|
+
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
|
+
if (input.action === "auto-review" && managed && legacy.selection().codex !== "github") await legacy.action({ action: "switch", provider: "github" });
|
|
283
|
+
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(); }
|
|
285
|
+
return result;
|
|
286
|
+
},
|
|
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(); },
|
|
288
|
+
};
|
|
289
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHmac } from "node:crypto";
|
|
4
|
+
import { accessSettingsPath, accessError } from "./access-settings.mjs";
|
|
5
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
6
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
7
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
8
|
+
|
|
9
|
+
// Correlation only: retain hashes, never prompts, session IDs or credentials.
|
|
10
|
+
export function createConversationSourceGuard(options = {}) {
|
|
11
|
+
const file = path.join(path.dirname(accessSettingsPath(options)), "conversation-sources.json");let cache;
|
|
12
|
+
return (client, profile, body, headers = {}, salt) => {
|
|
13
|
+
const hash = value => createHmac("sha256", salt).update(value).digest("hex");
|
|
14
|
+
const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
|
|
15
|
+
const hasHistory = Boolean(body.previous_response_id) || items.filter(item => item?.role === "user").length > 1
|
|
16
|
+
|| items.some(item => item?.role === "assistant" || item?.role === "tool" || /(?:call|output|reasoning|compaction)/.test(item?.type || "")
|
|
17
|
+
|| Array.isArray(item?.content) && item.content.some(part => part?.type === "tool_result" || part?.type === "thinking" || part?.type === "redacted_thinking"));
|
|
18
|
+
let session = headers.session_id || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
|
|
19
|
+
if (!session && typeof body.metadata?.user_id === "string") {
|
|
20
|
+
try { session = JSON.parse(body.metadata.user_id)?.session_id; } catch { session = /(?:^|_)session_([\w-]{8,128})$/.exec(body.metadata.user_id)?.[1]; }
|
|
21
|
+
}
|
|
22
|
+
const identified = typeof session === "string" && session.length > 0 && session.length <= 512 && !/[\u0000-\u001f\u007f]/.test(session);
|
|
23
|
+
const first = items.find(item => item?.role === "user"), input = identified ? `session\0${session}` : first ? `first\0${JSON.stringify(first)}` : typeof body.input === "string" ? `first\0${body.input}` : null;
|
|
24
|
+
if (!input) return;
|
|
25
|
+
const key = hash(client + "\0" + input), owner = hash(profile);
|
|
26
|
+
if (cache?.[key] === owner) return;
|
|
27
|
+
if (cache?.[key] && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
|
|
28
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
29
|
+
withFileLockSync(`${file}.lock`, () => {
|
|
30
|
+
let owners = {};
|
|
31
|
+
try { owners = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 256 * 1024 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_conversation_state_invalid", 409); }
|
|
32
|
+
if (!owners || typeof owners !== "object" || Array.isArray(owners) || Object.keys(owners).length > 1024
|
|
33
|
+
|| Object.entries(owners).some(([key, owner]) => !/^[a-f0-9]{64}$/.test(key) || !/^[a-f0-9]{64}$/.test(owner))) throw accessError("ccdx_conversation_state_invalid", 409);
|
|
34
|
+
if (owners[key] && owners[key] !== owner && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
|
|
35
|
+
if (owners[key] !== owner) {
|
|
36
|
+
owners[key] = owner;while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
|
|
37
|
+
atomicWriteFileSync(file, JSON.stringify(owners) + "\n", { mode: 0o600 });
|
|
38
|
+
}
|
|
39
|
+
cache = owners;
|
|
40
|
+
});
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const el = id => document.getElementById(id), root = el("connection-sources");if (!root) return;
|
|
3
|
+
const words = (node, key, args) => globalThis.ccdxLanguage.set(node, key, args), format = key => globalThis.ccdxLanguage.format(key);
|
|
4
|
+
let data = null, editing = null, editingClient = null, disabling = null, models = [], busy = false, generation = 0;
|
|
5
|
+
const apiForm = el("connection-api-form"), clientForm = el("connection-client-form");
|
|
6
|
+
const node = (tag, text, className) => { const item = document.createElement(tag);if (text !== undefined) item.textContent = text;if (className) item.className = className;return item; };
|
|
7
|
+
const source = id => data.providers.find(item => item.id === id), client = id => data.clients.find(item => item.id === id);
|
|
8
|
+
const compatible = (provider, id) => provider.protocols.includes(id === "codex" ? "responses" : "messages");
|
|
9
|
+
const message = key => words(el("connection-note"), key);
|
|
10
|
+
function button(key, action) { const item = node("button");item.type = "button";words(item, key);item.addEventListener("click", action);return item; }
|
|
11
|
+
function check(name, value, checked, text) { const label = node("label"), input = node("input");input.type = "checkbox";input.name = name;input.value = value;input.checked = checked;label.append(input, node("span", text));return label; }
|
|
12
|
+
async function api(input) {
|
|
13
|
+
const response = await fetch("/_ccdx/ui/connections", { method: input ? "POST" : "GET", headers: { "X-CCDX-Dashboard": "1", ...(input ? { "Content-Type": "application/json" } : {}) },
|
|
14
|
+
cache: "no-store", signal: AbortSignal.timeout(35000), ...(input ? { body: JSON.stringify(input) } : {}) });
|
|
15
|
+
const result = await response.json();if (!response.ok) throw new Error(result.error || "ccdx_connections_action_failed");
|
|
16
|
+
if (result.source !== "connections" || !Array.isArray(result.providers) || !Array.isArray(result.clients)) throw new Error("ccdx_connections_unavailable");return result;
|
|
17
|
+
}
|
|
18
|
+
function panels(which = "list") {
|
|
19
|
+
root.hidden = el("connection-clients").hidden = el("connection-disabled").hidden = which !== "list";
|
|
20
|
+
el("connection-editor").hidden = which !== "api";el("connection-client-editor").hidden = which !== "client";el("connection-disable-editor").hidden = which !== "disable";
|
|
21
|
+
apiForm.elements.key.value = "";
|
|
22
|
+
}
|
|
23
|
+
function choice(options, selected, pause = true) {
|
|
24
|
+
const select = node("select");if (pause) { const item = node("option");item.value = "";words(item, "api_pause");select.append(item); }
|
|
25
|
+
for (const value of options) { const item = node("option", value.name);item.value = value.id;select.append(item); }select.value = selected || "";return select;
|
|
26
|
+
}
|
|
27
|
+
function list() {
|
|
28
|
+
const providerList = el("connection-source-list"), clientList = el("connection-client-list"), disabledList = el("connection-disabled-list");
|
|
29
|
+
providerList.replaceChildren();clientList.replaceChildren();disabledList.replaceChildren();
|
|
30
|
+
for (const provider of data.providers) {
|
|
31
|
+
const row = node("div", undefined, "connection-row"), info = node("div"), actions = node("div", undefined, "connection-actions");info.append(node("h3", provider.name));
|
|
32
|
+
if (!provider.builtin) info.append(node("p", provider.base_url, "hint"));
|
|
33
|
+
if (provider.enabled) {
|
|
34
|
+
const allowed = data.clients.filter(c => c.enabled && c.allowed.includes(provider.id)).map(c => c.name).join(" / ");
|
|
35
|
+
const line = node("p", undefined, "hint");words(line, "api_allowed_summary", { clients: allowed || format("api_none") });info.append(line);
|
|
36
|
+
actions.append(button(provider.builtin ? "api_account" : "api_manage", () => provider.builtin ? (location.hash = "models", window.dispatchEvent(new CustomEvent("ccdx:choose-source", { detail: { id: provider.id } }))) : editApi(provider)));
|
|
37
|
+
const toggle = node("input");toggle.type = "checkbox";toggle.checked = true;toggle.setAttribute("role", "switch");toggle.setAttribute("aria-label", format("api_disable_source") + " " + provider.name);
|
|
38
|
+
toggle.addEventListener("change", () => { toggle.checked = true;disableSource(provider); });actions.append(toggle);
|
|
39
|
+
} else actions.append(button("api_restore", () => void change({ operation: "provider", id: provider.id, enabled: true })));
|
|
40
|
+
row.append(info, actions);(provider.enabled ? providerList : disabledList).append(row);
|
|
41
|
+
}
|
|
42
|
+
for (const c of data.clients) {
|
|
43
|
+
const row = node("div", undefined, "connection-row"), info = node("div"), actions = node("div", undefined, "connection-actions");info.append(node("h3", c.name));
|
|
44
|
+
const note = node("p", undefined, "hint");words(note, c.enabled ? "api_current_summary" : "api_client_disabled", { source: source(c.source)?.name || format("api_pause") });info.append(note);
|
|
45
|
+
if (c.enabled) {
|
|
46
|
+
actions.append(button("api_manage", () => editClient(c)));
|
|
47
|
+
const toggle = node("input");toggle.type = "checkbox";toggle.checked = true;toggle.setAttribute("role", "switch");toggle.setAttribute("aria-label", format("api_close_client") + " " + c.name);
|
|
48
|
+
toggle.addEventListener("change", () => { toggle.checked = true;void change({ operation: "client", id: c.id, enabled: false, source: null, allowed: c.allowed }); });actions.append(toggle);
|
|
49
|
+
} else actions.append(button("api_restore", () => void change({ operation: "client", id: c.id, enabled: true, source: null, allowed: c.allowed })));
|
|
50
|
+
row.append(info, actions);(c.enabled ? clientList : disabledList).append(row);
|
|
51
|
+
}
|
|
52
|
+
if (!disabledList.children.length) { const empty = node("p", undefined, "hint");words(empty, "api_no_disabled");disabledList.append(empty); }
|
|
53
|
+
for (const route of ["codex", "claude"]) {
|
|
54
|
+
const visible = route === "codex" ? client("codex").enabled : data.clients.some(c => c.enabled && c.id.startsWith("claude_"));
|
|
55
|
+
const link = document.querySelector(`[data-route="${route}"]`);if (link) link.hidden = !visible;
|
|
56
|
+
if (!visible && location.hash === "#" + route) location.hash = "system";
|
|
57
|
+
}
|
|
58
|
+
const m365Toggle = el("m365-enabled")?.closest(".setting-row");if (m365Toggle) m365Toggle.hidden = true;
|
|
59
|
+
for (const link of document.querySelectorAll("[data-source-link]")) { const id = link.dataset.sourceLink;if (["m365", "github"].includes(id)) link.hidden = !source(id)?.enabled; }
|
|
60
|
+
globalThis.ccdxConnectionNames = Object.fromEntries(data.providers.map(p => [p.id, p.name]));
|
|
61
|
+
}
|
|
62
|
+
async function load() {
|
|
63
|
+
if (busy) return;const current = ++generation;
|
|
64
|
+
try { const result = await api();if (current !== generation) return;data = result;list(); }
|
|
65
|
+
catch (error) { if (location.hash === "#system") message(error.message); }
|
|
66
|
+
}
|
|
67
|
+
async function change(input, done) {
|
|
68
|
+
if (busy) return;busy = true;generation++;root.closest("[data-view]").setAttribute("aria-busy", "true");
|
|
69
|
+
try { data = await api(input);list();done?.(data);if (!done) {
|
|
70
|
+
panels();let key = input.operation === "save_api" ? "api_config_saved" : input.operation === "provider" ? input.enabled ? "api_provider_enabled" : "api_provider_disabled"
|
|
71
|
+
: !input.enabled ? "api_client_disabled" : !input.source ? "api_client_enabled" : "api_saved";
|
|
72
|
+
const setup = data.clients.find(c => c.id === input.id)?.setup;
|
|
73
|
+
if (input.operation === "client" && input.source && ["preserved", "partially_preserved"].includes(setup)) key = "api_client_preserved";
|
|
74
|
+
if (input.operation === "client" && input.source && setup === "configuration_unavailable") key = "api_client_config_failed";
|
|
75
|
+
if (input.operation === "client" && input.source && setup === "not_installed") key = "api_client_not_installed";
|
|
76
|
+
message(key);
|
|
77
|
+
}window.dispatchEvent(new CustomEvent("ccdx:connections"));void dashboardRefresh.refresh("auth", { force: true });void dashboardRefresh.refresh("status", { force: true }); }
|
|
78
|
+
catch (error) { message(error.message); }
|
|
79
|
+
finally { busy = false;root.closest("[data-view]").removeAttribute("aria-busy"); }
|
|
80
|
+
}
|
|
81
|
+
function modelRows() {
|
|
82
|
+
const body = el("connection-models");body.replaceChildren();
|
|
83
|
+
for (const model of models) {
|
|
84
|
+
const tr = node("tr"), name = node("td", model.id), apis = node("td"), actions = node("td"), group = node("div", undefined, "connection-checks");
|
|
85
|
+
for (const protocol of ["messages", "responses", "chat"]) {
|
|
86
|
+
const label = check("model-api", protocol, model.protocols.includes(protocol), protocol === "chat" ? "Chat" : protocol === "messages" ? "Messages" : "Responses");
|
|
87
|
+
label.firstChild.addEventListener("change", e => { model.protocols = [...new Set([...model.protocols.filter(api => api !== protocol), ...(e.target.checked ? [protocol] : [])])]; });group.append(label);
|
|
88
|
+
}
|
|
89
|
+
apis.append(group);actions.append(button("api_remove_model", () => { models = models.filter(item => item !== model);modelRows(); }));tr.append(name, apis, actions);body.append(tr);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function setEndpoints(base, endpoints) { for (const [api, path] of [["messages", "messages"], ["responses", "responses"], ["chat", "chat/completions"]]) apiForm.elements[api + "_url"].value = endpoints?.[api] || base.replace(/\/+$/, "") + "/" + path; }
|
|
93
|
+
function editApi(provider) {
|
|
94
|
+
editing = provider?.id || null;panels("api");apiForm.reset();words(el("connection-editor-title"), provider ? "api_manage" : "api_add");
|
|
95
|
+
apiForm.elements.name.value = provider?.name || "";apiForm.elements.base.value = provider?.base_url || "";
|
|
96
|
+
apiForm.elements.key.required = !provider;globalThis.ccdxLanguage.set(apiForm.elements.key, provider ? "api_key_keep" : "api_key_enter", {}, "placeholder");
|
|
97
|
+
apiForm.elements.auth_header.value = provider?.auth_header || "x-api-key";
|
|
98
|
+
apiForm.elements.key_env.value = provider?.key_env || "";keyMode();
|
|
99
|
+
for (const input of apiForm.querySelectorAll('[name="protocol"]')) input.checked = provider ? provider.protocols.includes(input.value) : input.value !== "chat";
|
|
100
|
+
setEndpoints(provider?.base_url || "", provider?.endpoints);
|
|
101
|
+
const allowed = el("connection-allowed-clients");allowed.replaceChildren(...data.clients.filter(c => c.enabled).map(c => check("allowed", c.id, c.allowed.includes(editing), c.name)));
|
|
102
|
+
models = structuredClone(provider?.models || []);modelRows();el("connection-discover").disabled = !editing;el("connection-model-id").value = "";
|
|
103
|
+
}
|
|
104
|
+
apiForm.elements.base.addEventListener("change", () => setEndpoints(apiForm.elements.base.value));
|
|
105
|
+
function keyMode() { const external = Boolean(apiForm.elements.key_env.value.trim());apiForm.elements.key.disabled = external;apiForm.elements.key.required = !external && !editing;if (external) apiForm.elements.key.value = ""; }
|
|
106
|
+
apiForm.elements.key_env.addEventListener("input", keyMode);
|
|
107
|
+
apiForm.addEventListener("submit", e => {
|
|
108
|
+
e.preventDefault();if (busy || !apiForm.reportValidity()) return;
|
|
109
|
+
const endpoints = Object.fromEntries([...apiForm.querySelectorAll('[name="protocol"]:checked')].map(input => [input.value, apiForm.elements[input.value + "_url"].value.trim()]));
|
|
110
|
+
const key = apiForm.elements.key.value;apiForm.elements.key.value = "";
|
|
111
|
+
void change({ operation: "save_api", ...(editing ? { id: editing } : {}), key,
|
|
112
|
+
config: { name: apiForm.elements.name.value.trim(), base_url: apiForm.elements.base.value.trim().replace(/\/+$/, ""), endpoints, auth_header: apiForm.elements.auth_header.value, models,
|
|
113
|
+
...(apiForm.elements.key_env.value.trim() ? { key_env: apiForm.elements.key_env.value.trim() } : {}) },
|
|
114
|
+
allowed: [...apiForm.querySelectorAll('[name="allowed"]:checked')].map(input => input.value).concat(data.clients.filter(c => !c.enabled && c.allowed.includes(editing)).map(c => c.id)) });
|
|
115
|
+
});
|
|
116
|
+
el("connection-model-add").addEventListener("click", () => {
|
|
117
|
+
const id = el("connection-model-id").value.trim();if (!id || models.some(model => model.id === id) || models.length >= 500) return;
|
|
118
|
+
models.push({ id, protocols: [] });el("connection-model-id").value = "";modelRows();
|
|
119
|
+
});
|
|
120
|
+
el("connection-discover").addEventListener("click", () => void change({ operation: "discover", id: editing }, result => {
|
|
121
|
+
const known = new Map(models.map(model => [model.id, model]));for (const model of result.discovered || []) if (!known.has(model.id)) known.set(model.id, model);
|
|
122
|
+
models = [...known.values()].slice(0, 500);modelRows();message("api_models_read");
|
|
123
|
+
}));
|
|
124
|
+
function clientModels() {
|
|
125
|
+
const c = client(editingClient), provider = source(el("connection-current").value), selector = el("connection-current-model");
|
|
126
|
+
el("connection-current-model-row").hidden = c.id !== "codex" || provider?.builtin !== false;
|
|
127
|
+
selector.replaceChildren(...(provider?.models || []).filter(model => model.protocols.includes("responses")).map(model => { const item = node("option", model.id);item.value = model.id;return item; }));
|
|
128
|
+
if ([...selector.options].some(option => option.value === c.model)) selector.value = c.model;
|
|
129
|
+
}
|
|
130
|
+
function clientSources() {
|
|
131
|
+
const allowed = new Set([...el("connection-client-allowed").querySelectorAll("input:checked")].map(input => input.value));
|
|
132
|
+
const before = el("connection-current").value, replacement = choice(data.providers.filter(p => p.enabled && allowed.has(p.id) && compatible(p, editingClient)), before);
|
|
133
|
+
el("connection-current").replaceChildren(...replacement.childNodes);if ([...el("connection-current").options].some(option => option.value === before)) el("connection-current").value = before;clientModels();
|
|
134
|
+
}
|
|
135
|
+
function editClient(c) {
|
|
136
|
+
editingClient = c.id;panels("client");el("connection-client-title").textContent = c.name;
|
|
137
|
+
const allowed = el("connection-client-allowed");allowed.replaceChildren(...data.providers.filter(p => p.enabled && compatible(p, c.id)).map(p => check("source", p.id, c.allowed.includes(p.id), p.name)));
|
|
138
|
+
allowed.querySelectorAll("input").forEach(input => input.addEventListener("change", clientSources));
|
|
139
|
+
const select = choice(data.providers.filter(p => p.enabled && c.allowed.includes(p.id) && compatible(p, c.id)), c.source);
|
|
140
|
+
el("connection-current").replaceChildren(...select.childNodes);el("connection-current").value = c.source || "";clientModels();
|
|
141
|
+
}
|
|
142
|
+
el("connection-current").addEventListener("change", clientModels);
|
|
143
|
+
clientForm.addEventListener("submit", e => { e.preventDefault();const c = client(editingClient), selected = el("connection-current").value;
|
|
144
|
+
void change({ operation: "client", id: c.id, enabled: true, source: selected || null, allowed: [...el("connection-client-allowed").querySelectorAll("input:checked")].map(input => input.value).concat(c.allowed.filter(id => !source(id)?.enabled)),
|
|
145
|
+
...(selected.startsWith("api_") && c.id === "codex" ? { model: el("connection-current-model").value, auto_review_model: el("connection-current-model").value } : {}) });
|
|
146
|
+
});
|
|
147
|
+
function disableSource(provider) {
|
|
148
|
+
const affected = data.clients.filter(c => c.enabled && c.source === provider.id);
|
|
149
|
+
if (!affected.length) { void change({ operation: "provider", id: provider.id, enabled: false });return; }
|
|
150
|
+
disabling = provider.id;panels("disable");const area = el("connection-replacements");area.replaceChildren();
|
|
151
|
+
for (const c of affected) { const label = node("label", c.name), select = choice(data.providers.filter(p => p.id !== provider.id && p.enabled && c.allowed.includes(p.id) && compatible(p, c.id)));select.name = c.id;label.append(select);area.append(label); }
|
|
152
|
+
}
|
|
153
|
+
el("connection-disable-form").addEventListener("submit", e => { e.preventDefault();void change({ operation: "provider", id: disabling, enabled: false,
|
|
154
|
+
replacements: Object.fromEntries([...el("connection-replacements").querySelectorAll("select")].map(select => [select.name, select.value || null])) }); });
|
|
155
|
+
el("connection-add").addEventListener("click", () => { if (data) editApi(); });
|
|
156
|
+
for (const id of ["connection-cancel", "connection-client-cancel", "connection-disable-cancel"]) el(id).addEventListener("click", () => panels());
|
|
157
|
+
window.addEventListener("hashchange", () => { apiForm.elements.key.value = "";if (["#system", "#claude", "#codex"].includes(location.hash)) void load(); });
|
|
158
|
+
window.addEventListener("ccdx:choose-source", event => { if (typeof event.detail?.id === "string" && providerEntries.some(p => p.id === event.detail.id)) chooseProvider(event.detail.id); });
|
|
159
|
+
new MutationObserver(() => { if (data) list(); }).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
|
|
160
|
+
globalThis.ccdxConnections = { load, editClient: id => { if (data && client(id)) { location.hash = "system";editClient(client(id)); } } };
|
|
161
|
+
for (const button of document.querySelectorAll("[data-client-access]")) button.addEventListener("click", () => globalThis.ccdxConnections.editClient(button.dataset.clientAccess));
|
|
162
|
+
void load();
|
|
163
|
+
})();
|
package/src/dashboard/console.js
CHANGED
|
@@ -88,15 +88,17 @@
|
|
|
88
88
|
syncReviewButton();
|
|
89
89
|
}
|
|
90
90
|
function syncSources() {
|
|
91
|
-
const selector = el("source-provider"),
|
|
91
|
+
const selector = el("source-provider"), paused = settings?.providers?.connections?.managed && settings.providers.codex_provider === null;
|
|
92
|
+
const selected = sourceDirty ? selector.value : paused ? "" : settings?.providers?.codex_provider || selector.value;
|
|
92
93
|
const entries = providerEntries.filter(source => source.selection?.codex);
|
|
93
|
-
const signature = JSON.stringify(entries.map(source => [source.id, source.name]));
|
|
94
|
+
const signature = JSON.stringify([paused, entries.map(source => [source.id, source.name])]);
|
|
94
95
|
if (selector.dataset.sources !== signature) {
|
|
95
96
|
selector.replaceChildren(...entries.map(source => {
|
|
96
97
|
const option = document.createElement("option");option.value = source.id;option.textContent = source.name;return option;
|
|
97
98
|
}));selector.dataset.sources = signature;
|
|
99
|
+
if (paused) { const option = document.createElement("option");option.value = "";label(option, "api_pause");selector.prepend(option); }
|
|
98
100
|
}
|
|
99
|
-
if (entries.some(source => source.id === selected)) selector.value = selected;
|
|
101
|
+
if (paused && !sourceDirty || entries.some(source => source.id === selected)) selector.value = selected;
|
|
100
102
|
el("apply-source").disabled = settingsPending || !sourceReady();
|
|
101
103
|
syncReviewButton();
|
|
102
104
|
}
|
|
@@ -145,7 +147,7 @@
|
|
|
145
147
|
el("m365-control-note").replaceChildren();
|
|
146
148
|
if (state) {
|
|
147
149
|
const source = document.createElement("span"), m365 = document.createElement("span");
|
|
148
|
-
label(source, "codex_source_source", { source: providerEntries.find(entry => entry.id === state.codex_provider)?.name || state.codex_provider });
|
|
150
|
+
label(source, "codex_source_source", { source: providerEntries.find(entry => entry.id === state.codex_provider)?.name || (state.codex_provider === null ? { key: "api_pause" } : state.codex_provider) });
|
|
149
151
|
const status = { ready: "ready", checking: "checking", disabled: "disabled", unsupported: "unsupported", idle: "unknown", unavailable: "unavailable" }[state.m365?.state] || "unknown";
|
|
150
152
|
label(m365, "microsoft_365_state", { state: { key: status } });
|
|
151
153
|
el("source-control-note").replaceChildren(source);el("m365-control-note").append(m365);
|