codex-copilot-dx 1.2.32 → 1.2.33

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.
@@ -0,0 +1,340 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { dashboardToolRequest } from "./cli-tools.mjs";
4
+ import { readAdapterStatus } from "./cli-status.mjs";
5
+ import { CLI_CLIENTS } from "./cli-command-spec.mjs";
6
+ import { projectTerminalState, retainedRequests, clientSetup, TERMINAL_CLIENT_NAMES, terminalUptime } from "./terminal-state.mjs";
7
+ import { formatResponsiveCliTable, cliOutputWidth, terminalCell } from "./cli-table.mjs";
8
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
9
+ import { settingsPreferencesSnapshot, writeSettingsPreferences, checkedPreferenceValues } from "./settings-preferences.mjs";
10
+ import { checkedApi } from "./access-settings.mjs";
11
+ import { hiddenQuestion } from "./cli-image.mjs";
12
+ import { readBoundedFileSync } from "./bounded-file.mjs";
13
+ import { deploymentModelId } from "./model-capabilities.mjs";
14
+
15
+ async function readSecretInput(input) {
16
+ const chunks = [];let bytes = 0;
17
+ for await (const chunk of input) { const data = Buffer.from(chunk);bytes += data.length;if (bytes > 8192) throw new Error("API key input is too large");chunks.push(data); }
18
+ return Buffer.concat(chunks).toString("utf8").trim();
19
+ }
20
+
21
+ const apiConfig = source => Object.fromEntries(["name", "base_url", "endpoints", "auth_header", "models", "key_env"].filter(key => source[key] !== undefined).map(key => [key, source[key]]));
22
+ const publicValue = value => JSON.parse(JSON.stringify(value, (key, item) => /^(?:api_key|access_token|refresh_token|authorization|password|secret_ref|key|secret)$/.test(key) ? undefined
23
+ : typeof item === "string" ? redactDiagnosticText(item) : item));
24
+ export function formatManagement(value, { format, output = process.stdout, columns } = {}) {
25
+ const safe = publicValue(value);
26
+ if (format === "json") return JSON.stringify(safe, null, 2);
27
+ const rows = Array.isArray(safe) ? safe : [safe];
28
+ if (!rows.length) return "No retained records.";
29
+ if (columns && (format === "table" || format === undefined && output.isTTY === true)) {
30
+ const data = rows.map(row => Object.fromEntries(columns.map(([key]) => [key, Array.isArray(row[key]) ? row[key].join(", ") : typeof row[key] === "object" && row[key] !== null ? JSON.stringify(row[key]) : row[key] ?? "—"])));
31
+ const table = formatResponsiveCliTable({ columns: columns.map(([key, label]) => ({ key, label })), rows: data, width: cliOutputWidth(output) });
32
+ if (!table.overflow) return table.output;
33
+ }
34
+ const scalar = value => value === null || value === undefined ? "Not observed" : value === true ? "Yes" : value === false ? "No" : terminalCell(String(value));
35
+ const lines = (item, indent = "") => Object.entries(item).flatMap(([key, value]) => {
36
+ const label = key.replaceAll("_", " ").replace(/^./, char => char.toUpperCase());
37
+ if (Array.isArray(value)) {
38
+ if (!value.length) return [`${indent}${label}: None`];
39
+ if (value.every(row => row === null || typeof row !== "object")) return [`${indent}${label}: ${value.map(scalar).join(", ")}`];
40
+ return [`${indent}${label}:`, ...value.flatMap(row => typeof row === "object" && row ? lines(row, indent + " ") : [indent + " " + scalar(row)])];
41
+ }
42
+ if (value && typeof value === "object") return [`${indent}${label}:`, ...lines(value, indent + " ")];
43
+ return [`${indent}${label}: ${scalar(value)}`];
44
+ });
45
+ return rows.map(row => lines(row).join("\n")).join("\n\n");
46
+ }
47
+ export async function runManagementCommand(command, options = {}) {
48
+ const { group, ids = {}, flags = {}, path } = command, action = path.at(-1), input = options.input || process.stdin, output = options.output || process.stdout;
49
+ const io = { format: flags.format, output }, rawRequest = options.request || (args => dashboardToolRequest({ host: options.host, port: options.port, detailedErrors: true, ...args }));
50
+ const request = async args => {
51
+ try { return await rawRequest(args); }
52
+ catch (error) {
53
+ const messages = { ccdx_connections_conflict: "Settings changed. Reload and review before saving again.", ccdx_settings_changed: "Service preferences changed. Reload and review before saving again.", ccdx_source_in_use: "This source is still selected. Review replacements or pause the affected clients.",
54
+ ccdx_source_busy: "This source has active work. Wait for it to finish before changing access.", ccdx_api_model_unavailable: "A selected model is unavailable. Saved selections were kept.",
55
+ ccdx_client_source_disabled: "Model access is paused. Review the client, source and model selection.", ccdx_api_protocol_required: "This source does not provide the required client interface." };
56
+ if (error.code && error.code !== "ccdx_tool_unavailable") error.message = messages[error.code] || `Operation rejected: ${error.code}. ${error.code.startsWith("ccdx_settings_") ? "Review service preferences and their backup; existing files were kept." : "Review the selected source or client."}`;
57
+ throw error;
58
+ }
59
+ };
60
+ const readStatus = options.readStatus || (() => readAdapterStatus({ host: options.host, port: options.port }));
61
+ const ask = options.prompt || (async question => {
62
+ if (!input.isTTY || !output.isTTY) throw new Error("This edit needs an interactive terminal or explicit file/options.");
63
+ const prompt = createInterface({ input, output });try { return await prompt.question(question); } finally { prompt.close(); }
64
+ });
65
+ const print = (value, columns) => formatManagement(value, { ...io, columns });
66
+ const confirm = async message => {
67
+ if (flags.preview) return false;
68
+ if (flags.yes) return true;
69
+ if (!/^y(?:es)?$/i.test((await ask(`${message} [y/N]: `)).trim())) throw new Error("Change cancelled; existing settings kept.");
70
+ return true;
71
+ };
72
+ const choose = async (rows, selected = [], title = "Select numbers, separated by commas") => {
73
+ rows.forEach((row, index) => output.write(`${String(index + 1).padStart(3)} ${selected.includes(index) ? "[x]" : "[ ]"} ${terminalCell(row)}\n`));
74
+ const value = (await ask(`${title} (Enter keeps selection; none clears it): `)).trim();
75
+ if (!value) return selected;if (value === "none") return [];
76
+ const numbers = value.split(",").map(item => item.trim());
77
+ if (!numbers.every(item => /^\d+$/.test(item) && Number(item) >= 1 && Number(item) <= rows.length) || new Set(numbers).size !== numbers.length) throw new Error("Choose listed, unique numbers.");
78
+ return numbers.map(item => Number(item) - 1);
79
+ };
80
+ let managementVersion = 0;
81
+ const connection = async () => {
82
+ const graph = await request({ path: "connections" });
83
+ if (graph.source !== "connections" || !Array.isArray(graph.clients) || !Array.isArray(graph.providers)) throw new Error("Incompatible connection status; existing settings were kept.");
84
+ managementVersion = graph.management_version || 0;return graph;
85
+ };
86
+ const requireManagement = () => { if (managementVersion !== 1) throw new Error("This command needs the updated running service. Finish tasks, then restart CCDX normally; no settings changed."); };
87
+ const save = body => { requireManagement();return request({ path: "connections", body, timeoutMs: 30000 }); };
88
+ const getClient = (graph, id) => { const client = graph.clients.find(item => item.id === id);if (!client) throw new Error("Client is not registered.");return client; };
89
+ const getSource = (graph, id) => { const source = graph.providers.find(item => item.id === id);if (!source) throw new Error("Source is not registered.");return source; };
90
+ const clientBody = client => ({ operation: "client", id: client.id, client_revision: client.revision, enabled: client.enabled, allowed: client.allowed, source: client.source,
91
+ ...(Array.isArray(client.deployments) ? { deployments: client.deployments, default_model: client.default_model, auto_sync: client.auto_sync } : {}) });
92
+ const readFile = () => JSON.parse(readBoundedFileSync(flags.file, { encoding: "utf8", maxBytes: 256 * 1024 }));
93
+ if (group === "status") {
94
+ const { data, baseUrl } = await readStatus();
95
+ if (flags.details) {
96
+ if (flags.format === "json") return print(data);
97
+ const { formatAdapterStatus } = await import("./cli-status.mjs");const diagnostic = formatAdapterStatus({ data, baseUrl }, { cliVersion: options.version || data.version, scoped: true });
98
+ const settings = await request({ path: "settings" });
99
+ return diagnostic + (settings.terminal?.last_notice ? `\nLatest terminal notice: ${terminalCell(settings.terminal.last_notice)}` : "");
100
+ }
101
+ const view = projectTerminalState(data);
102
+ const result = { service: "Listening", address: baseUrl, running_version: data.version, ...(options.version !== data.version ? { installed_version: options.version } : {}),
103
+ enabled_sources: view.sources?.map(source => source.name) ?? null, apps: view.clients, model_requests: { total: view.requests, active: view.active, ...view.outcomes } };
104
+ if (flags.format === "json") return print(result);
105
+ const sourceNames = view.sources?.map(source => source.name).join(" · ");
106
+ return [`CCDX ${data.version}${options.version && options.version !== data.version ? ` · installed CLI ${options.version}` : ""}`,
107
+ `Listening · ${baseUrl} · up ${terminalUptime(data.uptime_ms)}`, `Enabled sources: ${view.sources?.length ?? "unknown"}`,
108
+ ...(sourceNames ? [sourceNames] : []), "", print(view.clients, [["name", "Client"], ["setup", "Setup"], ["active", "Active"]]), "",
109
+ `Model requests: ${view.requests ?? "unknown"} total · ${view.active ?? "unknown"} active · ${view.outcomes.failed} failed`].join("\n");
110
+ }
111
+ if (group === "requests") {
112
+ let rows = retainedRequests((await readStatus()).data);
113
+ if (ids.request) {
114
+ const found = rows.find(row => row.request_id === ids.request);if (!found) throw new Error("Request not retained. No full-history lookup is available.");return print(found);
115
+ }
116
+ rows = rows.filter(row => (!flags.active || row.active) && (!flags.failed || row.state !== "cancelled" && (row.state === "failed" || row.error))
117
+ && (!flags.source || row.provider === flags.source) && (!flags.app || (flags.app === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === CLI_CLIENTS[flags.app]))).slice(-(flags.limit || 20));
118
+ return print(rows, [["request_id", "Request"], ["application", "Client"], ["provider", "Source"], ["model", "Model"], ["route", "Route"], ["state", "State"]]);
119
+ }
120
+ if (group === "usage") {
121
+ if (flags.scope === "run") {
122
+ const usage = (await readStatus()).data.runtime_usage;
123
+ if (!usage) throw new Error("Current-run usage is unavailable.");
124
+ return print(flags.provider ? usage.by_provider?.[flags.provider] || { records: 0 } : usage);
125
+ }
126
+ const { summarizeUsageLogs } = await import("./usage-store.mjs");return print(await summarizeUsageLogs(undefined, { ...(flags.provider ? { provider: flags.provider } : {}) }));
127
+ }
128
+ if (group === "update") {
129
+ const { dashboardUpdateStatus } = await import("./dashboard-updates.mjs");return print(await dashboardUpdateStatus());
130
+ }
131
+ if (group === "config") {
132
+ const preferenceOptions = { ...options, backupScope: "service" }, local = settingsPreferencesSnapshot(preferenceOptions);
133
+ const effective = live => Object.fromEntries(Object.entries(live.effective || {}).filter(([key]) => Object.hasOwn(local.defaults, key)));
134
+ if (action === "show") {
135
+ if (!flags.effective) return print({ saved: local.values, backup: local.backup, backup_error: local.backup_error });
136
+ const live = await request({ path: "settings" });return print({ saved: local.values, effective: effective(live), nightly_update: live.nightly_update, terminal_mode: live.terminal?.mode ?? "Not observed" });
137
+ }
138
+ let values, operation = "preferences", backup_id;
139
+ if (path[1] === "set") {
140
+ if (!Object.hasOwn(local.defaults, ids.key)) throw new Error("Unknown service preference. Use ccdx config show.");
141
+ let value = ids.value;
142
+ if (typeof local.defaults[ids.key] === "boolean") { if (!["true", "false"].includes(value)) throw new Error("Use true or false for this setting.");value = value === "true"; }
143
+ values = { [ids.key]: value };
144
+ } else if (action === "terminal") {
145
+ const themes = ["green", "klein", "pink"], pick = (await ask(`Terminal color [${local.values.terminal_color_theme}] (green/klein/pink): `)).trim() || local.values.terminal_color_theme;
146
+ if (!themes.includes(pick)) throw new Error("Choose green, klein or pink.");values = { terminal_color_theme: pick };
147
+ } else if (["reset", "restore"].includes(action)) {
148
+ operation = action === "reset" ? "reset_preferences" : "restore_preferences";
149
+ backup_id = action === "reset" ? randomUUID() : local.backup?.id;
150
+ if (!backup_id) throw new Error("No service preference backup is available.");
151
+ } else throw new Error("Unsupported settings action.");
152
+ if (values) checkedPreferenceValues(values);
153
+ const preview = { operation, scope: "Service and terminal preferences only; browser colors, accounts, keys, models and chats stay unchanged", values: values || (action === "reset" ? local.defaults : "Current pre-reset service backup"), revision: local.revision };
154
+ if (flags.preview) return print(preview);
155
+ output.write(print(preview) + "\n");
156
+ let running;
157
+ try { running = await readStatus(); } catch (error) {
158
+ if (!/not running/.test(error.message)) throw error;
159
+ }
160
+ if (running && operation !== "preferences") { await connection();requireManagement(); }
161
+ const risk = values?.nightly_updates ? "Overnight updates can interrupt task continuation. Save this preference?" : "Save these service preferences?";
162
+ await confirm(risk);
163
+ const body = { action: operation, revision: local.revision, ...(values ? { values } : { backup_id, scope: "service" }) };
164
+ if (running) { const result = await request({ path: "settings", body });return print({ saved: result.preferences.values, effective: effective(result), nightly_update: result.nightly_update, effect: "Saved; restart requirements are shown in effective state" }); }
165
+ writeSettingsPreferences(body, preferenceOptions);return print({ saved: settingsPreferencesSnapshot(preferenceOptions).values, effect: "Saved for the next CCDX start; no service was started" });
166
+ }
167
+ if (group === "app") {
168
+ const graph = await connection(), snapshot = (await readStatus()).data, view = projectTerminalState(snapshot);
169
+ if (action === "list") return print(view.clients, [["id", "ID"], ["name", "Client"], ["setup", "Setup"], ["active", "Active"]]);
170
+ const id = ids.app ? CLI_CLIENTS[ids.app] : "codex", client = getClient(graph, id), modelPlan = client.model_plan;
171
+ if (!flags.preview && (flags.edit || ["sync", "enable", "disable"].includes(action))) requireManagement();
172
+ const feature = path.length > 3 ? path[2] : null;
173
+ if (feature || action === "status") {
174
+ const settings = id === "codex" && (flags.details || feature) ? await request({ path: "settings" }) : null;
175
+ const preference = settings?.providers?.[client.source || "github"]?.preference || {};
176
+ const reviewId = client.auto_review_model || preference.auto_review_model || preference.model || null;
177
+ const reviewModel = modelPlan?.models.find(model => [model.id, model.public_id, model.route_id].includes(reviewId));
178
+ const details = { predictions: snapshot.client_integrations?.prediction || null, images: settings?.effective?.image_enabled || null,
179
+ auto_review: { model: reviewModel?.id || reviewId, source: reviewModel?.source || client.source, effort: client.auto_review_effort ?? preference.auto_review_effort ?? preference.reasoningEffort ?? "Follows client" }, memory_model: client.memory_model || { model: null } };
180
+ if (feature) return print({ client: "Codex", feature, state: details[{ prediction: "predictions", image: "images", review: "auto_review" }[feature]] });
181
+ const observed = retainedRequests(snapshot).filter(row => id === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === id).at(-1);
182
+ return print({ id: ids.app, access: client.enabled ? clientSetup(client) === "Paused" ? "Paused" : "Enabled" : "Disabled", setup: view.clients.find(row => row.id === id)?.setup || clientSetup(client),
183
+ selected_models: Array.isArray(client.deployments) ? client.deployments.length : modelPlan?.models.length ?? null, unavailable_selection: (modelPlan?.unavailable || []).filter(model => !modelPlan?.available.some(candidate => candidate.source === model.source && candidate.id === model.id)),
184
+ app_adoption: view.clients.find(row => row.id === id)?.active > 0 ? "Active gateway request observed; process liveness not checked" : observed ? `Gateway request observed${observed.at || observed.time ? ` at ${observed.at || observed.time}` : ""}; process liveness not checked` : client.observed_at ? `Gateway request observed at ${client.observed_at}; process liveness not checked` : "Not observed",
185
+ active: view.clients.find(row => row.id === id)?.active ?? null, ...(id === "codex" && flags.details ? { features: details, chatgpt_sign_in: "Managed by Codex; not inferred from GitHub credentials" } : {}) });
186
+ }
187
+ if (action === "models" && !flags.edit) {
188
+ if (flags.format === "json") return print(modelPlan);
189
+ return print([...(modelPlan?.models || []).map(model => ({ source: model.source, model: model.display_name || model.id, id: model.id, state: "Selected", default: [model.route_id, model.public_id].includes(modelPlan.default_model) })),
190
+ ...(modelPlan?.unavailable || []).map(model => ({ source: model.source, model: model.id, id: model.id, state: !client.enabled && modelPlan?.available.some(item => item.source === model.source && item.id === model.id) ? "Retained; access disabled" : "Unavailable; retained", default: model.route_id === modelPlan.default_model }))], [["model", "Model"], ["source", "Source"], ["state", "Selection"], ["default", "Default"]]);
191
+ }
192
+ if (action === "sync") {
193
+ const preview = { client: ids.app, models: modelPlan?.models.map(model => ({ source: model.source, model: model.display_name || model.id, id: model.id, context_window: model.capability?.values.context_window ?? null, reasoning_efforts: model.capability?.values.reasoning_efforts ?? null })), unavailable: modelPlan?.unavailable, default_model: modelPlan?.default_model,
194
+ current_setup: clientSetup(client), note: "Model/configuration plan only, not a byte-level file diff. Ownership is rechecked on sync; no App is restarted." };
195
+ if (flags.preview) return print(preview);output.write(print(preview) + "\n");await confirm("Write CCDX-owned client settings now?");
196
+ const result = await save({ operation: "sync_client", id, client_revision: client.revision });return print({ client: ids.app, setup: getClient(result, id).setup, app_adoption: "Not verified by writing configuration" });
197
+ }
198
+ if (["enable", "disable"].includes(action)) {
199
+ const enabled = action === "enable", preview = { client: ids.app, access: enabled ? "Enabled" : "Disabled", retained_source: client.source,
200
+ retained_models: client.deployments || "Legacy source binding retained", note: "Only gateway access changes; the client program stays open." };
201
+ if (flags.preview) return print(preview);output.write(print(preview) + "\n");
202
+ await confirm(enabled ? "Enable gateway access with the saved selection?" : "Disable gateway access? Later turns may fail; saved selections are retained.");
203
+ const result = await save({ operation: "client_state", id, enabled, client_revision: client.revision });
204
+ return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
205
+ }
206
+ const body = clientBody(client);
207
+ if (action === "models") {
208
+ if (flags.file) {
209
+ const file = readFile();if (Object.keys(file).some(key => !["deployments", "default_model", "auto_sync"].includes(key))) throw new Error("Model files allow deployments, default_model and auto_sync only.");
210
+ if (!Array.isArray(file.deployments)) throw new Error("Model files require an explicit deployments array; use [] to pause access.");
211
+ Object.assign(body, file);if (!body.deployments.length) body.default_model = null;
212
+ } else {
213
+ const available = [...(modelPlan?.available || [])], selected = Array.isArray(client.deployments) ? client.deployments : modelPlan?.models.map(model => ({ source: model.source, model: model.id })) || [];
214
+ for (const old of selected) if (!available.some(row => row.source === old.source && row.id === old.model)) available.push({ source: old.source, id: old.model, unavailable: true });
215
+ const indexes = await choose(available.map(row => `${row.source} / ${row.id}${row.unavailable ? " (unavailable; selection retained)" : ""}`), available.flatMap((row, index) => selected.some(item => item.source === row.source && item.model === row.id) ? [index] : []));
216
+ body.deployments = indexes.map(index => ({ source: available[index].source, model: available[index].id }));
217
+ body.default_model = client.default_model || modelPlan?.default_model || null;
218
+ if (body.deployments.length) {
219
+ const defaults = body.deployments.map(item => deploymentModelId(item.source, item.model));
220
+ output.write(body.deployments.map((item, index) => `${index + 1} ${item.source} / ${item.model}`).join("\n") + "\n");
221
+ const value = (await ask(`Default model number [${Math.max(1, defaults.indexOf(body.default_model) + 1)}]: `)).trim();
222
+ if (value && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > defaults.length)) throw new Error("Choose a listed default model number.");
223
+ body.default_model = defaults[value ? Number(value) - 1 : Math.max(0, defaults.indexOf(body.default_model))];
224
+ } else body.default_model = null;
225
+ }
226
+ if (body.deployments?.some(item => modelPlan?.unavailable.some(row => row.source === item.source && row.id === item.model))) throw new Error("Unavailable selections were kept. Wait for the catalog or explicitly deselect them before saving a changed plan.");
227
+ } else throw new Error("Unsupported client action.");
228
+ const memory = id === "codex" ? client.memory_model?.model : null;
229
+ const memoryModels = [...(modelPlan?.models || []), ...(modelPlan?.available || []), ...(modelPlan?.unavailable || [])].filter(row => [row.id, row.route_id, row.public_id].includes(memory));
230
+ const memoryPairs = new Set(memoryModels.map(row => row.source + "\0" + row.id));
231
+ const memoryMatch = row => memoryPairs.size ? memoryPairs.has(row.source + "\0" + (row.model || row.id)) : [row.model, row.id, row.route_id, row.public_id].includes(memory);
232
+ if (memory && (client.deployments || modelPlan?.models || []).some(memoryMatch) && Array.isArray(body.deployments) && !body.deployments.some(memoryMatch)) {
233
+ output.write(`Warning: ${terminalCell(memory)} is an observed memory dependency; memory writing may fail if it is unselected.\n`);
234
+ }
235
+ const checked = await save({ ...body, operation: "preview_client" });
236
+ output.write(print({ client: ids.app, planned_models: checked.preview?.models.map(model => ({ source: model.source, id: model.id })), change: action, enabled: body.enabled, deployments: body.deployments, default_model: body.default_model }) + "\n");
237
+ if (flags.preview) return "Preview only; no settings changed.";
238
+ await confirm(body.enabled ? "Save this client selection?" : "Disable gateway access? Later turns may fail; the client program stays open.");
239
+ const result = await save(body);return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
240
+ }
241
+ if (group !== "source") throw new Error("Unknown management command.");
242
+ let graph = await connection();
243
+ if (!flags.preview && (flags.edit || ["add", "edit", "enable", "disable", "remove"].includes(action))) requireManagement();
244
+ if (action === "list") return print(graph.providers.map(source => ({ id: source.id, name: source.name, enabled: source.enabled, key_saved: source.builtin ? undefined : source.key_saved })), [["id", "ID"], ["name", "Source"], ["enabled", "Enabled"]]);
245
+ const id = ids.source, source = id ? getSource(graph, id) : null;
246
+ if (action === "status" || action === "models" && !flags.refresh) {
247
+ if (action === "models" && source.builtin) {
248
+ return print(await save({ operation: "source_catalog", id }));
249
+
250
+ }
251
+ if (action === "models") return print({ source: id, evidence: "Saved API model selection; access not checked", models: source.models });
252
+ const diagnostics = await request({ path: "providers" }), observed = diagnostics.providers.find(provider => provider.id === id);
253
+ return print({ id, name: source.name, saved_enabled: source.enabled, runtime_state: observed?.state || "Not observed", credentials: source.builtin ? observed?.auth : { key_saved: source.key_saved },
254
+ catalog: observed?.models || source.discovery || { count: source.models?.length ?? null, source: "configured" }, access: "Not inferred from saved credentials or configuration", diagnostic: observed?.catalog_diagnostic || null });
255
+ }
256
+ if (action === "check" || action === "models" && flags.refresh) {
257
+ if (!source.enabled || id === "m365" && graph.m365_state === "disabled") throw new Error("Source is disabled; it was not enabled automatically.");
258
+ if (action === "check" && id === "github") {
259
+ const checked = await request({ path: "account", body: { action: "check" }, timeoutMs: 60000 });
260
+ if (checked.online?.ok === false) throw Object.assign(new Error(`GitHub access check failed: ${checked.online.reason}`), { code: checked.online.reason });return print(checked);
261
+ }
262
+ return print(source.builtin ? await request({ path: `models/live?provider=${encodeURIComponent(id)}`, timeoutMs: 60000 }) : (await save({ operation: "discover", id })).discovered);
263
+ }
264
+ if (action === "access") {
265
+ const current = graph.clients.filter(client => client.allowed.includes(id)).map(client => client.id);
266
+ if (!flags.edit) return print({ source: id, authorized_clients: current.map(value => Object.keys(CLI_CLIENTS).find(key => CLI_CLIENTS[key] === value)), consuming_clients: graph.source_impacts?.[id]?.clients || [] });
267
+ const allowed = flags.apps !== undefined ? flags.apps === "none" ? [] : flags.apps.split(",").map(app => { if (!CLI_CLIENTS[app]) throw new Error("Use listed client IDs, or none.");return CLI_CLIENTS[app]; })
268
+ : (await choose(graph.clients.map(client => TERMINAL_CLIENT_NAMES[client.id]), graph.clients.flatMap((client, index) => current.includes(client.id) ? [index] : []))).map(index => graph.clients[index].id);
269
+ output.write(print({ source: id, before: current, after: allowed, effect: "Revoked routes are removed; added grants do not select models" }) + "\n");
270
+ if (flags.preview) return "Preview only; access unchanged.";await confirm("Save source authorization for these clients?");
271
+ const result = await save({ operation: "source_access", id, allowed, impact_revision: graph.source_impacts[id].revision });
272
+ return print({ source: id, authorized_clients: result.clients.filter(client => client.allowed.includes(id)).map(client => TERMINAL_CLIENT_NAMES[client.id]), saved: true });
273
+ }
274
+ if (["enable", "disable", "remove"].includes(action)) {
275
+ const impact = graph.source_impacts?.[id];
276
+ if (action === "remove" && (source.builtin || source.enabled || graph.clients.some(client => client.source === id || client.deployments?.some(item => item.source === id)))) throw new Error("Only a disabled API with no selected consumers can be removed. Disable it and review replacements first.");
277
+ let replacements;
278
+ if (action === "disable") {
279
+ replacements = flags.replacements ? JSON.parse(flags.replacements) : {};
280
+ if (!replacements || typeof replacements !== "object" || Array.isArray(replacements)) throw new Error("Replacements must be a JSON object.");
281
+ replacements = Object.fromEntries(Object.entries(replacements).map(([key, value]) => { const client = CLI_CLIENTS[key] || Object.values(CLI_CLIENTS).find(id => id === key);if (!client) throw new Error("Unknown replacement client");return [client, value]; }));
282
+ for (const client of impact?.clients.filter(client => client.needs_replacement) || []) if (!Object.hasOwn(replacements, client.id)) {
283
+ if (flags.yes && !flags.preview) throw new Error("Provide explicit --replacements JSON for every affected client; null pauses it.");
284
+ if (!flags.preview) {
285
+ const value = (await ask(`${TERMINAL_CLIENT_NAMES[client.id]} replacement source ID (none pauses): `)).trim();
286
+ if (!value) throw new Error("Enter a source ID or none; bindings were kept.");replacements[client.id] = value === "none" ? null : value;
287
+ }
288
+ }
289
+ }
290
+ output.write(print({ source: id, action, affected_clients: impact?.clients || [], replacements }) + "\n");
291
+ if (flags.preview) return "Preview only; sources and bindings unchanged.";await confirm(`Apply source ${action}?`);
292
+ const result = await save(action === "remove" ? { operation: "remove_api", id, impact_revision: impact.revision } : { operation: "provider", id, impact_revision: impact.revision, enabled: action === "enable", ...(action === "disable" ? { replacements } : {}) });
293
+ return print({ source: id, ...(action === "remove" ? { removed: true } : { saved_enabled: getSource(result, id).enabled }),
294
+ affected_clients: (impact?.clients || []).map(client => ({ name: TERMINAL_CLIENT_NAMES[client.id], setup: getClient(result, client.id).setup })) });
295
+ }
296
+ if (!["add", "edit"].includes(action) || source?.builtin) throw new Error("This action is available for API sources only.");
297
+ let config, allowed, key;
298
+ if (flags.file) {
299
+ const file = readFile();if (Object.keys(file).some(key => !["config", "allowed"].includes(key))) throw new Error("API files contain config and allowed only; supply keys privately.");
300
+ config = file.config;allowed = file.allowed || [];
301
+ if (!config || typeof config !== "object" || Object.keys(config).some(key => !["name", "base_url", "endpoints", "auth_header", "models", "key_env"].includes(key))) throw new Error("Use API metadata only; keys must use private input or key_env.");
302
+ } else {
303
+ const base = (await ask(`API base URL${source ? ` [${source.base_url}]` : ""}: `)).trim() || source?.base_url;
304
+ const name = (await ask(`Source name${source ? ` [${source.name}]` : ""}: `)).trim() || source?.name;
305
+ const protocols = (await ask(`Interfaces [${Object.keys(source?.endpoints || { responses: 1, messages: 1 }).join(",")}]: `)).trim();
306
+ const enabled = protocols ? protocols.split(",").map(value => value.trim()) : Object.keys(source?.endpoints || { responses: 1, messages: 1 });
307
+ if (!base || !name || enabled.some(value => !["responses", "messages", "chat"].includes(value))) throw new Error("Enter a URL, source name and supported interfaces.");
308
+ const authHeader = (await ask(`API key header [${source?.auth_header || "x-api-key"}] (x-api-key/bearer): `)).trim() || source?.auth_header || "x-api-key";
309
+ config = { ...(source ? apiConfig(source) : { models: [], auth_header: "x-api-key" }), name, base_url: base, auth_header: authHeader,
310
+ endpoints: Object.fromEntries(enabled.map(protocol => [protocol, source?.base_url === base && source.endpoints?.[protocol] || base.replace(/\/+$/, "") + "/" + (protocol === "chat" ? "chat/completions" : protocol)])) };
311
+ allowed = (await choose(graph.clients.map(client => TERMINAL_CLIENT_NAMES[client.id]), graph.clients.flatMap((client, index) => source && client.allowed.includes(id) ? [index] : []), "Authorize clients")).map(index => graph.clients[index].id);
312
+ }
313
+ if (!Array.isArray(allowed) || new Set(allowed).size !== allowed.length || allowed.some(id => !Object.values(CLI_CLIENTS).includes(id))) throw new Error("Use unique, listed client IDs for API authorization.");
314
+ checkedApi({ ...config, id: source?.id || "api_preview", enabled: true, ...(config.key_env ? {} : { secret_ref: "0".repeat(32) }) });
315
+ if (flags.preview) return print({ config, allowed, note: "Key not read; no source or client settings changed" });
316
+ if (!config.key_env) {
317
+ if (flags.key_stdin) key = await readSecretInput(input);
318
+ else if (flags.file) {
319
+ if (!source?.key_saved || new URL(source.base_url).origin !== new URL(config.base_url).origin) throw new Error("Supply --key-stdin or key_env for this API; same-origin saved keys can be kept without re-entry.");
320
+ } else key = await (options.promptSecret || ((question) => hiddenQuestion(input, output, question, { cancelMessage: "API setup cancelled" })))(source ? "API key (hidden; Enter keeps the same-origin key): " : "API key (hidden): ");
321
+ if (source && new URL(source.base_url).origin !== new URL(config.base_url).origin && !key) throw new Error("Changing API origin requires a new key.");
322
+ }
323
+ await confirm("Save this API configuration and client authorization?");
324
+ graph = await save({ operation: "save_api", ...(id ? { id, impact_revision: graph.source_impacts[id].revision } : {}), config, allowed, ...(key ? { key } : {}) });key = undefined;
325
+ const saved = id ? getSource(graph, id) : graph.providers.find(row => !row.builtin && row.name === config.name);
326
+ if (!saved) throw new Error("The source was saved but could not be identified. Review source list.");
327
+ if (flags.file) return print({ source: saved.id, saved: true, models: saved.models.length, note: "Source saved; background catalog discovery is independent of model selection" });
328
+ let catalog;
329
+ try { graph = await save({ operation: "discover", id: saved.id });catalog = graph.discovered || [];allowed = graph.clients.filter(client => client.allowed.includes(saved.id)).map(client => client.id); }
330
+ catch (error) { throw Object.assign(new Error(`Source ${saved.id} was saved, but model lookup failed (${error.code || error.message}). Saved source kept; retry ccdx source ${saved.id} models --refresh.`), { code: "ccdx_source_saved_catalog_unavailable" }); }
331
+ const picks = await choose(catalog.map(model => `${model.id} / ${model.protocols.join(", ")}`), catalog.flatMap((model, index) => saved.models.some(row => row.id === model.id) ? [index] : []), "Select API models");
332
+ const selected = picks.map(index => { const { display, ...model } = catalog[index];return model; });
333
+ for (const model of selected) if (!model.protocols.length) {
334
+ const value = (await ask(`Interfaces for ${model.id} (${Object.keys(config.endpoints).join(", ")}): `)).trim();
335
+ model.protocols = value.split(",").map(item => item.trim());
336
+ if (!value || model.protocols.some(api => !config.endpoints[api])) throw new Error("Choose configured interfaces explicitly; source settings were kept.");
337
+ }
338
+ const result = await save({ operation: "save_api", id: saved.id, impact_revision: graph.source_impacts[saved.id]?.revision, config: { ...apiConfig(getSource(graph, saved.id)), models: selected }, allowed });
339
+ return print({ source: saved.id, selected_models: getSource(result, saved.id).models.length, next: "Choose visible models separately under ccdx app <id> models --edit" });
340
+ }
@@ -1,3 +1,4 @@
1
+ import { parseManagedCommand, managedCommandHelp, rootCommandHelp } from "./cli-command-spec.mjs";
1
2
  import { isProviderId } from "./provider-metadata.mjs";
2
3
  import { MAX_TIMER_DELAY_MS } from "./runtime-config.mjs";
3
4
 
@@ -130,6 +131,12 @@ function parseStartOptions(args) {
130
131
  export function parseCliArgs(args = []) {
131
132
  const [command, ...rest] = args;
132
133
  if (!command) return baseCommand("start");
134
+ const helpParts = HELP_COMMANDS.has(command) ? rest : HELP_COMMANDS.has(args.at(-1)) ? args.slice(0, -1) : null;
135
+ if (helpParts && managedCommandHelp(helpParts) !== null) return baseCommand("help", { helpTopic: helpParts.join(" ") });
136
+ if (["app", "config"].includes(command) && !rest.length) return baseCommand("help", { helpTopic: command });
137
+ const managed = parseManagedCommand(args);
138
+ if (managed) return managed.legacy ? parseCliArgs(managed.legacy) : baseCommand("manage", managed);
139
+
133
140
  if (command === "reauth") return parseCliArgs(["auth", "reauth", ...rest]);
134
141
  if (command === "source") { if (rest.length === 1 && HELP_COMMANDS.has(rest[0])) return helpCommand(["source"]);return parseCliArgs(["m365", "switch", ...rest]); }
135
142
  if (command === "web") { if (rest.length === 1 && HELP_COMMANDS.has(rest[0])) return helpCommand(["web"]);if (rest.length) unexpectedArgs(rest);return baseCommand("web"); }
@@ -430,56 +437,16 @@ function topicHelp(name, topic) {
430
437
  }
431
438
 
432
439
  export function cliHelp(commandName = "ccdx", topic = "") {
433
- const name = "ccdx";
434
- const normalizedTopic = checkedHelpTopic(topic ? topic.split(" ") : []);
435
- if (normalizedTopic) return topicHelp(name, normalizedTopic);
436
- return `Usage:
437
- ${name} [start] [--show-request-id] [--no-browser] [--verbose]
438
- ${name} auth status [--online] [--format table|plain]
439
- ${name} doctor [--online] [--compat] [--fix] [--json]
440
- ${name} doctor config
441
- ${name} doctor network
442
- ${name} doctor report
443
- ${name} auth [login|reauth|check|logout]
444
- ${name} web
445
- ${name} source [github|m365]
446
- ${name} image [status|pause|resume]
447
- ${name} status
448
- ${name} models [--format table|plain]
449
- ${name} usage [--format table|plain] [--provider ID]
450
- ${name} cache [--limit <MiB|default> | --clean [--history] [--yes]]
451
- ${name} limits [--decoded <MiB|default>]
452
- ${name} animation
453
- ${name} enable-image
454
- ${name} disable-image
455
- ${name} image-status
456
- ${name} auto-review-model
457
- ${name} prediction [status|on|off|fix|pause|resume]
458
- ${name} m365 [status|models|accounts|account|switch|on|off|remove]
459
- ${name} update [npm|github] [--allow-remote]
460
- ${name} --version
461
- ${name} --help
462
-
463
- Commands:
464
- start Start or reuse the adapter and configure Codex
465
- auth Manage GitHub sign-in and check access
466
- web Open local account and repair tools
467
- source Choose a Codex model source
468
- image Inspect, pause or resume image requests
469
- doctor Diagnose local config; optional live and inference checks
470
- status Show runtime routing, performance, queue, and cache health
471
- models Show the selected Codex provider's GPT model catalog
472
- usage Summarize locally recorded token usage
473
- cache Inspect, size, or clear bounded runtime caches
474
- limits Inspect or configure the decoded request-body limit
475
- animation Select the terminal activity animation
476
- enable-image Configure and enable the optional image provider
477
- disable-image Disable the image provider and remove its credential
478
- image-status Show the optional image provider status
479
- auto-review-model Select the Codex Auto-review model and reasoning effort
480
- prediction Toggle optional native next-message predictions
481
- m365 Manage M365 Claude access and the optional Codex backup
482
- update Update the global package from npm or GitHub
483
-
484
- Run ${name} <command> --help for command details.`;
440
+ if (!topic) return rootCommandHelp();
441
+ const parts = topic.split(" "), canonical = managedCommandHelp(parts);
442
+ if (canonical !== null) {
443
+ const feature = parts[0] === "app" && parts[1] === "codex" ? parts[2] : null;
444
+ const integration = feature === "prediction" ? "prediction" : feature === "image" ? parts[3] === "remove" ? "disable-image" : "enable-image" : feature === "review" ? "auto-review-model"
445
+ : parts[0] === "source" && parts[1] === "github" && ["login", "reauth", "logout"].includes(parts[2]) ? "auth"
446
+ : parts[0] === "source" && parts[1] === "m365" && parts[2] === "account" ? "m365"
447
+ : parts[0] === "doctor" && parts[1] === "cache" ? "cache" : parts[0] === "config" && ["limits", "animation"].includes(parts[1]) ? parts[1] : parts[0] === "update" ? "update" : null;
448
+ const notes = integration ? topicHelp("ccdx", integration).split("\n\n").slice(1).join("\n\n") : "";
449
+ return canonical + (notes ? "\n\nIntegration details:\n" + notes : "");
450
+ }
451
+ return topicHelp("ccdx", checkedHelpTopic(topic.split(" ")));
485
452
  }
@@ -134,7 +134,7 @@ export async function readAdapterStatus({
134
134
  }
135
135
  }
136
136
 
137
- export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", cliVersion = data.version } = {}) {
137
+ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", cliVersion = data.version, scoped = false } = {}) {
138
138
  const requests = data.requests || {};
139
139
  const performance = data.stream_performance?.by_route?.responses || {};
140
140
  const terminalOutcomes = performance.terminal_outcomes?.totals;
@@ -154,7 +154,7 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
154
154
  const lines = [
155
155
  `${commandName} status`,
156
156
  adapterLine,
157
- status("info", `Requests: ${count(requests.completed)}/${count(requests.total)} completed, ${count(requests.active)} active, ${count(requests.status_4xx)} 4xx, ${count(requests.status_5xx)} 5xx, ${count(requests.aborted)} aborted`),
157
+ status("info", `${scoped ? "HTTP requests" : "Requests"}: ${count(requests.completed)}/${count(requests.total)} completed, ${count(requests.active)} active, ${count(requests.status_4xx)} 4xx, ${count(requests.status_5xx)} 5xx, ${count(requests.aborted)} aborted`),
158
158
  status("info", `Responses stream: TTFT avg ${firstOutputLatency(performance.ttft_ms)} (${count(performance.ttft_ms?.samples)} samples), output avg ${outputRate(performance.output_tokens_per_second)} (${count(performance.output_tokens_per_second?.samples)} samples; gateway estimate)`),
159
159
  ...(terminalOutcomes ? [status("info", `Model outcomes: ${count(terminalOutcomes.completed)} completed, ${count(terminalOutcomes.incomplete)} incomplete, ${count(terminalOutcomes.failed)} failed, ${count(terminalOutcomes.cancelled)} cancelled, ${count(terminalOutcomes.unknown)} without terminal`)] : []),
160
160
  status("info", `Admission: ${count(admission.activeRequests)} active, ${count(admission.queued)} queued, ${count(admission.rejected)} rejected, ${count(admission.timedOut)} timed out, wait avg ${latency(admission.waitMsAvg)}`),
@@ -205,19 +205,19 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
205
205
  lines.push(status("warn", `HTTP ${count(failure.http_status)} ${terminalCell(failure.model)} ${terminalCell(failure.code)}${failure.reason ? ` reason=${terminalCell(failure.reason)}` : ""}${failure.parameter ? ` param=${terminalCell(failure.parameter)}` : ""}; ${terminalCell(failure.origin)}; ${count(failure.upstream_attempts)} attempts`));
206
206
  }
207
207
  }
208
- lines.push(status("info", `Models: ${count(models.models)} total; Copilot token ${copilot.token_cached ? `cached (${duration(copilot.token_expires_in_ms)} remaining)` : "not cached"}`));
208
+ lines.push(status("info", `${scoped ? "Codex models" : "Models"}: ${count(models.models)} total; Copilot token ${copilot.token_cached ? `cached (${duration(copilot.token_expires_in_ms)} remaining)` : "not cached"}`));
209
209
  const prediction = data.client_integrations?.prediction;
210
210
  if (prediction) {
211
- lines.push(status("info", `Native predictions: ${prediction.configured ? "on" : "off"}; bridge ${prediction.bridge}; client route ${prediction.client_route}; visible candidate unknown`));
212
- if (prediction.launch_route) lines.push(status("info", `Prediction self-check: App route ${prediction.launch_route}; persistent route ${prediction.persistence || "unknown"}; ${count(prediction.recovery?.recovered)} bridge recoveries, ${count(prediction.recovery?.attempts)}/3 attempts used`));
211
+ lines.push(status("info", `${scoped ? "Codex predictions" : "Native predictions"}: ${prediction.configured ? "on" : "off"}; bridge ${prediction.bridge}; client route ${prediction.client_route}; visible candidate unknown`));
212
+ if (prediction.launch_route) lines.push(status("info", `${scoped ? "Codex prediction route" : "Prediction self-check"}: App route ${prediction.launch_route}; persistent route ${prediction.persistence || "unknown"}; ${count(prediction.recovery?.recovered)} bridge recoveries, ${count(prediction.recovery?.attempts)}/3 attempts used`));
213
213
  if (prediction.reason) lines.push(status("warn", terminalCell(prediction.reason).slice(0, 400)));
214
214
  if (prediction.environment) lines.push(status("info", formatPredictionEnvironment(prediction.environment)));
215
215
  }
216
216
  if (data.profiles?.codex) {
217
- lines.push(status("info", `Profile: ${profileSummary("Codex", data.profiles.codex)}`));
217
+ lines.push(status("info", `${scoped ? "GitHub profile for Codex" : "Profile"}: ${profileSummary("Codex", data.profiles.codex)}`));
218
218
  }
219
219
  if (data.routing?.responses) {
220
- lines.push(status("info", `Routing: /v1/responses -> ${routingTarget(data.routing.responses)}`));
220
+ lines.push(status("info", `${scoped ? "Codex routing" : "Routing"}: /v1/responses -> ${routingTarget(data.routing.responses)}`));
221
221
  }
222
222
  if (data.providers?.m365) {
223
223
  const m365 = data.providers.m365;
package/src/cli-tools.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import { adapterBaseUrl, checkRunningAdapter } from "./running-adapter.mjs";
2
2
  import { isLoopbackHost } from "./security.mjs";
3
3
  import { readBoundedResponseText } from "./upstream-body.mjs";
4
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
4
5
  import { writeServicePreference } from "./user-settings.mjs";
5
6
 
6
- export async function dashboardToolRequest({ host = "127.0.0.1", port = 2026, path = "account", body, fetchImpl = fetch, timeoutMs = 5000 } = {}) {
7
+ export async function dashboardToolRequest({ host = "127.0.0.1", port = 2026, path = "account", body, fetchImpl = fetch, timeoutMs = 5000, detailedErrors = false } = {}) {
7
8
  const baseUrl = adapterBaseUrl(isLoopbackHost(host) ? host : "127.0.0.1", port);
8
9
  const running = await checkRunningAdapter({ host, port, fetchImpl, timeoutMs });
9
10
  if (!running.ok) throw new Error("Start or restart CCDX to use this tool.");
@@ -11,7 +12,7 @@ export async function dashboardToolRequest({ host = "127.0.0.1", port = 2026, pa
11
12
  headers: { "X-CCDX-Dashboard": "1", Origin: baseUrl, ...(body ? { "Content-Type": "application/json" } : {}) },
12
13
  ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(timeoutMs) });
13
14
  const data = JSON.parse(await readBoundedResponseText(response, { maxBytes: 1024 * 1024, label: "Local tool response" }));
14
- if (!response.ok) throw new Error("Local tool is unavailable. Restart the updated CCDX service.");
15
+ if (!response.ok) throw Object.assign(new Error(detailedErrors && typeof data.error === "string" ? redactDiagnosticText(data.error.slice(0, 300)) : "Local tool is unavailable. Restart the updated CCDX service."), { statusCode: response.status, code: /^(?:ccdx|m365|auth)_[a-z0-9_]+$/.test(data.code || data.error || "") ? data.code || data.error : "ccdx_tool_unavailable" });
15
16
  return data;
16
17
  }
17
18
 
@@ -13,7 +13,7 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
13
13
  const prediction = createPredictionState();
14
14
  let native = null;
15
15
  let operation = null, operationName = null, closed = false;
16
- let pendingRoutePid = null;
16
+ let pendingRoutePid = null, codexSetup = null;
17
17
  async function startPredictionBridge(expectedPort, environment) {
18
18
  const started = await startPrediction({ state: prediction, warning: info,
19
19
  ...(environment ? { environment } : {}), ...(expectedPort ? { expectedPort } : {}) });
@@ -52,7 +52,11 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
52
52
  retirePredictionIntegration();
53
53
  } catch { /* Legacy cleanup is optional; never interrupt or clutter core startup. */ }
54
54
  const enabled = Boolean(readImageProviderConfig());
55
- const { imageMcpSkipped } = ensureCodexConfig(port, { host, imageProviderEnabled: enabled, ...(configLog ? { log: configLog } : {}) });
55
+ let imageMcpSkipped;
56
+ try {
57
+ const result = ensureCodexConfig(port, { host, imageProviderEnabled: enabled, ...(configLog ? { log: configLog } : {}) });
58
+ imageMcpSkipped = result.imageMcpSkipped;codexSetup = { setup: result.coreSetup, checked_at: new Date().toISOString() };
59
+ } catch (error) { codexSetup = { setup: "configuration_unavailable", checked_at: new Date().toISOString() };throw error; }
56
60
  if (enabled && !imageMcpSkipped) {
57
61
  try {
58
62
  const { syncEnabledImageSkill } = await import("./cli-image.mjs");
@@ -120,7 +124,7 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
120
124
  const active = native?.setActive?.(value) ?? false;
121
125
  return { active, state: active ? "active" : native ? "paused" : "needs_setup" };
122
126
  },
123
- snapshot() { return { prediction: { ...prediction.snapshot(), active: native?.enabled?.() === true } }; },
127
+ snapshot() { return { codex: codexSetup ? { ...codexSetup } : null, prediction: { ...prediction.snapshot(), active: native?.enabled?.() === true } }; },
124
128
  busy: () => Boolean(operation),
125
129
  bridgeHealthy: () => native?.healthy?.() === true,
126
130
  pauseForUpdate() { return serialize("pause", async () => { await native?.close();native = null; }); },
package/src/config.mjs CHANGED
@@ -315,7 +315,8 @@ function ensureCodexConfigUnlocked(adapterPort = 2026, {
315
315
  }
316
316
  // Disabled means no image maintenance, including no implicit removal of old
317
317
  // or user-owned entries. Explicit disable-image owns the cleanup operation.
318
- if (!imageProviderEnabled) return { imageMcpSkipped: false };
318
+ const coreSetup = parseCodexToml(core.content).openai_base_url === baseUrl ? "configured" : "preserved";
319
+ if (!imageProviderEnabled) return { coreSetup, imageMcpSkipped: false };
319
320
  try {
320
321
  const previousBaseUrl = content === undefined ? undefined : parseCodexToml(content).openai_base_url;
321
322
  const image = computeImageConfig(core.content, { enabled: true, adapterPort, adapterHost: host }, previousBaseUrl);
@@ -325,9 +326,9 @@ function ensureCodexConfigUnlocked(adapterPort = 2026, {
325
326
  }
326
327
  atomicWriteFileIfChangedSync(filePath, image.content);
327
328
  }
328
- return { imageMcpSkipped: false };
329
+ return { coreSetup, imageMcpSkipped: false };
329
330
  } catch (error) {
330
331
  console.warn(status("warn", `Image MCP setup was skipped: ${error.message}. Core proxy startup will continue.`));
331
- return { imageMcpSkipped: true };
332
+ return { coreSetup, imageMcpSkipped: true };
332
333
  }
333
334
  }