codex-copilot-dx 1.2.32 → 1.3.0

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 (48) hide show
  1. package/README.md +65 -113
  2. package/bin/cli.mjs +61 -103
  3. package/docs/ARCHITECTURE.md +51 -3
  4. package/docs/README.md +9 -76
  5. package/docs/REFERENCE.md +137 -1827
  6. package/package.json +11 -4
  7. package/src/access-settings.mjs +2 -2
  8. package/src/adapter.mjs +1 -1
  9. package/src/auth-credentials.mjs +1 -1
  10. package/src/auto-review-model.mjs +2 -2
  11. package/src/cli-animation.mjs +2 -2
  12. package/src/cli-auth.mjs +3 -3
  13. package/src/cli-cache.mjs +2 -2
  14. package/src/cli-command-spec.mjs +325 -0
  15. package/src/cli-image.mjs +4 -4
  16. package/src/cli-limits.mjs +2 -2
  17. package/src/cli-m365.mjs +1 -1
  18. package/src/cli-management.mjs +344 -0
  19. package/src/cli-options.mjs +73 -443
  20. package/src/cli-status.mjs +7 -7
  21. package/src/cli-tools.mjs +3 -2
  22. package/src/client-integration.mjs +7 -3
  23. package/src/config.mjs +4 -3
  24. package/src/connection-runtime.mjs +1414 -350
  25. package/src/copilot-token-session.mjs +1 -1
  26. package/src/dashboard/connections.js +23 -4
  27. package/src/dashboard/ui.css +9 -2
  28. package/src/dashboard-api.mjs +5 -5
  29. package/src/doctor.mjs +4 -4
  30. package/src/image-mcp.mjs +2 -2
  31. package/src/native-prediction-fix.mjs +1 -1
  32. package/src/native-prediction-profile.mjs +1 -1
  33. package/src/native-prediction-windows.mjs +1 -1
  34. package/src/native-prediction.mjs +6 -6
  35. package/src/nightly-update.mjs +2 -2
  36. package/src/provider-runtime.mjs +1 -1
  37. package/src/providers/m365-accounts.mjs +1 -1
  38. package/src/release-install.mjs +11 -15
  39. package/src/service-control.mjs +1 -1
  40. package/src/settings-preferences.mjs +6 -4
  41. package/src/startup-ui.mjs +34 -2
  42. package/src/terminal-console.mjs +32 -30
  43. package/src/terminal-state.mjs +69 -0
  44. package/src/usage.mjs +5 -5
  45. package/src/windows-command.mjs +2 -2
  46. package/bin/codex-copilot-dx.mjs +0 -11
  47. package/src/cli-models.mjs +0 -94
  48. package/src/legacy-command-warning.mjs +0 -38
@@ -0,0 +1,344 @@
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 = terminalCell(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
+ `Running · up ${terminalUptime(data.uptime_ms)}`, `Web UI: ${baseUrl}`, `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");
127
+ const summary = await summarizeUsageLogs(undefined, { ...(flags.provider ? { provider: flags.provider } : {}) });
128
+ if (flags.format === "json") return print(summary);
129
+ const { formatUsageSummary } = await import("./usage.mjs");
130
+ return formatUsageSummary(summary, { format: flags.format || "auto", output });
131
+ }
132
+ if (group === "update") {
133
+ const { dashboardUpdateStatus } = await import("./dashboard-updates.mjs");return print(await dashboardUpdateStatus());
134
+ }
135
+ if (group === "config") {
136
+ const preferenceOptions = { ...options, backupScope: "service" }, local = settingsPreferencesSnapshot(preferenceOptions);
137
+ const effective = live => Object.fromEntries(Object.entries(live.effective || {}).filter(([key]) => Object.hasOwn(local.defaults, key)));
138
+ if (action === "show") {
139
+ if (!flags.effective) return print({ saved: local.values, backup: local.backup, backup_error: local.backup_error });
140
+ 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" });
141
+ }
142
+ let values, operation = "preferences", backup_id;
143
+ if (path[1] === "set") {
144
+ if (!Object.hasOwn(local.defaults, ids.key)) throw new Error("Unknown service preference. Use ccdx config show.");
145
+ let value = ids.value;
146
+ 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"; }
147
+ values = { [ids.key]: value };
148
+ } else if (action === "terminal") {
149
+ const themes = ["green", "klein", "pink"], pick = (await ask(`Terminal color [${local.values.terminal_color_theme}] (green/klein/pink): `)).trim() || local.values.terminal_color_theme;
150
+ if (!themes.includes(pick)) throw new Error("Choose green, klein or pink.");values = { terminal_color_theme: pick };
151
+ } else if (["reset", "restore"].includes(action)) {
152
+ operation = action === "reset" ? "reset_preferences" : "restore_preferences";
153
+ backup_id = action === "reset" ? randomUUID() : local.backup?.id;
154
+ if (!backup_id) throw new Error("No service preference backup is available.");
155
+ } else throw new Error("Unsupported settings action.");
156
+ if (values) checkedPreferenceValues(values);
157
+ 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 };
158
+ if (flags.preview) return print(preview);
159
+ output.write(print(preview) + "\n");
160
+ let running;
161
+ try { running = await readStatus(); } catch (error) {
162
+ if (!/not running/.test(error.message)) throw error;
163
+ }
164
+ if (running && operation !== "preferences") { await connection();requireManagement(); }
165
+ const risk = values?.nightly_updates ? "Overnight updates can interrupt task continuation. Save this preference?" : "Save these service preferences?";
166
+ await confirm(risk);
167
+ const body = { action: operation, revision: local.revision, ...(values ? { values } : { backup_id, scope: "service" }) };
168
+ 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" }); }
169
+ writeSettingsPreferences(body, preferenceOptions);return print({ saved: settingsPreferencesSnapshot(preferenceOptions).values, effect: "Saved for the next CCDX start; no service was started" });
170
+ }
171
+ if (group === "app") {
172
+ const graph = await connection(), snapshot = (await readStatus()).data, view = projectTerminalState(snapshot);
173
+ if (action === "list") return print(view.clients, [["id", "ID"], ["name", "Client"], ["setup", "Setup"], ["active", "Active"]]);
174
+ const id = ids.app ? CLI_CLIENTS[ids.app] : "codex", client = getClient(graph, id), modelPlan = client.model_plan;
175
+ if (!flags.preview && (flags.edit || ["sync", "enable", "disable"].includes(action))) requireManagement();
176
+ const feature = path.length > 3 ? path[2] : null;
177
+ if (feature || action === "status") {
178
+ const settings = id === "codex" && (flags.details || feature) ? await request({ path: "settings" }) : null;
179
+ const preference = settings?.providers?.[client.source || "github"]?.preference || {};
180
+ const reviewId = client.auto_review_model || preference.auto_review_model || preference.model || null;
181
+ const reviewModel = modelPlan?.models.find(model => [model.id, model.public_id, model.route_id].includes(reviewId));
182
+ const details = { predictions: snapshot.client_integrations?.prediction || null, images: settings?.effective?.image_enabled || null,
183
+ 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 } };
184
+ if (feature) return print({ client: "Codex", feature, state: details[{ prediction: "predictions", image: "images", review: "auto_review" }[feature]] });
185
+ const observed = retainedRequests(snapshot).filter(row => id === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === id).at(-1);
186
+ 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),
187
+ 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)),
188
+ 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",
189
+ 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" } : {}) });
190
+ }
191
+ if (action === "models" && !flags.edit) {
192
+ if (flags.format === "json") return print(modelPlan);
193
+ 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) })),
194
+ ...(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"]]);
195
+ }
196
+ if (action === "sync") {
197
+ 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,
198
+ current_setup: clientSetup(client), note: "Model/configuration plan only, not a byte-level file diff. Ownership is rechecked on sync; no App is restarted." };
199
+ if (flags.preview) return print(preview);output.write(print(preview) + "\n");await confirm("Write CCDX-owned client settings now?");
200
+ 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" });
201
+ }
202
+ if (["enable", "disable"].includes(action)) {
203
+ const enabled = action === "enable", preview = { client: ids.app, access: enabled ? "Enabled" : "Disabled", retained_source: client.source,
204
+ retained_models: client.deployments || "Legacy source binding retained", note: "Only gateway access changes; the client program stays open." };
205
+ if (flags.preview) return print(preview);output.write(print(preview) + "\n");
206
+ await confirm(enabled ? "Enable gateway access with the saved selection?" : "Disable gateway access? Later turns may fail; saved selections are retained.");
207
+ const result = await save({ operation: "client_state", id, enabled, client_revision: client.revision });
208
+ return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
209
+ }
210
+ const body = clientBody(client);
211
+ if (action === "models") {
212
+ if (flags.file) {
213
+ 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.");
214
+ if (!Array.isArray(file.deployments)) throw new Error("Model files require an explicit deployments array; use [] to pause access.");
215
+ Object.assign(body, file);if (!body.deployments.length) body.default_model = null;
216
+ } else {
217
+ const available = [...(modelPlan?.available || [])], selected = Array.isArray(client.deployments) ? client.deployments : modelPlan?.models.map(model => ({ source: model.source, model: model.id })) || [];
218
+ 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 });
219
+ 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] : []));
220
+ body.deployments = indexes.map(index => ({ source: available[index].source, model: available[index].id }));
221
+ body.default_model = client.default_model || modelPlan?.default_model || null;
222
+ if (body.deployments.length) {
223
+ const defaults = body.deployments.map(item => deploymentModelId(item.source, item.model));
224
+ output.write(body.deployments.map((item, index) => `${index + 1} ${item.source} / ${item.model}`).join("\n") + "\n");
225
+ const value = (await ask(`Default model number [${Math.max(1, defaults.indexOf(body.default_model) + 1)}]: `)).trim();
226
+ if (value && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > defaults.length)) throw new Error("Choose a listed default model number.");
227
+ body.default_model = defaults[value ? Number(value) - 1 : Math.max(0, defaults.indexOf(body.default_model))];
228
+ } else body.default_model = null;
229
+ }
230
+ 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.");
231
+ } else throw new Error("Unsupported client action.");
232
+ const memory = id === "codex" ? client.memory_model?.model : null;
233
+ const memoryModels = [...(modelPlan?.models || []), ...(modelPlan?.available || []), ...(modelPlan?.unavailable || [])].filter(row => [row.id, row.route_id, row.public_id].includes(memory));
234
+ const memoryPairs = new Set(memoryModels.map(row => row.source + "\0" + row.id));
235
+ 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);
236
+ if (memory && (client.deployments || modelPlan?.models || []).some(memoryMatch) && Array.isArray(body.deployments) && !body.deployments.some(memoryMatch)) {
237
+ output.write(`Warning: ${terminalCell(memory)} is an observed memory dependency; memory writing may fail if it is unselected.\n`);
238
+ }
239
+ const checked = await save({ ...body, operation: "preview_client" });
240
+ 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");
241
+ if (flags.preview) return "Preview only; no settings changed.";
242
+ await confirm(body.enabled ? "Save this client selection?" : "Disable gateway access? Later turns may fail; the client program stays open.");
243
+ const result = await save(body);return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
244
+ }
245
+ if (group !== "source") throw new Error("Unknown management command.");
246
+ let graph = await connection();
247
+ if (!flags.preview && (flags.edit || ["add", "edit", "enable", "disable", "remove"].includes(action))) requireManagement();
248
+ 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"]]);
249
+ const id = ids.source, source = id ? getSource(graph, id) : null;
250
+ if (action === "status" || action === "models" && !flags.refresh) {
251
+ if (action === "models" && source.builtin) {
252
+ return print(await save({ operation: "source_catalog", id }));
253
+
254
+ }
255
+ if (action === "models") return print({ source: id, evidence: "Saved API model selection; access not checked", models: source.models });
256
+ const diagnostics = await request({ path: "providers" }), observed = diagnostics.providers.find(provider => provider.id === id);
257
+ 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 },
258
+ 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 });
259
+ }
260
+ if (action === "check" || action === "models" && flags.refresh) {
261
+ if (!source.enabled || id === "m365" && graph.m365_state === "disabled") throw new Error("Source is disabled; it was not enabled automatically.");
262
+ if (action === "check" && id === "github") {
263
+ const checked = await request({ path: "account", body: { action: "check" }, timeoutMs: 60000 });
264
+ if (checked.online?.ok === false) throw Object.assign(new Error(`GitHub access check failed: ${checked.online.reason}`), { code: checked.online.reason });return print(checked);
265
+ }
266
+ return print(source.builtin ? await request({ path: `models/live?provider=${encodeURIComponent(id)}`, timeoutMs: 60000 }) : (await save({ operation: "discover", id })).discovered);
267
+ }
268
+ if (action === "access") {
269
+ const current = graph.clients.filter(client => client.allowed.includes(id)).map(client => client.id);
270
+ 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 || [] });
271
+ 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]; })
272
+ : (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);
273
+ output.write(print({ source: id, before: current, after: allowed, effect: "Revoked routes are removed; added grants do not select models" }) + "\n");
274
+ if (flags.preview) return "Preview only; access unchanged.";await confirm("Save source authorization for these clients?");
275
+ const result = await save({ operation: "source_access", id, allowed, impact_revision: graph.source_impacts[id].revision });
276
+ return print({ source: id, authorized_clients: result.clients.filter(client => client.allowed.includes(id)).map(client => TERMINAL_CLIENT_NAMES[client.id]), saved: true });
277
+ }
278
+ if (["enable", "disable", "remove"].includes(action)) {
279
+ const impact = graph.source_impacts?.[id];
280
+ 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.");
281
+ let replacements;
282
+ if (action === "disable") {
283
+ replacements = flags.replacements ? JSON.parse(flags.replacements) : {};
284
+ if (!replacements || typeof replacements !== "object" || Array.isArray(replacements)) throw new Error("Replacements must be a JSON object.");
285
+ 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]; }));
286
+ for (const client of impact?.clients.filter(client => client.needs_replacement) || []) if (!Object.hasOwn(replacements, client.id)) {
287
+ if (flags.yes && !flags.preview) throw new Error("Provide explicit --replacements JSON for every affected client; null pauses it.");
288
+ if (!flags.preview) {
289
+ const value = (await ask(`${TERMINAL_CLIENT_NAMES[client.id]} replacement source ID (none pauses): `)).trim();
290
+ if (!value) throw new Error("Enter a source ID or none; bindings were kept.");replacements[client.id] = value === "none" ? null : value;
291
+ }
292
+ }
293
+ }
294
+ output.write(print({ source: id, action, affected_clients: impact?.clients || [], replacements }) + "\n");
295
+ if (flags.preview) return "Preview only; sources and bindings unchanged.";await confirm(`Apply source ${action}?`);
296
+ 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 } : {}) });
297
+ return print({ source: id, ...(action === "remove" ? { removed: true } : { saved_enabled: getSource(result, id).enabled }),
298
+ affected_clients: (impact?.clients || []).map(client => ({ name: TERMINAL_CLIENT_NAMES[client.id], setup: getClient(result, client.id).setup })) });
299
+ }
300
+ if (!["add", "edit"].includes(action) || source?.builtin) throw new Error("This action is available for API sources only.");
301
+ let config, allowed, key;
302
+ if (flags.file) {
303
+ 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.");
304
+ config = file.config;allowed = file.allowed || [];
305
+ 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.");
306
+ } else {
307
+ const base = (await ask(`API base URL${source ? ` [${source.base_url}]` : ""}: `)).trim() || source?.base_url;
308
+ const name = (await ask(`Source name${source ? ` [${source.name}]` : ""}: `)).trim() || source?.name;
309
+ const protocols = (await ask(`Interfaces [${Object.keys(source?.endpoints || { responses: 1, messages: 1 }).join(",")}]: `)).trim();
310
+ const enabled = protocols ? protocols.split(",").map(value => value.trim()) : Object.keys(source?.endpoints || { responses: 1, messages: 1 });
311
+ if (!base || !name || enabled.some(value => !["responses", "messages", "chat"].includes(value))) throw new Error("Enter a URL, source name and supported interfaces.");
312
+ const authHeader = (await ask(`API key header [${source?.auth_header || "x-api-key"}] (x-api-key/bearer): `)).trim() || source?.auth_header || "x-api-key";
313
+ config = { ...(source ? apiConfig(source) : { models: [], auth_header: "x-api-key" }), name, base_url: base, auth_header: authHeader,
314
+ endpoints: Object.fromEntries(enabled.map(protocol => [protocol, source?.base_url === base && source.endpoints?.[protocol] || base.replace(/\/+$/, "") + "/" + (protocol === "chat" ? "chat/completions" : protocol)])) };
315
+ 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);
316
+ }
317
+ 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.");
318
+ checkedApi({ ...config, id: source?.id || "api_preview", enabled: true, ...(config.key_env ? {} : { secret_ref: "0".repeat(32) }) });
319
+ if (flags.preview) return print({ config, allowed, note: "Key not read; no source or client settings changed" });
320
+ if (!config.key_env) {
321
+ if (flags.key_stdin) key = await readSecretInput(input);
322
+ else if (flags.file) {
323
+ 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.");
324
+ } 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): ");
325
+ 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.");
326
+ }
327
+ await confirm("Save this API configuration and client authorization?");
328
+ graph = await save({ operation: "save_api", ...(id ? { id, impact_revision: graph.source_impacts[id].revision } : {}), config, allowed, ...(key ? { key } : {}) });key = undefined;
329
+ const saved = id ? getSource(graph, id) : graph.providers.find(row => !row.builtin && row.name === config.name);
330
+ if (!saved) throw new Error("The source was saved but could not be identified. Review source list.");
331
+ 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" });
332
+ let catalog;
333
+ 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); }
334
+ 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" }); }
335
+ 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");
336
+ const selected = picks.map(index => { const { display, ...model } = catalog[index];return model; });
337
+ for (const model of selected) if (!model.protocols.length) {
338
+ const value = (await ask(`Interfaces for ${model.id} (${Object.keys(config.endpoints).join(", ")}): `)).trim();
339
+ model.protocols = value.split(",").map(item => item.trim());
340
+ if (!value || model.protocols.some(api => !config.endpoints[api])) throw new Error("Choose configured interfaces explicitly; source settings were kept.");
341
+ }
342
+ 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 });
343
+ return print({ source: saved.id, selected_models: getSource(result, saved.id).models.length, next: "Choose visible models separately under ccdx app <id> models --edit" });
344
+ }