codex-copilot-dx 1.2.19 → 1.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,10 @@
1
- import fs from "node:fs";
2
1
  import os from "node:os";
3
2
  import path from "node:path";
4
3
  import { execFile } from "node:child_process";
5
4
  import { promisify } from "node:util";
6
5
  import { readAdapterStatus } from "./cli-status.mjs";
6
+ import { codexPaths } from "./codex-paths.mjs";
7
+ import { readBoundedFileSync } from "./bounded-file.mjs";
7
8
  import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
8
9
 
9
10
  export function parseRunningCodexApps(stdout) {
@@ -20,13 +21,13 @@ export function parseRunningCodexApps(stdout) {
20
21
  }
21
22
 
22
23
  export async function inspectCodexClient({
23
- home = os.homedir(), platform = process.platform, running,
24
- host, port, fetchImpl = fetch, readFileFn = fs.readFileSync,
24
+ home = os.homedir(), env = process.env, platform = process.platform, running,
25
+ host, port, fetchImpl = fetch, readFileFn = (file, encoding) => readBoundedFileSync(file, { encoding, maxBytes: 8 * 1024 * 1024 }),
25
26
  execFileFn = promisify(execFile), readStatus = readAdapterStatus,
26
27
  } = {}) {
27
28
  const checks = [];
28
29
  if (platform === "darwin") {
29
- const seen = new Set();
30
+ const seen = new Set(), versions = new Set();
30
31
  for (const root of ["/Applications", path.join(home, "Applications")]) {
31
32
  for (const name of ["ChatGPT.app", "Codex.app"]) {
32
33
  try {
@@ -37,8 +38,21 @@ export async function inspectCodexClient({
37
38
  seen.add(`${name}/${version}`);
38
39
  }
39
40
  } catch {}
41
+ try {
42
+ const metadata = JSON.parse(readFileFn(path.join(root, name, "Contents", "Resources", "codex-cli", "codex-package.json"), "utf8"));
43
+ if (/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+_-]+)?$/.test(metadata.version || "")) versions.add(metadata.version);
44
+ } catch { /* Older app bundles may not publish CLI package metadata. */ }
40
45
  }
41
46
  }
47
+ for (const version of versions) checks.push({ kind: "info", message: `Bundled Codex CLI: ${version}` });
48
+ try {
49
+ const cache = JSON.parse(readFileFn(path.join(codexPaths({ home, env }).directory, "models_cache.json"), "utf8"));
50
+ const core = value => /^(\d+\.\d+\.\d+)/.exec(String(value || ""))?.[1];
51
+ const current = new Set([...versions].map(core));
52
+ if (current.size === 1 && core(cache.client_version) && !current.has(core(cache.client_version))) {
53
+ checks.push({ kind: "warn", message: `Model cache client ${core(cache.client_version)} differs from bundled CLI ${[...current][0]}; fully quit and reopen the App once after updating. This does not prove a failed catalog.` });
54
+ }
55
+ } catch { /* Cache contents are optional and never repaired by this read-only check. */ }
42
56
  try {
43
57
  // comm contains executable names, never command-line arguments or environments.
44
58
  const { stdout } = await execFileFn("ps", ["-axo", "pid=,comm="], { timeout: 1500, maxBuffer: 256 * 1024, encoding: "utf8" });
@@ -65,6 +79,6 @@ export async function inspectCodexClient({
65
79
  } else checks.push({ kind: "info", message: "No client model-catalog request observed by this adapter" });
66
80
  } catch { checks.push({ kind: "info", message: "Client model-catalog diagnostics unavailable from the running adapter" }); }
67
81
  }
68
- checks.push({ kind: "info", message: "App-internal model cache is not externally verified; process age alone does not prove a stale catalog" });
82
+ checks.push({ kind: "info", message: "App adoption of the model cache is not externally verified; process age alone does not prove a stale catalog" });
69
83
  return checks;
70
84
  }
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import { codexPaths } from "./codex-paths.mjs";
4
+ import { codexBaseUrlManaged } from "./codex-api-config.mjs";
4
5
  import { isDeepStrictEqual } from "node:util";
5
6
  import { createHash } from "node:crypto";
6
7
  import { parse } from "smol-toml";
@@ -53,12 +54,12 @@ function unmanagedSettings(config) {
53
54
  return remaining;
54
55
  }
55
56
 
56
- function startupPreview(content, config, host, port) {
57
+ function startupPreview(content, config, host, port, preserveBaseUrl = false) {
57
58
  let updated;
58
59
  try {
59
60
  updated = content === null
60
61
  ? { content: initialCodexConfig(port, host), changed: true }
61
- : computeUpdatedCodexConfig(content, port, host);
62
+ : computeUpdatedCodexConfig(content, port, host, { preserveBaseUrl });
62
63
  } catch {
63
64
  return { kind: "err", message: "Startup configuration cannot be edited safely; review the file before starting ccdx" };
64
65
  }
@@ -165,7 +166,8 @@ export function inspectCodexConfig({ home = os.homedir(), env: processEnv = proc
165
166
  } else {
166
167
  checks.push({ kind: "err", message: "features.context_management must be a boolean for the basic feature flag" });
167
168
  }
168
- checks.push(startupPreview(content, config, host, port));
169
+ try { checks.push(startupPreview(content, config, host, port, codexBaseUrlManaged({ home, env: processEnv }))); }
170
+ catch { checks.push({ kind: "err", message: "Codex gateway ownership cannot be read; startup base URL changes are blocked" }); }
169
171
  return checks;
170
172
  }
171
173
 
@@ -182,7 +184,7 @@ export function repairCodexConfig(options = {}) {
182
184
  throw Object.assign(new Error("config_preview_changed"), { code: "config_preview_changed", statusCode: 409 });
183
185
  }
184
186
  const next = content === null ? { content: initialCodexConfig(port, host), changed: true }
185
- : computeUpdatedCodexConfig(content, port, host);
187
+ : computeUpdatedCodexConfig(content, port, host, { preserveBaseUrl: codexBaseUrlManaged(options) });
186
188
  if (!next.changed) return { status: "unchanged", changed: false };
187
189
  const before = content === null ? {} : parseConfig(content);
188
190
  if (!isDeepStrictEqual(unmanagedSettings(before), unmanagedSettings(parseConfig(next.content)))) {
package/src/config.mjs CHANGED
@@ -5,6 +5,7 @@ import { adapterBaseUrl } from "./running-adapter.mjs";
5
5
  import { isLoopbackHost } from "./security.mjs";
6
6
  import { codexTomlStatements, configValue, parseCodexToml, validateManagedConfigEdit } from "./config-toml.mjs";
7
7
  import { codexPaths } from "./codex-paths.mjs";
8
+ import { codexBaseUrlManaged } from "./codex-api-config.mjs";
8
9
  import { withFileLockSync } from "./lock.mjs";
9
10
 
10
11
  const MODEL_CONTEXT_WINDOW = 1_000_000;
@@ -204,7 +205,7 @@ export function computeUpdatedCodexConfig(
204
205
  content,
205
206
  adapterPort = 2026,
206
207
  adapterHost = "127.0.0.1",
207
- { imageProviderEnabled } = {},
208
+ { imageProviderEnabled, preserveBaseUrl = false } = {},
208
209
  ) {
209
210
  const config = parseCodexToml(content);
210
211
  const baseUrl = `${adapterBaseUrl(adapterHost, adapterPort)}/v1`;
@@ -213,7 +214,8 @@ export function computeUpdatedCodexConfig(
213
214
 
214
215
  let changed = false;
215
216
  const openaiLine = `openai_base_url = "${baseUrl}"`;
216
- if (!Object.hasOwn(config, "openai_base_url")) {
217
+ if (preserveBaseUrl) { /* The gateway journal owns this field, including preserved user edits. */ }
218
+ else if (!Object.hasOwn(config, "openai_base_url")) {
217
219
  lines.unshift(openaiLine);
218
220
  changed = true;
219
221
  } else {
@@ -287,6 +289,7 @@ function ensureCodexConfigUnlocked(adapterPort = 2026, {
287
289
  host = "127.0.0.1",
288
290
  imageProviderEnabled = false,
289
291
  log = console.log,
292
+ ...options
290
293
  } = {}) {
291
294
  const baseUrl = `${adapterBaseUrl(host, adapterPort)}/v1`;
292
295
 
@@ -303,12 +306,12 @@ function ensureCodexConfigUnlocked(adapterPort = 2026, {
303
306
  // failures must not roll it back or close an otherwise usable GPT adapter.
304
307
  const core = content === undefined
305
308
  ? { content: initialCodexConfig(adapterPort, host), changed: true }
306
- : computeUpdatedCodexConfig(content, adapterPort, host);
309
+ : computeUpdatedCodexConfig(content, adapterPort, host, { preserveBaseUrl: codexBaseUrlManaged({ ...options, filePath }) });
307
310
  if (!core.changed) {
308
- log(status("ok", `Codex already points to ${baseUrl}`));
311
+ log(status("ok", parseCodexToml(core.content).openai_base_url === baseUrl ? `Codex already points to ${baseUrl}` : "Codex configuration unchanged; existing base URL preserved"));
309
312
  } else {
310
313
  atomicWriteFileIfChangedSync(filePath, core.content);
311
- log(status("ok", content === undefined ? `Created Codex configuration: ${filePath}` : `Configured Codex base URL: ${baseUrl}`));
314
+ log(status("ok", content === undefined ? `Created Codex configuration: ${filePath}` : parseCodexToml(core.content).openai_base_url === baseUrl ? `Configured Codex base URL: ${baseUrl}` : "Codex startup settings updated; existing base URL preserved"));
312
315
  }
313
316
  // Disabled means no image maintenance, including no implicit removal of old
314
317
  // or user-owned entries. Explicit disable-image owns the cleanup operation.
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import { randomBytes } from "node:crypto";
3
3
  import { accessSettingsPath, readAccessSettings, updateAccessSettings, checkedApi, checkedAccessSettings, accessError, CLIENT_IDS, CLIENT_NAMES } from "./access-settings.mjs";
4
4
  import { createApiSecretStore, checkedApiKey } from "./api-secrets.mjs";
5
+ import { createApiCatalogRefresh } from "./api-catalog-refresh.mjs";
5
6
  import { createApiProvider } from "./providers/api.mjs";
6
7
  import { readClientGatewayKeys, gatewayClient } from "./client-gateway-keys.mjs";
7
8
  import { createClaudeGatewayHandler } from "./claude-gateway.mjs";
@@ -25,9 +26,12 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
25
26
  let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
26
27
  const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
27
28
  const retiredSecrets = new Map(), cleanups = new Set(), plans = new Map(), discoveries = new Map();
28
- const catalogReads = new Map(), stopping = new AbortController();let refreshFlight;
29
+ const catalogRefresh = createApiCatalogRefresh({ config: id => settings.apis.find(api => api.id === id), source: getSource, track,
30
+ revision: api => deploymentRevision(api, env), now,
31
+ commit: (...args) => enqueue(() => applyCatalog(...args)),
32
+ onState: (id, state) => state ? discoveries.set(id, state) : discoveries.delete(id) });
29
33
  const capabilitySupport = inspectClaudeCapabilitySupport(options);
30
- let sharedSync = null, syncFlight = null, syncAgain = false;
34
+ let sharedSync = null, syncFlight = null, syncAgain = false;const syncTargets = new Set();
31
35
  function cleanSecrets(id) {
32
36
  const refs = retiredSecrets.get(id);if (!refs) return;
33
37
  for (const ref of refs) {
@@ -94,7 +98,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
94
98
  plans.clear();
95
99
  settings = structuredClone(updateAccessSettings(current => {
96
100
  if (JSON.stringify(current) !== JSON.stringify(settings)) throw accessError("ccdx_connections_conflict", 409);return next;
97
- }, options));managed = true;
101
+ }, options));managed = true;catalogRefresh.invalidate();
98
102
  for (const [id, item] of instances) {
99
103
  const current = settings.apis.find(api => api.id === id);
100
104
  if (!current?.enabled || JSON.stringify(current) + deploymentRevision(current, env) !== item.signature) { instances.delete(id);retire(item.source); }else item.config = current;
@@ -112,27 +116,40 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
112
116
  ...config.apis.map(api => { const { secret_ref, ...publicApi } = api;return { ...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
113
117
  ...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) }; }),
114
118
  ], clients: CLIENT_IDS.map(id => ({ id, name: CLIENT_NAMES[id], ...config.clients[id], setup: setup[id] || null,
115
- observed_at: lastClients[id] || null, ...(compact ? {} : { model_plan: { default_model: plan(id).defaultModel,
119
+ observed_at: lastClients[id] || null, ...(compact ? {} : { model_plan: { default_model: plan(id).defaultModel, default_unavailable: plan(id).defaultUnavailable,
116
120
  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 })),
121
+ unavailable: (config.clients[id].deployments || []).filter(item => !plan(id).models.some(model => model.source_id === item.source && model.id === item.model))
122
+ .map(item => ({ source: item.source, id: item.model, route_id: deploymentModelId(item.source, item.model) })),
117
123
  available: config.clients[id].allowed.filter(enabled).flatMap(source => sourceModels(getSource(source), id).map(model => ({ source, id: model.id,
118
124
  route_id: deploymentModelId(source, model.id), capability: model.capability || resolveModelCapabilities(model, { builtin: true }) }))), sync: sharedSync, support: capabilitySupport } }) })), managed, m365_state: state.m365.state });
119
125
  }
120
- async function syncClients() {
126
+ async function syncClients(ids = CLIENT_IDS) {
127
+ for (const id of ids) syncTargets.add(id);
121
128
  syncAgain = true;if (syncFlight) return syncFlight;
122
- syncFlight = (async () => { do { syncAgain = false;await performClientSync(); } while (syncAgain && !closed); })();
129
+ syncFlight = (async () => { do { syncAgain = false;const targets = new Set(syncTargets);syncTargets.clear();await performClientSync(targets); } while (syncAgain && !closed); })();
123
130
  try { return await syncFlight; } finally { syncFlight = null; }
124
131
  }
125
- async function performClientSync() {
132
+ async function performClientSync(targets) {
126
133
  if (!managed || closed) return;
127
- const codex = binding("codex");
128
- 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_"))
129
- ? { baseUrl: `http://127.0.0.1:${corePort}/v1`, apiKey: identities().codex, model: plan("codex").defaultModel || codex.model } : { restore: true }) }).state; }
130
- catch { setup.codex = "configuration_unavailable"; }
131
- if (!settings.claude_private_keys) return;
134
+ const codex = binding("codex"), compiledCodex = plan("codex");
135
+ const explicit = Array.isArray(codex.deployments), native = explicit ? codex.deployments.length > 0 && codex.deployments.every(item => item.source === "github") : codex.source === "github";
136
+ if (targets.has("codex")) try {
137
+ if (codex.enabled && codex.auto_sync === false) setup.codex = "manual_sync";
138
+ else if (codex.enabled && compiledCodex.defaultUnavailable && !native) setup.codex = "default_unavailable";
139
+ else {
140
+ setup.codex = configureCodex({ ...options, ...(codex.enabled && (native || explicit && codex.deployments.length || codex.source?.startsWith("api_"))
141
+ ? { baseUrl: `http://127.0.0.1:${corePort}/v1`, native, ...(native ? { nativeModels: compiledCodex.models } : {}), ...(!native ? { apiKey: identities().codex } : {}),
142
+ ...(explicit || !native ? { model: compiledCodex.defaultModel || (!compiledCodex.defaultUnavailable ? codex.model : undefined) } : {}) } : { restore: true }) }).state;
143
+ if (codex.enabled && compiledCodex.defaultUnavailable && setup.codex === "configured") setup.codex = "default_unavailable";
144
+ }
145
+ } catch { setup.codex = "configuration_unavailable"; }
146
+ if (!settings.claude_private_keys || !["claude_app", "claude_code"].some(id => targets.has(id))) return;
132
147
  let desktopManaged;
133
148
  for (const id of ["claude_app", "claude_code"]) {
149
+ if (!targets.has(id)) continue;
134
150
  const selected = binding(id), compiled = plan(id), source = selected.source && permitted(id, selected.source) ? getSource(selected.source) : null;
135
151
  try {
152
+ if (selected.enabled && compiled.defaultUnavailable) { setup[id] = "default_unavailable";continue; }
136
153
  if (!selected.enabled || !compiled.models.length) { const result = restoreClaude({ ...options, client: id });setup[id] = result.preserved ? "preserved" : "not_configured";continue; }
137
154
  if (selected.auto_sync === false) { setup[id] = "manual_sync";continue; }
138
155
  if (id === "claude_app") desktopManaged ??= await inspectDesktop(options);
@@ -143,6 +160,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
143
160
  setup[id] = result[id === "claude_app" ? "app" : "code"] || "not_configured";
144
161
  } catch { setup[id] = "configuration_unavailable"; }
145
162
  }
163
+ if (["claude_app", "claude_code"].some(id => setup[id] === "default_unavailable")) {
164
+ sharedSync = { ...sharedSync, state: "partially_preserved", limitations: [{ code: "default_model_unavailable" }] };return;
165
+ }
146
166
  const shared = claudeSharedCapabilityPlan({ app: setup.claude_app === "configured" ? plan("claude_app").models : [],
147
167
  code: setup.claude_code === "configured" ? plan("claude_code").models : [], support: capabilitySupport });
148
168
  if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
@@ -160,53 +180,23 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
160
180
  if (!body || typeof body !== "object" || Array.isArray(body)) return;
161
181
  if (managed && (binding(client).history_isolation || source?.id.startsWith("api_"))) guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client]);
162
182
  }
163
- async function applyCatalog(id, models, revision, checkedAt) {
183
+ async function applyCatalog(id, models, revision, checkedAt, active) {
184
+ if (!active()) throw accessError("ccdx_connections_conflict", 409);
164
185
  const next = editable(), current = next.apis.find(api => api.id === id);
165
186
  if (!current?.enabled || deploymentRevision(current, env) !== revision) throw accessError("ccdx_connections_conflict", 409);
166
187
  const byId = new Map(models.map(model => [model.id, model]));
167
188
  for (const model of current.models) if (byId.get(model.id)?.metadata) model.metadata = byId.get(model.id).metadata;
168
189
  current.checked_at = checkedAt;
169
- if (JSON.stringify(current) !== JSON.stringify(settings.apis.find(api => api.id === id))) { save(next);await syncClients(); }
170
- discoveries.set(id, { state: "ready", checked_at: checkedAt });
171
- }
172
- async function refreshApi(id, force = false) {
173
- const config = settings.apis.find(api => api.id === id && api.enabled);
174
- if (!config) throw accessError("ccdx_client_source_disabled", 503);
175
- const revision = deploymentRevision(config, env), cached = catalogReads.get(id), age = cached ? now() - cached.at : Infinity;
176
- if (cached?.revision === revision && age >= 0 && age < (force || cached.error ? 60000 : 30 * 60000)) {
177
- if (cached.error) throw cached.error;await applyCatalog(id, cached.models, revision, new Date(cached.at).toISOString());return cached.models;
190
+ if (JSON.stringify(current) !== JSON.stringify(settings.apis.find(api => api.id === id))) {
191
+ save(next);await syncClients(CLIENT_IDS.filter(client => binding(client).source === id || binding(client).deployments?.some(model => model.source === id)));
178
192
  }
179
- const savedAge = now() - Date.parse(config.checked_at);
180
- if (!force && !cached && savedAge >= 0 && savedAge < 30 * 60000 && config.models.every(model => model.metadata?.state && model.metadata.deployment === revision)) return config.models;
181
- const source = getSource(id), finish = track(source);
182
- try {
183
- const models = await source.discover({ signal: AbortSignal.any([stopping.signal, AbortSignal.timeout(20000)]) });
184
- if (closed) throw accessError("ccdx_connections_closed", 503);
185
- await applyCatalog(id, models, revision, new Date(now()).toISOString());
186
- catalogReads.set(id, { revision, at: now(), models });
187
- return models;
188
- } catch (error) {
189
- const code = /^ccdx_[a-z0-9_]+$/.test(error.code || "") ? error.code : "ccdx_api_catalog_unavailable";
190
- const failure = accessError(code, [401, 403].includes(error.statusCode) ? error.statusCode : 502);
191
- catalogReads.set(id, { revision, at: now(), error: failure });
192
- discoveries.set(id, { state: "stale", code, checked_at: new Date(now()).toISOString() });throw failure;
193
- } finally { finish(); }
194
193
  }
195
194
  function enqueue(work) { const job = serial.then(work);serial = job.catch(() => {});return job; }
196
- function refreshApis() {
197
- if (closed || !managed) return Promise.resolve();
198
- refreshFlight ||= (async () => {
199
- for (const api of settings.apis) {
200
- if (closed) break;if (!api.enabled) continue;
201
- await enqueue(() => closed ? undefined : refreshApi(api.id)).catch(() => {});
202
- }
203
- })().finally(() => { refreshFlight = null; });
204
- return refreshFlight;
205
- }
195
+ const refreshApis = () => !closed && managed ? catalogRefresh.refreshAll(settings.apis.filter(api => api.enabled).map(api => api.id)) : Promise.resolve();
206
196
  async function change(input) {
207
197
  if (closed) throw accessError("ccdx_connections_closed", 503);
208
198
  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");
209
- const next = editable();let freshRef, previousRef, savedApi;
199
+ const next = editable();let freshRef, previousRef;
210
200
  if (input.operation === "save_api") {
211
201
  const existing = next.apis.find(api => api.id === input.id);
212
202
  if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
@@ -227,7 +217,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
227
217
  }
228
218
  if (existing) { previousRef = existing.secret_ref;next.apis[next.apis.indexOf(existing)] = config; } else next.apis.push(config);
229
219
  checkedAccessSettings(next);
230
- try { if (freshRef) await secrets.set(freshRef, input.key);save(next);savedApi = id; } catch (error) { if (freshRef) await secrets.remove(freshRef).catch(() => {});throw error; }
220
+ try { if (freshRef) await secrets.set(freshRef, input.key);save(next); } catch (error) { if (freshRef) await secrets.remove(freshRef).catch(() => {});throw error; }
231
221
  } else if (["client", "preview_client"].includes(input.operation)) {
232
222
  if (!CLIENT_IDS.includes(input.id) || typeof input.enabled !== "boolean" || !Array.isArray(input.allowed)
233
223
  || input.source !== null && input.source !== undefined && !input.allowed.includes(input.source)) throw accessError("ccdx_connections_action_invalid");
@@ -315,13 +305,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
315
305
  const source = await legacy.pauseM365();if (source) retire(source);
316
306
  }
317
307
  }
318
- } else if (input.operation === "discover") {
319
- const models = await refreshApi(input.id, true);return { ...snapshot(), discovered: models };
320
308
  } else throw accessError("ccdx_connections_action_invalid");
321
309
  await syncClients();
322
310
  if (input.operation === "client" && input.id === "codex") await clientAccessChanged?.(binding("codex").enabled);
323
311
  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); }
324
- if (savedApi && enabled(savedApi)) await refreshApi(savedApi).catch(() => {});
325
312
  return snapshot();
326
313
  }
327
314
  return {
@@ -329,7 +316,19 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
329
316
  source: getSource,
330
317
  connections: snapshot,
331
318
  syncClients,
332
- manageConnections(input) { if (!input) return Promise.resolve(snapshot());return enqueue(() => change(input)); },
319
+ async manageConnections(input) {
320
+ if (!input) return snapshot();
321
+ if (validObject(input, ["operation", "id"]) && input.operation === "discover") {
322
+ const models = await catalogRefresh.refresh(input.id, true);return { ...snapshot(), discovered: models };
323
+ }
324
+ if (validObject(input, ["operation", "id"]) && input.operation === "cancel_discovery") { catalogRefresh.cancel(input.id);return snapshot(); }
325
+ const result = await enqueue(() => change(input));
326
+ if (input.operation === "save_api") {
327
+ const id = input.id || result.providers.find(api => !api.builtin && api.name === input.config.name)?.id;
328
+ if (enabled(id)) void catalogRefresh.refresh(id).catch(() => {});
329
+ } else if (input.operation === "provider" && input.enabled && input.id?.startsWith("api_")) void catalogRefresh.refresh(input.id).catch(() => {});
330
+ return input.operation === "save_api" ? snapshot() : result;
331
+ },
333
332
  async start() { const old = legacy.start();if (managed) await syncClients();const result = await old;if (managed) await syncClients();void refreshApis();return result; },
334
333
  async refresh() { const result = await Promise.allSettled([!managed || settings.providers.m365 ? legacy.refresh() : Promise.resolve(), refreshApis()]);if (result[0].status === "rejected") throw result[0].reason; },
335
334
  selection() { return { ...legacy.selection(), codex: binding("codex").enabled ? binding("codex").source : null }; },
@@ -356,13 +355,20 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
356
355
  current(req) {
357
356
  if (!managed) return legacy.current();
358
357
  const c = binding("codex"), compiled = plan("codex");
359
- const source = requireSource("codex", Array.isArray(c.deployments) ? compiled.routes.get(compiled.defaultModel)?.source : c.source);
360
358
  if (Array.isArray(c.deployments) && req?.method === "GET") {
359
+ if (!c.enabled) throw accessError("ccdx_client_source_disabled", 503);
361
360
  if (codexRequiresKey()) requireCodexKey(req);
362
- return { ...source, registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
363
- client: { ...source.client, listModels: async () => ({ status: 200, body: JSON.stringify({ data: compiled.models.map(model => ({ ...model, id: model.public_id })) }) }) },
361
+ return { id: "connections", registry: { models: { data: compiled.models.map(model => ({ ...model, id: model.public_id })) } },
362
+ client: { listModels: async () => ({ status: 200, body: JSON.stringify({ data: compiled.models.map(model => ({ ...model, id: model.public_id })) }) }) },
364
363
  codexCatalog: codexClientCatalog(compiled) };
365
364
  }
365
+ if (Array.isArray(c.deployments) && compiled.defaultUnavailable) {
366
+ if (req && codexRequiresKey()) requireCodexKey(req);
367
+ // Admission uses the common handler; resolveCodex must resolve the
368
+ // explicitly requested model before any provider request is opened.
369
+ return null;
370
+ }
371
+ const source = requireSource("codex", Array.isArray(c.deployments) ? compiled.routes.get(compiled.defaultModel)?.source : c.source);
366
372
  if (source?.id.startsWith("api_") && req) requireCodexKey(req);
367
373
  return req?.method === "GET" && source?.configuredModels && source.id.startsWith("api_") ? { ...source, codexCatalog: codexSourceCatalog(source) } : source;
368
374
  },
@@ -386,6 +392,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
386
392
  track,
387
393
  validateConversation,
388
394
  historyContext(headers, target) {
395
+ if (target.id === "connections") return {};
389
396
  if (!target.id.startsWith("api_")) return legacy.historyContext(headers, target);
390
397
  // Opaque Responses state never transfers to another API/key/configuration.
391
398
  return { historyNamespace: target.profileId() };
@@ -466,6 +473,6 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
466
473
  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(); }
467
474
  return result;
468
475
  },
469
- async close() { closed = true;stopping.abort();await refreshFlight;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(); },
476
+ async close() { closed = true;await catalogRefresh.close();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(); },
470
477
  };
471
478
  }
@@ -3,6 +3,7 @@
3
3
  const words = (node, key, args) => globalThis.ccdxLanguage.set(node, key, args), format = key => globalThis.ccdxLanguage.format(key);
4
4
  let data = null, editing = null, editingClient = null, disabling = null, models = [], selectedModels = new Set(), busy = false, generation = 0;
5
5
  let claudeClient = "claude_app", bindingSelection = new Set(), bindingDefault = null, bindingDirty = false;
6
+ const drafts = new Map();let editorOrigin = null, discovery = null, desiredSource = null;
6
7
  const apiForm = el("connection-api-form"), clientForm = el("connection-client-form");
7
8
  const node = (tag, text, className) => { const item = document.createElement(tag);if (text !== undefined) item.textContent = text;if (className) item.className = className;return item; };
8
9
  const source = id => data.providers.find(item => item.id === id), client = id => data.clients.find(item => item.id === id);
@@ -12,13 +13,14 @@
12
13
  const message = (key, values) => words(el("connection-note"), key, values);
13
14
  function button(key, action) { const item = node("button");item.type = "button";words(item, key);item.addEventListener("click", action);return item; }
14
15
  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; }
15
- async function api(input) {
16
+ async function api(input, signal) {
16
17
  const response = await fetch("/_ccdx/ui/connections", { method: input ? "POST" : "GET", headers: { "X-CCDX-Dashboard": "1", ...(input ? { "Content-Type": "application/json" } : {}) },
17
- cache: "no-store", signal: AbortSignal.timeout(35000), ...(input ? { body: JSON.stringify(input) } : {}) });
18
+ cache: "no-store", signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(35000)]) : AbortSignal.timeout(35000), ...(input ? { body: JSON.stringify(input) } : {}) });
18
19
  const result = await response.json();if (!response.ok) throw new Error(result.error || "ccdx_connections_action_failed");
19
20
  if (result.source !== "connections" || !Array.isArray(result.providers) || !Array.isArray(result.clients)) throw new Error("ccdx_connections_unavailable");return result;
20
21
  }
21
22
  function panels(which = "list") {
23
+ if (which !== "api") stopDiscovery();
22
24
  root.hidden = which !== "list";
23
25
  el("source-account-panel").hidden = el("model-providers").hidden = which !== "list";
24
26
  el("connection-editor").hidden = which !== "api";el("connection-disable-editor").hidden = which !== "disable";
@@ -39,11 +41,11 @@
39
41
  const allowed = data.clients.filter(c => c.enabled && c.allowed.includes(provider.id)).map(c => c.name).join(" / ");
40
42
  const line = node("p", undefined, "hint");words(line, "api_allowed_summary", { clients: allowed || format("api_none") });info.append(line);
41
43
  if (provider.discovery?.state === "stale") { const warning = node("p", undefined, "hint");words(warning, "cap_catalog_stale");warning.append(" ", provider.discovery.code);info.append(warning); }
42
- 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)));
44
+ if (!provider.builtin) actions.append(button("api_manage", () => editApi(provider)));
43
45
  const toggle = node("input");toggle.type = "checkbox";toggle.checked = true;toggle.setAttribute("role", "switch");toggle.setAttribute("aria-label", format("api_disable_source") + " " + provider.name);
44
46
  toggle.addEventListener("change", () => { toggle.checked = true;disableSource(provider); });actions.append(toggle);
45
47
  } else actions.append(button("api_restore", () => void change({ operation: "provider", id: provider.id, enabled: true })));
46
- row.append(info, actions);(provider.enabled ? providerList : disabledSources).append(row);
48
+ row.append(info, actions);if (!provider.enabled) disabledSources.append(row);else if (provider.id === selectedProvider) providerList.append(row);
47
49
  }
48
50
  const current = editingClient && client(editingClient);
49
51
  if (current) {
@@ -67,11 +69,19 @@
67
69
  async function load() {
68
70
  if (busy) return;const current = ++generation;
69
71
  try { const result = await api();if (current !== generation) return;data = result;mountClient();list(); }
70
- catch (error) { message(error.message); }
72
+ catch (error) { if (!data) message(error.message); }
71
73
  }
72
74
  async function change(input, done) {
73
- if (busy) return;busy = true;generation++;const view = document.querySelector(`[data-view="${location.hash.slice(1)}"]`);view?.setAttribute("aria-busy", "true");
74
- try { data = await api(input);if (input.operation === "client") bindingDirty = false;mountClient();list();done?.(data);if (!done) {
75
+ if (busy) return;busy = true;generation++;
76
+ const trigger = input.operation === "client" ? clientForm.querySelector('button[type="submit"]') : input.operation === "preview_client" ? el("connection-sync-preview")
77
+ : input.operation === "save_api" ? apiForm.querySelector('button[type="submit"]') : document.activeElement;
78
+ const oldKey = trigger?.dataset.i18n, oldText = trigger?.textContent;
79
+ if (trigger?.tagName === "BUTTON") { trigger.setAttribute("aria-busy", "true");trigger.disabled = true;words(trigger, input.operation === "preview_client" ? "api_reading" : "api_saving"); }
80
+ try { if (input.operation === "save_api") await stopDiscovery();data = await api(input);if (input.operation === "client") { drafts.delete(input.id);if (editingClient === input.id) bindingDirty = false; }mountClient();list();done?.(data);if (!done) {
81
+ if (input.operation === "save_api") {
82
+ desiredSource = input.id || data.providers.find(p => !p.builtin && p.name === input.config.name)?.id;
83
+ stopDiscovery();
84
+ } else if (input.operation === "provider" && input.enabled) desiredSource = input.id;
75
85
  panels();let key = input.operation === "save_api" ? "api_config_saved" : input.operation === "provider" ? input.enabled ? "api_provider_enabled" : "api_provider_disabled"
76
86
  : !input.enabled ? "api_client_disabled" : !input.source ? "api_client_enabled" : "api_saved";
77
87
  const setup = data.clients.find(c => c.id === input.id)?.setup;
@@ -81,7 +91,9 @@
81
91
  if (input.operation === "client") words(el("connection-client-note"), key);else message(key);
82
92
  }window.dispatchEvent(new CustomEvent("ccdx:connections"));void dashboardRefresh.refresh("auth", { force: true });void dashboardRefresh.refresh("status", { force: true }); }
83
93
  catch (error) { if (input.operation === "client") words(el("connection-client-note"), error.message);else message(error.message); }
84
- finally { busy = false;view?.removeAttribute("aria-busy"); }
94
+ finally { busy = false;if (trigger?.tagName === "BUTTON") { trigger.removeAttribute("aria-busy");trigger.disabled = false;if (oldKey) words(trigger, oldKey);else trigger.textContent = oldText; }
95
+ if (["client", "preview_client"].includes(input.operation)) bindingRows();
96
+ }
85
97
  }
86
98
  const resolved = (model, protocol = model.protocols.includes("messages") ? "messages" : model.protocols[0]) => {
87
99
  const metadata = model.metadata?.deployment === source(editing)?.deployment_revision ? model.metadata : null;
@@ -180,7 +192,7 @@
180
192
  }
181
193
  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; }
182
194
  function editApi(provider) {
183
- editing = provider?.id || null;panels("api");apiForm.reset();words(el("connection-editor-title"), provider ? "api_manage" : "api_add");
195
+ stopDiscovery();editorOrigin = document.activeElement;editing = provider?.id || null;panels("api");apiForm.reset();words(el("connection-editor-title"), provider ? "api_manage" : "api_add");
184
196
  apiForm.elements.name.value = provider?.name || "";apiForm.elements.base.value = provider?.base_url || "";
185
197
  apiForm.elements.key.required = !provider;globalThis.ccdxLanguage.set(apiForm.elements.key, provider ? "api_key_keep" : "api_key_enter", {}, "placeholder");
186
198
  apiForm.elements.auth_header.value = provider?.auth_header || "x-api-key";
@@ -189,7 +201,7 @@
189
201
  setEndpoints(provider?.base_url || "", provider?.endpoints);
190
202
  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)));
191
203
  el("connection-model-detail").hidden = true;
192
- models = structuredClone(provider?.models || []);selectedModels = new Set(models.map(model => model.id));modelRows();el("connection-manual-model").open = false;el("connection-discover").disabled = !editing;el("connection-model-id").value = "";
204
+ models = structuredClone(provider?.models || []);selectedModels = new Set(models.map(model => model.id));modelRows();el("connection-manual-model").open = false;el("connection-discover").disabled = !editing;el("connection-model-id").value = "";apiForm.elements.name.focus();
193
205
  }
194
206
  apiForm.elements.base.addEventListener("change", () => setEndpoints(apiForm.elements.base.value));
195
207
  for (const input of apiForm.querySelectorAll('[name="protocol"]')) input.addEventListener("change", () => {
@@ -217,56 +229,83 @@
217
229
  const id = el("connection-model-id").value.trim();if (!id || models.some(model => model.id === id) || models.length >= 500) return;
218
230
  models.push({ id, protocols: [] });selectedModels.add(id);el("connection-model-id").value = "";modelRows();
219
231
  });
220
- el("connection-discover").addEventListener("click", () => void change({ operation: "discover", id: editing }, result => {
221
- const known = new Map(models.map(model => [model.id, model]));for (const model of result.discovered || []) { const previous = known.get(model.id);known.set(model.id, previous ? { ...previous, ...(model.metadata ? { metadata: model.metadata } : {}) } : model); }
222
- models = [...known.values()].slice(0, 500);modelRows();message("api_models_read");
223
- }));
232
+ function stopDiscovery() {
233
+ const previous = discovery;if (!previous) return;discovery = null;previous.controller.abort();
234
+ const cancelled = api({ operation: "cancel_discovery", id: previous.id }).catch(() => {});
235
+ el("connection-discover").disabled = !editing;el("connection-discover").removeAttribute("aria-busy");words(el("connection-discover"), "api_read_models");el("connection-discover-cancel").hidden = true;return cancelled;
236
+ }
237
+ el("connection-discover-cancel").addEventListener("click", () => { stopDiscovery();message("api_read_cancelled");el("connection-discover").focus(); });
238
+ el("connection-discover").addEventListener("click", async () => {
239
+ if (discovery || !editing) return;
240
+ const read = { id: editing, controller: new AbortController() };discovery = read;
241
+ const trigger = el("connection-discover");trigger.disabled = true;trigger.setAttribute("aria-busy", "true");words(trigger, "api_reading");el("connection-discover-cancel").hidden = false;
242
+ try {
243
+ const result = await api({ operation: "discover", id: read.id }, read.controller.signal);if (discovery !== read || editing !== read.id) return;
244
+ data = result;
245
+ const known = new Map(models.map(model => [model.id, model]));for (const model of result.discovered || []) { const previous = known.get(model.id);known.set(model.id, previous ? { ...previous, ...(model.metadata ? { metadata: model.metadata } : {}) } : model); }
246
+ models = [...known.values()].slice(0, 500);modelRows();message("api_models_read");
247
+ } catch (error) { if (discovery === read) message(error.message); }
248
+ finally { if (discovery === read) { discovery = null;trigger.disabled = false;trigger.removeAttribute("aria-busy");words(trigger, "api_read_models");el("connection-discover-cancel").hidden = true; } }
249
+ });
224
250
  const bindingKey = (source, model) => source + "\0" + model;
225
251
  const routeId = item => item.route_id || item.public_id;
252
+ function rememberDraft() {
253
+ if (editingClient && bindingDirty) drafts.set(editingClient, { selection: new Set(bindingSelection), defaultModel: bindingDefault, autoSync: el("connection-auto-sync").checked });
254
+ }
226
255
  function mountClient(force = false) {
227
256
  if (!data) return;
228
257
  const route = location.hash.slice(1), id = route === "claude" ? claudeClient : "codex";
229
- const mount = el(route === "claude" ? "claude-model-management" : "codex-model-management");
230
258
  if (!["codex", "claude"].includes(route)) return;
259
+ rememberDraft();
260
+ const mount = el(route === "claude" ? "claude-model-management" : "codex-model-management");
231
261
  mount.append(el("connection-clients"), el("connection-client-editor"));
232
262
  const c = client(id);el("connection-client-editor").hidden = !c.enabled;
233
263
  if (editingClient !== id || force || !bindingDirty) {
234
- editingClient = id;bindingDirty = false;
264
+ editingClient = id;const draft = drafts.get(id);bindingDirty = Boolean(draft);
235
265
  const selected = Array.isArray(c.deployments) ? c.deployments : (c.model_plan?.models || []).map(model => ({ source: model.source, model: model.id }));
236
- bindingSelection = new Set(selected.map(item => bindingKey(item.source, item.model)));
237
- bindingDefault = c.default_model || c.model_plan?.models.find(model => model.public_id === c.model_plan?.default_model)?.route_id || null;
238
- el("connection-auto-sync").checked = c.auto_sync !== false;bindingRows();
266
+ bindingSelection = draft ? new Set(draft.selection) : new Set(selected.map(item => bindingKey(item.source, item.model)));
267
+ bindingDefault = draft ? draft.defaultModel : c.default_model || c.model_plan?.models.find(model => model.public_id === c.model_plan?.default_model)?.route_id || null;
268
+ el("connection-auto-sync").checked = draft ? draft.autoSync : c.auto_sync !== false;
239
269
  el("connection-sync-result").hidden = true;el("connection-client-note").textContent = "";
240
270
  }
241
- words(el("connection-client-title"), "cap_visible_model");list();
271
+ bindingRows(document.activeElement?.name === "binding-model" ? { kind: "selection", key: document.activeElement.value } : document.activeElement?.dataset.binding ? { kind: "default", key: document.activeElement.dataset.binding } : null);words(el("connection-client-title"), "cap_visible_model");list();
242
272
  }
243
- function bindingRows() {
273
+ function bindingRows(focus) {
244
274
  el("connection-client-cancel").disabled = !bindingDirty;
245
275
  const body = el("connection-bindings"), c = client(editingClient);body.replaceChildren();
246
276
  const available = c.model_plan?.available || [], availableKeys = new Set(available.map(item => bindingKey(item.source, item.id)));
247
- const missing = [...bindingSelection].filter(key => !availableKeys.has(key)).map(key => { const [source, id] = key.split("\0");return { source, id, unavailable: true }; });
277
+ const missing = [...bindingSelection].filter(key => !availableKeys.has(key)).map(key => { const [source, id] = key.split("\0");return { source, id, route_id: c.model_plan?.unavailable?.find(item => item.source === source && item.id === id)?.route_id, unavailable: true }; });
248
278
  for (const item of [...available, ...missing]) {
249
279
  const key = bindingKey(item.source, item.id), row = node("tr"), name = node("td"), capability = item.capability?.values || {};
250
280
  const selection = check("binding-model", key, bindingSelection.has(key), item.id);
251
281
  selection.firstChild.addEventListener("change", event => {
252
282
  bindingDirty = true;if (event.target.checked) { bindingSelection.add(key);bindingDefault ||= routeId(item); }
253
- else { bindingSelection.delete(key);if (bindingDefault === routeId(item) || !available.some(entry => routeId(entry) === bindingDefault)) bindingDefault = available.find(entry => bindingSelection.has(bindingKey(entry.source, entry.id)))?.route_id || null; }
254
- bindingRows();
283
+ else { bindingSelection.delete(key);if (bindingDefault === routeId(item) || !bindingSelection.size) bindingDefault = null; }
284
+ rememberDraft();bindingRows({ kind: "selection", key });
255
285
  });name.append(selection);
256
- const action = button(bindingDefault === routeId(item) && bindingSelection.has(key) ? "cap_default" : "cap_set_default", () => { bindingDirty = true;bindingSelection.add(key);bindingDefault = routeId(item);bindingRows(); });
286
+ const action = button(bindingDefault === routeId(item) && bindingSelection.has(key) ? "cap_default" : "cap_set_default", () => { bindingDirty = true;bindingSelection.add(key);bindingDefault = routeId(item);rememberDraft();bindingRows({ kind: "default", key }); });
257
287
  action.setAttribute("aria-pressed", String(bindingDefault === routeId(item) && bindingSelection.has(key)));
258
- const cell = node("td");if (item.unavailable) words(cell, "cap_model_unavailable");else cell.append(action);
259
- row.append(name, node("td", source(item.source)?.name || item.source), node("td", count(capability.context_window)), node("td", reasoningText(capability)), cell);body.append(row);
288
+ action.dataset.binding = key;action.disabled = Boolean(item.unavailable);action.setAttribute("aria-label", item.id + " · " + format(bindingDefault === routeId(item) ? "cap_default" : "cap_set_default"));
289
+ if (item.unavailable) { const warning = node("span", undefined, "hint binding-unavailable");words(warning, "cap_model_unavailable");name.append(warning); }
290
+ const cell = node("td");cell.append(action);
291
+ const details = [node("td", source(item.source)?.name || item.source), node("td", count(capability.context_window)), node("td", reasoningText(capability))];
292
+ details.forEach((cell, i) => cell.dataset.label = format(["source", "cap_context", "cap_reasoning"][i]));
293
+ row.append(name, ...details, cell);body.append(row);
260
294
  }
295
+ const unavailableDefault = bindingSelection.size > 0 && !available.some(item => routeId(item) === bindingDefault && bindingSelection.has(bindingKey(item.source, item.id)));
296
+ const warning = el("connection-default-note");warning.hidden = !unavailableDefault;words(warning, "cap_default_unavailable");
297
+ clientForm.querySelector('button[type="submit"]').disabled = unavailableDefault || busy;
298
+ words(el("connection-draft-state"), bindingDirty ? "cap_unsaved" : "cap_saved");
299
+ if (focus) { const selector = focus.kind === "selection" ? 'input[name="binding-model"]' : 'button[data-binding]';[...body.querySelectorAll(selector)].find(input => (input.value || input.dataset.binding) === focus.key)?.focus(); }
261
300
  if (!body.children.length) { const row = node("tr"), cell = node("td");cell.colSpan = 5;words(cell, "cap_no_models");const link = node("a");link.href = "#models";words(link, "model_services");cell.append(" ", link);row.append(cell);body.append(row); }
262
301
  }
263
302
  function editClient(c) { location.hash = c.id === "codex" ? "codex" : "claude";if (c.id !== "codex") claudeClient = c.id;mountClient(true); }
264
303
  for (const segment of document.querySelectorAll("[data-claude-client]")) segment.addEventListener("click", () => {
265
- claudeClient = segment.dataset.claudeClient;bindingDirty = false;
304
+ rememberDraft();claudeClient = segment.dataset.claudeClient;
266
305
  for (const button of document.querySelectorAll("[data-claude-client]")) button.setAttribute("aria-pressed", String(button === segment));mountClient(true);
267
306
  });
268
- el("connection-auto-sync").addEventListener("change", () => { bindingDirty = true;el("connection-client-cancel").disabled = false; });
269
- el("connection-client-cancel").addEventListener("click", () => mountClient(true));
307
+ el("connection-auto-sync").addEventListener("change", () => { bindingDirty = true;rememberDraft();el("connection-client-cancel").disabled = false;words(el("connection-draft-state"), "cap_unsaved"); });
308
+ el("connection-client-cancel").addEventListener("click", () => { drafts.delete(editingClient);bindingDirty = false;mountClient(true); });
270
309
  function bindingInput(operation) {
271
310
  const c = client(editingClient);return { operation, id: c.id, enabled: true, allowed: c.allowed,
272
311
  deployments: [...bindingSelection].map(key => { const [source, model] = key.split("\0");return { source, model }; }),
@@ -283,9 +322,11 @@
283
322
  el("connection-disable-form").addEventListener("submit", e => { e.preventDefault();void change({ operation: "provider", id: disabling, enabled: false,
284
323
  replacements: Object.fromEntries([...el("connection-replacements").querySelectorAll("select")].map(select => [select.name, select.value || null])) }); });
285
324
  el("connection-add").addEventListener("click", () => { if (data) editApi(); });
286
- for (const id of ["connection-cancel", "connection-disable-cancel"]) el(id).addEventListener("click", () => panels());
325
+ for (const id of ["connection-cancel", "connection-disable-cancel"]) el(id).addEventListener("click", () => { panels();(editorOrigin?.isConnected ? editorOrigin : el("connection-source-list").querySelector("button") || el("connection-add")).focus(); });
287
326
  window.addEventListener("hashchange", () => { apiForm.elements.key.value = "";mountClient();if (["#models", "#claude", "#codex"].includes(location.hash)) void load(); });
288
327
  window.addEventListener("ccdx:choose-source", event => { if (typeof event.detail?.id === "string" && providerEntries.some(p => p.id === event.detail.id)) chooseProvider(event.detail.id); });
328
+ window.addEventListener("ccdx:source-view", () => { if (data) list(); });
329
+ window.addEventListener("ccdx:providers", () => { if (desiredSource && providerEntries.some(p => p.id === desiredSource)) { const id = desiredSource;desiredSource = null;chooseProvider(id); }if (data) list(); });
289
330
  new MutationObserver(() => { if (data) list(); }).observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] });
290
331
  globalThis.ccdxConnections = { load, editClient: id => { if (data && client(id)) { editClient(client(id)); } } };
291
332
  for (const button of document.querySelectorAll("[data-client-access]")) button.addEventListener("click", () => globalThis.ccdxConnections.editClient(button.dataset.clientAccess));