codex-copilot-dx 1.2.20 → 1.2.22

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.
Files changed (45) hide show
  1. package/README.md +7 -7
  2. package/bin/cli.mjs +85 -15
  3. package/docs/ARCHITECTURE.md +95 -3
  4. package/docs/REFERENCE.md +148 -13
  5. package/package.json +2 -1
  6. package/src/access-settings.mjs +1 -0
  7. package/src/account-tools.mjs +1 -1
  8. package/src/adapter.mjs +17 -2
  9. package/src/api-catalog-refresh.mjs +1 -0
  10. package/src/api-secrets.mjs +28 -9
  11. package/src/auth.mjs +2 -0
  12. package/src/bounded-result-cache.mjs +12 -0
  13. package/src/client-gateway-keys.mjs +7 -3
  14. package/src/client-integration.mjs +3 -0
  15. package/src/client-model-plan.mjs +11 -4
  16. package/src/clients/codex-models.mjs +2 -2
  17. package/src/codex-api-config.mjs +94 -26
  18. package/src/codex-client-doctor.mjs +19 -5
  19. package/src/codex-config-doctor.mjs +6 -4
  20. package/src/config.mjs +8 -5
  21. package/src/connection-runtime.mjs +28 -11
  22. package/src/dashboard/console.js +6 -1
  23. package/src/dashboard/flow.js +17 -7
  24. package/src/dashboard/index.html +6 -0
  25. package/src/dashboard/language.js +24 -0
  26. package/src/dashboard/ui.css +16 -2
  27. package/src/dashboard/ui.js +4 -4
  28. package/src/dashboard/view-boundary.js +41 -0
  29. package/src/dashboard-tools.mjs +1 -0
  30. package/src/dashboard.mjs +26 -5
  31. package/src/image-mcp.mjs +3 -0
  32. package/src/image-references.mjs +9 -0
  33. package/src/local-tools.mjs +1 -1
  34. package/src/m365-settings.mjs +5 -0
  35. package/src/nightly-update.mjs +107 -0
  36. package/src/optional-routes.mjs +19 -5
  37. package/src/provider-runtime.mjs +3 -2
  38. package/src/providers/api.mjs +6 -4
  39. package/src/release-install.mjs +24 -12
  40. package/src/response-history.mjs +50 -0
  41. package/src/service-control.mjs +9 -3
  42. package/src/service-supervisor.mjs +168 -0
  43. package/src/service-worker.mjs +87 -0
  44. package/src/terminal-console.mjs +1 -0
  45. package/src/user-settings.mjs +15 -0
@@ -116,6 +116,6 @@ export function createAccountTools({ home = os.homedir(), env = process.env, fet
116
116
  online = null;checkedAt = null;checkedFingerprint = "";operation = null;await onChanged();
117
117
  return snapshot();
118
118
  }
119
- return { snapshot, check, start, cancel, logout, wait: async () => { await operation?.task;return snapshot(); },
119
+ return { snapshot, check, start, cancel, logout, busy: () => Boolean(checkFlight || operation && ["starting", "authorizing", "verifying"].includes(operation.state)), wait: async () => { await operation?.task;return snapshot(); },
120
120
  async reload() { await onChanged();return snapshot(); }, dispose() { operation?.controller.abort(); } };
121
121
  }
package/src/adapter.mjs CHANGED
@@ -12,6 +12,7 @@ import { createRequestId, runWithRequestContext, currentRequestContext } from ".
12
12
  import { requestApplication } from "./request-application.mjs";
13
13
  import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
14
14
  import { status } from "./status.mjs";
15
+ import { exportResponseHistory, importResponseHistory } from "./response-history.mjs";
15
16
  import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
16
17
  import { ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH } from "./running-adapter.mjs";
17
18
  import { createManagementHandler, isManagementRoute } from "./management-routes.mjs";
@@ -264,6 +265,9 @@ export function createAdapterHandler(options = {}) {
264
265
  return providerHandlers.get(provider);
265
266
  }
266
267
  const dispatch = async (req, res, pathname) => {
268
+ if (options.isDraining?.() && ![ADAPTER_STATUS_PATH, ADAPTER_HEALTH_PATH].includes(pathname)) {
269
+ res.setHeader("Retry-After", "1");sendJsonError(res, httpError("CCDX is switching versions; retry shortly", 503));return;
270
+ }
267
271
  if (pathname.startsWith("/anthropic/")) {
268
272
  if (!isLoopbackAddress(req.socket?.remoteAddress) || !req.headers?.host || !isLoopbackHostHeader(req.headers.host)
269
273
  || Object.hasOwn(req.headers, "origin")) { sendJsonError(res, httpError("Claude requires native local clients", 403));return; }
@@ -482,13 +486,20 @@ export function createAdapterHandler(options = {}) {
482
486
  }
483
487
  };
484
488
  handler.snapshot = statusSnapshot;
489
+ handler.busy = () => optionalRoutes.busy() || options.providerRuntime?.busy?.() === true;
490
+ handler.exportState = () => ({ version: 1, history: exportResponseHistory(), optional: optionalRoutes.exportState() });
491
+ handler.importState = async state => {
492
+ if (state?.version !== 1) throw new Error("Unsupported service-state version");
493
+ importResponseHistory(state.history);await optionalRoutes.importState(state.optional);
494
+ };
485
495
  handler.cleanup = () => optionalRoutes.dispose();
486
496
  return handler;
487
497
  }
488
498
 
489
499
  // Public server entry point.
490
500
 
491
- export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
501
+ export async function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
502
+ const handoffState = options.handoffState;options = { ...options };delete options.handoffState;
492
503
  const ownsTerminalActivity = !Object.hasOwn(options, "terminalActivity");
493
504
  const terminalActivity = ownsTerminalActivity
494
505
  ? createTerminalActivityIndicator({ theme: options.terminalAnimationTheme })
@@ -496,11 +507,15 @@ export function startAdapter(port = 2026, host = "127.0.0.1", options = {}) {
496
507
  const handler = createAdapterHandler({ ...options, terminalActivity, imageMcpHostname: host });
497
508
  const server = http.createServer(handler);
498
509
  server.ccdxSnapshot = handler.snapshot;
510
+ server.ccdxBusy = handler.busy;
511
+ server.ccdxExportState = handler.exportState;
512
+ server.ccdxImportState = handler.importState;
513
+ if (handoffState) await handler.importState(handoffState);
499
514
  const cleanupTerminalActivity = () => {
500
515
  if (ownsTerminalActivity) terminalActivity?.cleanup?.();
501
516
  handler.cleanup?.();
502
517
  };
503
- server.once("close", cleanupTerminalActivity);
518
+ server.on("close", cleanupTerminalActivity);
504
519
 
505
520
  server.on("upgrade", (req, socket) => {
506
521
  // The responses_websockets upgrade expects a server-push protocol that this
@@ -57,6 +57,7 @@ export function createApiCatalogRefresh({ config, source, track, revision, commi
57
57
  return flight.promise;
58
58
  }
59
59
  return {
60
+ busy: () => pending.size > 0,
60
61
  refresh, cancel, invalidate,
61
62
  refreshAll(ids) {
62
63
  if (closed) return Promise.resolve();
@@ -25,7 +25,8 @@ export function checkedApiKey(key) {
25
25
  if (typeof key !== "string" || !/^[\x21-\x7e]{8,4096}$/.test(key)) throw accessError("ccdx_api_key_invalid");return key;
26
26
  }
27
27
  export function createApiSecretStore({ platform = process.platform, env = process.env, run = secretProcess, ...options } = {}) {
28
- const cache = new Map(), folder = path.join(path.dirname(accessSettingsPath({ ...options, env })), "api-secrets");
28
+ const cache = new Map(), reads = new Map(), folder = path.join(path.dirname(accessSettingsPath({ ...options, env })), "api-secrets");
29
+ const forget = id => { cache.delete(id);reads.delete(id); };
29
30
  const ref = id => { if (!/^[a-f0-9]{32}$/.test(id)) throw accessError("ccdx_api_key_invalid");return id; };
30
31
  const powershell = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
31
32
  const ps = async (script, input) => run(powershell, ["-NoProfile", "-NonInteractive", "-Command",
@@ -33,6 +34,9 @@ export function createApiSecretStore({ platform = process.platform, env = proces
33
34
  return {
34
35
  async get(id) {
35
36
  ref(id);if (cache.has(id)) return cache.get(id);
37
+ if (reads.has(id)) return reads.get(id).promise;
38
+ const flight = {};
39
+ flight.promise = Promise.resolve().then(async () => {
36
40
  let key;
37
41
  if (platform === "darwin") key = await run("/usr/bin/security", ["find-generic-password", "-s", SERVICE, "-a", id, "-w"], "", env);
38
42
  else if (platform === "win32") {
@@ -40,10 +44,13 @@ export function createApiSecretStore({ platform = process.platform, env = proces
40
44
  if (!/^[A-Za-z0-9+/]{64,65536}={0,2}$/.test(encrypted) || encrypted.length % 4) throw accessError("ccdx_api_secret_unavailable", 503);
41
45
  key = await ps("$null=[Reflection.Assembly]::LoadWithPartialName('System.Security');$b=[Convert]::FromBase64String([Console]::In.ReadLine());$p=[Security.Cryptography.ProtectedData]::Unprotect($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Write([Text.Encoding]::UTF8.GetString($p))", encrypted);
42
46
  } else key = await run("/usr/bin/secret-tool", ["lookup", "service", SERVICE, "reference", id], "", env);
43
- checkedApiKey(key);cache.set(id, key);return key;
47
+ checkedApiKey(key);if (reads.get(id) === flight) cache.set(id, key);return key;
48
+ }).finally(() => { if (reads.get(id) === flight) reads.delete(id); });
49
+ reads.set(id, flight);return flight.promise;
44
50
  },
45
51
  async set(id, key) {
46
- ref(id);checkedApiKey(key);
52
+ ref(id);checkedApiKey(key);forget(id);
53
+ try {
47
54
  if (platform === "darwin") {
48
55
  const quote = value => '"' + value.replace(/[\\"]/g, "\\$&") + '"';
49
56
  await run("/usr/bin/security", ["-i"], `add-generic-password -a ${quote(id)} -s ${quote(SERVICE)} -w ${quote(key)}\n`, env);
@@ -56,14 +63,26 @@ export function createApiSecretStore({ platform = process.platform, env = proces
56
63
  if (!/^[A-Za-z0-9+/]{64,65536}={0,2}$/.test(encrypted) || encrypted.length % 4) throw accessError("ccdx_api_secret_unavailable", 503);
57
64
  fs.mkdirSync(folder, { recursive: true, mode: 0o700 });atomicWriteFileSync(path.join(folder, id), encrypted, { mode: 0o600 });
58
65
  } else await run("/usr/bin/secret-tool", ["store", "--label=CCDX API", "service", SERVICE, "reference", id], key, env);
59
- cache.set(id, key);
66
+ } catch (error) { forget(id);throw error; }
67
+ forget(id);cache.set(id, key);
60
68
  },
61
69
  async remove(id) {
62
- ref(id);cache.delete(id);
63
- if (platform === "darwin") await run("/usr/bin/security", ["delete-generic-password", "-s", SERVICE, "-a", id], "", env);
64
- else if (platform === "win32") fs.rmSync(path.join(folder, id), { force: true });
65
- else await run("/usr/bin/secret-tool", ["clear", "service", SERVICE, "reference", id], "", env);
70
+ ref(id);forget(id);
71
+ try {
72
+ if (platform === "darwin") await run("/usr/bin/security", ["delete-generic-password", "-s", SERVICE, "-a", id], "", env);
73
+ else if (platform === "win32") fs.rmSync(path.join(folder, id), { force: true });
74
+ else await run("/usr/bin/secret-tool", ["clear", "service", SERVICE, "reference", id], "", env);
75
+ } finally { forget(id); }
76
+ },
77
+ close() { cache.clear();reads.clear(); },
78
+ exportState(allowed) { return [...cache].filter(([id]) => allowed.includes(id)); },
79
+ importState(values, allowed) {
80
+ if (!Array.isArray(values) || values.length > 16 || new Set(values.map(pair => pair?.[0])).size !== values.length) throw accessError("ccdx_api_secret_unavailable", 503);
81
+ for (const pair of values) {
82
+ if (!Array.isArray(pair) || pair.length !== 2 || !allowed.includes(pair[0])) throw accessError("ccdx_api_secret_unavailable", 503);
83
+ ref(pair[0]);checkedApiKey(pair[1]);
84
+ }
85
+ for (const [id, key] of values) { forget(id);cache.set(id, key); }
66
86
  },
67
- close() { cache.clear(); },
68
87
  };
69
88
  }
package/src/auth.mjs CHANGED
@@ -339,6 +339,7 @@ export async function ensureAuth({
339
339
  githubIdentityTimeoutMs = DEFAULT_GITHUB_IDENTITY_TIMEOUT_MS,
340
340
  sleepImpl = sleep,
341
341
  now = Date.now,
342
+ interactive = true,
342
343
  } = {}) {
343
344
  const GITHUB_TOKEN_PATH = githubTokenPath(home);
344
345
  if (fs.existsSync(GITHUB_TOKEN_PATH)) {
@@ -350,6 +351,7 @@ export async function ensureAuth({
350
351
  log(status("warn", "GitHub token file is empty"));
351
352
  }
352
353
 
354
+ if (!interactive) throw new Error("Saved GitHub sign-in is unavailable; unattended login was skipped");
353
355
  await withFileLock(githubTokenLockPath(home), async () => {
354
356
  const savedToken = readSavedGithubToken(home);
355
357
  if (savedToken) {
@@ -61,6 +61,18 @@ export function createByteLruCache({ maxBytes }) {
61
61
  misses = 0;
62
62
  evictions = 0;
63
63
  },
64
+ exportEntries() { return [...entries].map(([key, entry]) => [key, entry.value]); },
65
+ importEntries(values) {
66
+ if (!Array.isArray(values) || values.length > 10000) throw new Error("Invalid cache handoff");
67
+ const seen = new Set();let size = 0;
68
+ for (const pair of values) {
69
+ if (!Array.isArray(pair) || pair.length !== 2 || pair.some(value => typeof value !== "string") || seen.has(pair[0])) throw new Error("Invalid cache handoff");
70
+ seen.add(pair[0]);size += byteLength(pair[0]) + byteLength(pair[1]);
71
+ if (size > limit) throw new Error("Cache handoff exceeds this version's limit");
72
+ }
73
+ entries.clear();bytes = 0;
74
+ for (const [key, value] of values) { const size = byteLength(key) + byteLength(value);entries.set(key, { value, bytes: size });bytes += size; }
75
+ },
64
76
  stats() {
65
77
  return {
66
78
  entries: entries.size,
@@ -6,8 +6,13 @@ import { readBoundedFileSync } from "./bounded-file.mjs";
6
6
  import { withFileLockSync } from "./lock.mjs";
7
7
  import { atomicWriteFileSync } from "./atomic-file.mjs";
8
8
 
9
- export function readClientGatewayKeys(options = {}) {
9
+ export function readClientGatewayKeys({ create = true, ...options } = {}) {
10
10
  const file = path.join(path.dirname(accessSettingsPath(options)), "client-gateway-keys.json");
11
+ const checked = value => {
12
+ if (!value || Object.keys(value).length !== CLIENT_IDS.length || CLIENT_IDS.some(id => !/^[a-f0-9]{64}$/.test(value[id]))) throw accessError("ccdx_client_keys_invalid", 409);
13
+ return value;
14
+ };
15
+ if (!create) return checked(JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 2048 })));
11
16
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
12
17
  return withFileLockSync(`${file}.lock`, () => {
13
18
  let value;
@@ -17,8 +22,7 @@ export function readClientGatewayKeys(options = {}) {
17
22
  value = Object.fromEntries(CLIENT_IDS.map(id => [id, randomBytes(32).toString("hex")]));
18
23
  atomicWriteFileSync(file, JSON.stringify(value) + "\n", { mode: 0o600 });
19
24
  }
20
- if (!value || Object.keys(value).length !== CLIENT_IDS.length || CLIENT_IDS.some(id => !/^[a-f0-9]{64}$/.test(value[id]))) throw accessError("ccdx_client_keys_invalid", 409);
21
- return value;
25
+ return checked(value);
22
26
  });
23
27
  }
24
28
  export function gatewayClient(headers, keys) {
@@ -121,6 +121,9 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
121
121
  return { active, state: active ? "active" : native ? "paused" : "needs_setup" };
122
122
  },
123
123
  snapshot() { return { prediction: { ...prediction.snapshot(), active: native?.enabled?.() === true } }; },
124
+ busy: () => Boolean(operation),
125
+ bridgeHealthy: () => native?.healthy?.() === true,
126
+ pauseForUpdate() { return serialize("pause", async () => { await native?.close();native = null; }); },
124
127
  async close() { closed = true;try { await operation; } finally { await native?.close();native = null; } },
125
128
  };
126
129
  }
@@ -15,16 +15,23 @@ export function compileClientModels({ client, binding, source, enabled, names =
15
15
  if (!binding.enabled) return { models: [], routes: new Map(), defaultModel: null, revision: "disabled" };
16
16
  const explicit = Array.isArray(binding.deployments), selected = explicit ? binding.deployments : binding.source
17
17
  ? sourceModels(source(binding.source), client).map(model => ({ source: binding.source, model: model.id })) : [];
18
- const models = [], routes = new Map(), raw = new Map(), catalogs = new Map();
18
+ const models = [], routes = new Map(), raw = new Map(), catalogs = new Map(), available = [], counts = new Map();
19
19
  for (const item of selected) {
20
20
  if (!binding.allowed.includes(item.source) || !enabled(item.source)) continue;
21
21
  const provider = source(item.source);
22
22
  if (!catalogs.has(provider)) catalogs.set(provider, new Map(sourceModels(provider, client).map(model => [model.id, model])));
23
23
  const model = catalogs.get(provider).get(item.model);
24
24
  if (!model || model.policy?.state && model.policy.state !== "enabled" || model.model_picker_enabled === false) continue;
25
- const route = deploymentModelId(item.source, model.id), capability = model.capability || resolveModelCapabilities(model, { builtin: true });
26
- const entry = { ...model, capability, source_id: item.source, route_id: route,
27
- ...(explicit ? { client_id: route, display_name: `${model.id} · ${names[item.source] || item.source}` } : {}) };
25
+ available.push({ item, provider, model, route: deploymentModelId(item.source, model.id) });counts.set(model.id, (counts.get(model.id) || 0) + 1);
26
+ }
27
+ const routeIds = new Set(available.map(entry => entry.route));
28
+ for (const { item, provider, model, route } of available) {
29
+ const capability = model.capability || resolveModelCapabilities(model, { builtin: true });
30
+ const sourceName = names[item.source] || provider.name || ({ github: "GitHub Copilot", m365: "Microsoft 365" })[item.source] || item.source;
31
+ const ambiguous = counts.get(model.id) > 1;
32
+ const entry = { ...model, capability, source_id: item.source, source_name: sourceName, route_id: route,
33
+ ...(explicit ? { client_id: client === "codex" && !ambiguous && !routeIds.has(model.id) ? model.id : route,
34
+ ...(ambiguous ? { display_name: `${model.display_name || model.name || model.id} · ${sourceName}` } : {}) } : {}) };
28
35
  if (client === "claude_app" && explicit) entry.client_id = claudeDeploymentId(entry, route, { desktopEffortAliases });
29
36
  const publicId = explicit ? entry.client_id : client === "codex" ? model.id : claudeModelEntries([entry], { desktopAliases: client === "claude_app" && provider.id.startsWith("api_") })[0].name;
30
37
  entry.public_id = publicId;
@@ -5,14 +5,14 @@ export function codexModelEntry(model, { priority = 0, name = "", template = {}
5
5
  base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
6
6
  supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
7
7
  experimental_supported_tools: [], input_modalities: values.input_modalities || ["text"], ...template,
8
- slug: model.public_id || model.id, display_name: model.display_name || model.id, description: name, visibility: "list", supported_in_api: true, priority,
8
+ slug: model.public_id || model.id, display_name: model.display_name || template.display_name || model.name || model.id, description: model.description || template.description || name, visibility: "list", supported_in_api: true, priority,
9
9
  default_reasoning_level: efforts[0] || null, supported_reasoning_levels: efforts.map(effort => ({ effort, description: effort })),
10
10
  context_window: values.context_window || template.context_window || null, max_context_window: values.context_window || template.max_context_window || null };
11
11
  }
12
12
  export function codexClientCatalog(plan) {
13
13
  return Object.assign((value, nativeCatalog) => ({ ...value, models: plan.models.map((model, priority) => {
14
14
  const template = model.source_id === "github" ? nativeCatalog?.models?.find(entry => entry.slug === model.id) : undefined;
15
- return codexModelEntry(model, { priority, template, name: model.source_id });
15
+ return codexModelEntry(model, { priority, template, name: model.source_name || model.source_id });
16
16
  }) }), { needsNativeCatalog: plan.models.some(model => model.source_id === "github") });
17
17
  }
18
18
 
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { parse } from "smol-toml";
3
+ import { codexTomlStatements, parseCodexToml, validateManagedConfigEdit } from "./config-toml.mjs";
4
4
  import { codexPaths } from "./codex-paths.mjs";
5
5
  import { accessSettingsPath, accessError } from "./access-settings.mjs";
6
6
  import { readBoundedFileSync } from "./bounded-file.mjs";
@@ -19,49 +19,117 @@ function retainsCodexSignIn(config, directory, env) {
19
19
  throw accessError("ccdx_codex_config_invalid", 409);
20
20
  }
21
21
  }
22
- // Only the provider, selected model and private provider table are owned.
23
- export function configureCodexApi({ baseUrl, apiKey, model, restore = false, ...options } = {}) {
22
+ function validateOwner(owner) {
23
+ if (owner && (![1, 2].includes(owner.version) || !Object.hasOwn(owner, "beforeProvider") || !Object.hasOwn(owner, "beforeSection")
24
+ || owner.version === 1 && typeof owner.section !== "string"
25
+ || owner.version === 2 && (!["openai", "gateway"].includes(owner.mode) || owner.mode === "gateway" && typeof owner.section !== "string"
26
+ || owner.mode === "openai" && owner.section !== null && typeof owner.section !== "string"))) throw accessError("ccdx_codex_config_invalid", 409);
27
+ }
28
+ export function codexBaseUrlManaged(options = {}) {
29
+ if (options.filePath && path.resolve(options.filePath) !== codexPaths(options).config) return false;
30
+ const journal = path.join(path.dirname(accessSettingsPath(options)), "codex-gateway-owner.json");
31
+ try {
32
+ const owner = JSON.parse(readBoundedFileSync(journal, { encoding: "utf8", maxBytes: 16384 }));validateOwner(owner);
33
+ return owner?.version === 2 && Object.hasOwn(owner, "base");
34
+ } catch (error) { if (error.code === "ENOENT") return false;throw accessError("ccdx_codex_config_invalid", 409); }
35
+ }
36
+
37
+ // Retain exact declarations for restoration; the scanner handles quoted keys,
38
+ // comments and multiline values without serializing unrelated TOML.
39
+ function rootDeclaration(content, key) {
40
+ const item = codexTomlStatements(content).find(item => item.kind === "value" && !item.section.length && item.keys.length === 1 && item.keys[0] === key);
41
+ if (!item) return null;
42
+ const start = content.lastIndexOf("\n", item.start - 1) + 1, newline = content.indexOf("\n", item.valueEnd), end = newline < 0 ? content.length : newline + 1;
43
+ return { start, end, text: content.slice(start, end) };
44
+ }
45
+ function replaceRoot(content, key, text) {
46
+ const item = rootDeclaration(content, key);
47
+ return item ? content.slice(0, item.start) + (text || "") + (text && !text.endsWith("\n") && item.end < content.length ? "\n" : "") + content.slice(item.end) : (text || "") + content;
48
+ }
49
+
50
+ // Retire only the complete, recognized qualified-ID cache from the old native
51
+ // route. Its bytes remain available for rollback; unknown caches are untouched.
52
+ function retireQualifiedCache(models, options) {
53
+ if (!Array.isArray(models) || !models.length) return () => {};
54
+ const aliases = new Set(models.filter(model => model.public_id !== model.route_id && /^ccdx\/model-\d+$/.test(model.route_id)).map(model => model.route_id));
55
+ if (aliases.size !== models.length) return () => {};
56
+ const file = path.join(codexPaths(options).directory, "models_cache.json"), backup = file + ".ccdx-qualified.bak";
57
+ let bytes, cache;
58
+ try { bytes = readBoundedFileSync(file, { maxBytes: 8 * 1024 * 1024 });cache = JSON.parse(bytes.toString("utf8")); }
59
+ catch (error) { if (error.code === "ENOENT" || error instanceof SyntaxError) return () => {};throw accessError("ccdx_codex_catalog_cache_unavailable", 409); }
60
+ if (!Array.isArray(cache.models) || cache.models.length !== aliases.size || !cache.models.every(model => typeof model?.slug === "string" && aliases.has(model.slug))
61
+ || new Set(cache.models.map(model => model.slug)).size !== aliases.size) return () => {};
62
+ try {
63
+ if (fs.existsSync(backup) && !readBoundedFileSync(backup, { maxBytes: 8 * 1024 * 1024 }).equals(bytes)) throw Error("cache_backup_conflict");
64
+ if (!readBoundedFileSync(file, { maxBytes: 8 * 1024 * 1024 }).equals(bytes)) throw Error("cache_changed");
65
+ fs.renameSync(file, backup);fs.chmodSync(backup, 0o600);
66
+ } catch { throw accessError("ccdx_codex_catalog_cache_unavailable", 409); }
67
+ return () => { if (!fs.existsSync(file)) fs.renameSync(backup, file); };
68
+ }
69
+
70
+ // GitHub-only traffic retains the built-in OpenAI provider. Private API traffic
71
+ // keeps its own provider and local key. Both routes share one ownership journal.
72
+ export function configureCodexApi({ baseUrl, apiKey, model, native = false, nativeModels, restore = false, ...options } = {}) {
24
73
  if (!restore) {
25
74
  let url;try { url = new URL(baseUrl); } catch { throw accessError("ccdx_codex_config_invalid"); }
26
75
  if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/v1" || url.username || url.password || url.search || url.hash
27
- || !/^[a-f0-9]{64}$/.test(apiKey)) throw accessError("ccdx_codex_config_invalid");
76
+ || !native && !/^[a-f0-9]{64}$/.test(apiKey)) throw accessError("ccdx_codex_config_invalid");
28
77
  }
29
78
  const file = codexPaths(options).config, journal = path.join(path.dirname(accessSettingsPath(options)), "codex-gateway-owner.json");
30
79
  if (restore && !fs.existsSync(journal)) return { state: "unchanged" };
31
80
  fs.mkdirSync(path.dirname(journal), { recursive: true, mode: 0o700 });fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
32
- return withFileLockSync(`${journal}.lock`, () => {
81
+ return withFileLockSync(`${file}.ccdx.lock`, () => withFileLockSync(`${journal}.lock`, () => {
33
82
  let content = "", owner = null;
34
83
  try { content = readBoundedFileSync(file, { encoding: "utf8", maxBytes: 1024 * 1024 }); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_codex_config_invalid", 409); }
35
84
  try { owner = JSON.parse(readBoundedFileSync(journal, { encoding: "utf8", maxBytes: 16384 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_codex_config_invalid", 409); }
36
- let config;try { config = parse(content); } catch { throw accessError("ccdx_codex_config_invalid", 409); }
37
- if (owner && (owner.version !== 1 || typeof owner.section !== "string" || !Object.hasOwn(owner, "beforeProvider") || !Object.hasOwn(owner, "beforeSection"))) throw accessError("ccdx_codex_config_invalid", 409);
38
- const firstTable = content.search(/^\s*\[/m), head = firstTable < 0 ? content : content.slice(0, firstTable), tail = firstTable < 0 ? "" : content.slice(firstTable);
85
+ let config;try { config = parseCodexToml(content); } catch { throw accessError("ccdx_codex_config_invalid", 409); }
86
+ validateOwner(owner);
87
+ const table = codexTomlStatements(content).find(item => item.kind === "table"), firstTable = table ? content.lastIndexOf("\n", table.start - 1) + 1 : -1;
88
+ const head = firstTable < 0 ? content : content.slice(0, firstTable), tail = firstTable < 0 ? "" : content.slice(firstTable);
39
89
  const sectionPattern = /^\[model_providers\.ccdx_gateway\]\r?\n[^]*?(?=^\[|$(?![^]))/m;
40
90
  const currentSection = tail.match(sectionPattern)?.[0] || null;
41
- if (owner && (config.model_provider !== ID || currentSection !== owner.section)) return { state: "preserved" };
91
+ const nativeOwner = owner?.mode === "openai", openaiProvider = !config.model_provider || config.model_provider === "openai";
92
+ if (owner && (currentSection !== owner.section || (nativeOwner ? !openaiProvider : config.model_provider !== ID && !(native && openaiProvider)))) return { state: "preserved" };
93
+ if (owner && Object.hasOwn(owner, "base") && rootDeclaration(head, "openai_base_url")?.text !== owner.base) return { state: "preserved" };
42
94
  const modelEdited = owner?.model !== undefined && config.model !== owner.model;
43
95
  if (restore && modelEdited) return { state: "preserved" };
44
- if (!owner && (config.model_provider && config.model_provider !== "openai" || config.model_providers?.[ID])) return { state: "preserved" };
96
+ if (!owner && (!openaiProvider || config.model_providers?.[ID])) return { state: "preserved" };
97
+ const beforeProvider = owner ? owner.beforeProvider : rootDeclaration(head, "model_provider")?.text || null;
98
+ const beforeSection = owner ? owner.beforeSection : currentSection;
45
99
  let next, nextOwner = null;
46
100
  if (restore) {
47
101
  if (!owner) return { state: "unchanged" };
48
- let root = head.replace(/^model_provider\s*=.*(?:\r?\n|$)/m, owner.beforeProvider || "");
49
- if (owner.model !== undefined) root = root.replace(/^model\s*=.*(?:\r?\n|$)/m, owner.beforeModel || "");
50
- next = root + tail.replace(sectionPattern, owner.beforeSection || "");
102
+ let root = replaceRoot(head, "model_provider", beforeProvider);
103
+ if (owner.model !== undefined) root = replaceRoot(root, "model", owner.beforeModel);
104
+ if (Object.hasOwn(owner, "base")) root = replaceRoot(root, "openai_base_url", owner.beforeBase);
105
+ next = root + (currentSection ? tail.replace(sectionPattern, beforeSection || "") : tail);
51
106
  } else {
52
- // Account identity remains native; only model traffic uses the local key.
53
- const requiresAuth = retainsCodexSignIn(config, path.dirname(file), options.env || process.env);
54
- const section = `[model_providers.${ID}]\nname = "CCDX"\nbase_url = ${JSON.stringify(baseUrl)}\nmodel_catalog_url = ${JSON.stringify(baseUrl + "/models")}\nwire_api = "responses"\nrequires_openai_auth = ${requiresAuth}\nexperimental_bearer_token = ${JSON.stringify(apiKey)}\n\n`;
55
- let root = head;
56
- if (model && !modelEdited) root = root.match(/^model\s*=/m) ? root.replace(/^model\s*=.*(?:\r?\n|$)/m, `model = ${JSON.stringify(model)}\n`) : `model = ${JSON.stringify(model)}\n` + root;
57
- next = (root.match(/^model_provider\s*=/m) ? root.replace(/^model_provider\s*=.*(?:\r?\n|$)/m, `model_provider = "${ID}"\n`) : `model_provider = "${ID}"\n` + root)
58
- + (currentSection ? tail.replace(sectionPattern, section) : tail + (tail && !tail.endsWith("\n") ? "\n" : "") + "\n" + section);
59
- nextOwner = { version: 1, beforeProvider: owner ? owner.beforeProvider : head.match(/^model_provider\s*=.*(?:\r?\n|$)/m)?.[0] || null,
60
- beforeSection: owner ? owner.beforeSection : currentSection, section,
61
- ...(modelEdited ? { model: owner.model, beforeModel: owner.beforeModel }
62
- : model ? { model, beforeModel: owner && Object.hasOwn(owner, "beforeModel") ? owner.beforeModel : head.match(/^model\s*=.*(?:\r?\n|$)/m)?.[0] || null } : {}) };
107
+ let root = head, section;
108
+ if (model && !modelEdited) root = replaceRoot(root, "model", `model = ${JSON.stringify(model)}\n`);
109
+ if (native) {
110
+ root = replaceRoot(root, "model_provider", beforeProvider);
111
+ root = replaceRoot(root, "openai_base_url", `openai_base_url = ${JSON.stringify(baseUrl)}\n`);
112
+ // Existing sessions retain their provider ID. Keep its unchanged table
113
+ // inactive so they can resume; fresh native installs create no table.
114
+ section = currentSection;
115
+ next = root + tail;
116
+ } else {
117
+ const requiresAuth = retainsCodexSignIn(config, path.dirname(file), options.env || process.env);
118
+ section = `[model_providers.${ID}]\nname = "CCDX"\nbase_url = ${JSON.stringify(baseUrl)}\nmodel_catalog_url = ${JSON.stringify(baseUrl + "/models")}\nwire_api = "responses"\nrequires_openai_auth = ${requiresAuth}\nexperimental_bearer_token = ${JSON.stringify(apiKey)}\n\n`;
119
+ root = replaceRoot(root, "model_provider", `model_provider = "${ID}"\n`);
120
+ next = root + (currentSection ? tail.replace(sectionPattern, section) : tail + (tail && !tail.endsWith("\n") ? "\n" : "") + "\n" + section);
121
+ }
122
+ nextOwner = { version: 2, mode: native ? "openai" : "gateway", beforeProvider, beforeSection, section,
123
+ ...(native || owner && Object.hasOwn(owner, "base") ? { beforeBase: owner && Object.hasOwn(owner, "beforeBase") ? owner.beforeBase : rootDeclaration(head, "openai_base_url")?.text || null,
124
+ base: native ? `openai_base_url = ${JSON.stringify(baseUrl)}\n` : owner.base } : {}),
125
+ ...(modelEdited || !model && owner?.model !== undefined ? { model: owner.model, beforeModel: owner.beforeModel }
126
+ : model ? { model, beforeModel: owner && Object.hasOwn(owner, "beforeModel") ? owner.beforeModel : rootDeclaration(head, "model")?.text || null } : {}) };
63
127
  }
64
- parse(next);if (next !== content || JSON.stringify(nextOwner) !== JSON.stringify(owner)) atomicWriteFilePairSync(file, next, journal, nextOwner ? JSON.stringify(nextOwner) + "\n" : null, { mode: 0o600 });
128
+ try { validateManagedConfigEdit(config, next, [["model"], ["model_provider"], ["model_providers", ID], ["openai_base_url"]]); }
129
+ catch { throw accessError("ccdx_codex_config_invalid", 409); }
130
+ const undoCache = native && !restore ? retireQualifiedCache(nativeModels, options) : () => {};
131
+ try { if (next !== content || JSON.stringify(nextOwner) !== JSON.stringify(owner)) atomicWriteFilePairSync(file, next, journal, nextOwner ? JSON.stringify(nextOwner) + "\n" : null, { mode: 0o600 }); }
132
+ catch (error) { undoCache();throw error; }
65
133
  return { state: modelEdited ? "preserved" : "configured", changed: next !== content };
66
- });
134
+ }));
67
135
  }
@@ -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.