omp-config-crypt 0.6.3 → 0.6.4

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,308 @@
1
+ import { listProviders, getProvider, saveProvider, removeProvider } from "./provider-store.js";
2
+ import { getRoles } from "./role-manager.js";
3
+ import { probeProvider, inferModelCapabilities } from "./prober.js";
4
+ import { acquireProviderModels, runModelChecks } from "./provider-models.js";
5
+
6
+ const APIS = ["openai-completions", "openai-responses", "anthropic-messages"];
7
+ const DIALOG = { outline: true, helpText: "↑↓ 选择 · Enter 确认 · Esc 返回" };
8
+ const select = (ctx, title, options) => ctx.ui.select(title, options, DIALOG);
9
+ const rolesFor = (name, agentDir) => Object.entries(getRoles(agentDir))
10
+ .filter(([, ref]) => ref.startsWith(`${name}/`)).map(([role]) => role);
11
+
12
+ function validName(name) {
13
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) throw new Error("名称须以字母或数字开头,仅含字母、数字、_、-");
14
+ return name;
15
+ }
16
+ function validUrl(value) {
17
+ const parsed = new URL(value);
18
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) {
19
+ throw new Error("地址仅允许 http/https,不能包含用户名密码");
20
+ }
21
+ if (parsed.search || parsed.hash) throw new Error("Base URL 不能包含查询参数或片段");
22
+ return parsed.href.replace(/\/+$/, "");
23
+ }
24
+ function summary(draft, agentDir) {
25
+ return [draft.name, draft.config.api, draft.config.baseUrl,
26
+ draft.isPrivate ? "PRIVATE · 本地私有" : "PUBLIC · 参与加密同步",
27
+ `模型 (${draft.config.models.length}): ${draft.config.models.map(m => draft.requireVerifiedModels
28
+ ? `${m.id} · ${draft.checks?.get(m.id)?.ok ? `可用 · ${draft.checks.get(m.id).latencyMs} ms` : "未通过验证"}` : m.id).join(", ") || "无"}`,
29
+ `角色: ${rolesFor(draft.name, agentDir).join(", ") || "无"}`,
30
+ `Key: ${draft.config.apiKey ? "已设置" : "未设置"}`,
31
+ draft.requireVerifiedModels ? `已验证 ${draft.config.models.filter(m => draft.checks?.get(m.id)?.ok === true).length}/${draft.config.models.length}`
32
+ : `验证: ${draft.verified ? "已通过生成验证(单模型)" : "未验证"}`].join("\n");
33
+ }
34
+ function fromProvider(provider) {
35
+ const { name, isPrivate, ...config } = provider;
36
+ return { name, isPrivate: Boolean(isPrivate || config.private), config: structuredClone(config), verified: false };
37
+ }
38
+ async function inputField(ctx, title, placeholder, validate) {
39
+ for (;;) {
40
+ const value = await ctx.ui.input(title, placeholder);
41
+ if (value === undefined) return;
42
+ try { return validate(value.trim()); }
43
+ catch (error) { ctx.ui.notify(error.message, "error"); }
44
+ }
45
+ }
46
+ async function chooseApi(ctx) {
47
+ const family = await select(ctx, "PROVIDER // 协议家族", ["OpenAI", "Anthropic"]);
48
+ if (!family) return;
49
+ if (family === "Anthropic") return "anthropic-messages";
50
+ return select(ctx, "OPENAI // 协议", [
51
+ { label: "openai-completions", description: "POST /chat/completions" },
52
+ { label: "openai-responses", description: "POST /responses · Codex 类网关" },
53
+ ]);
54
+ }
55
+ async function chooseScope(ctx) {
56
+ const scope = await select(ctx, "PROVIDER // 存储范围", [
57
+ { label: "PRIVATE", description: "本地私有(默认)" },
58
+ { label: "PUBLIC", description: "配置与 Key 将参与加密同步" },
59
+ ]);
60
+ return scope === undefined ? undefined : scope === "PRIVATE";
61
+ }
62
+ async function verifyDraft(ctx, draft) {
63
+ const models = draft.config.models;
64
+ if (!models.length) { ctx.ui.notify("请先配置实际模型 ID", "error"); return; }
65
+ const id = models.length === 1 ? models[0].id : await select(ctx, "TEST // 选择模型", models.map(m => m.id));
66
+ if (!id) return;
67
+ ctx.ui.notify(`正在验证 ${draft.name} / ${id};将产生一次短生成请求`, "info");
68
+ const result = await probeProvider({ ...draft.config, providerName: draft.name, testModelId: id, verify: true });
69
+ draft.verified = Boolean(result.ok && result.verified);
70
+ ctx.ui.notify((draft.verified ? "连接验证成功(已完成文本生成,单模型)" : `连接验证失败: ${result.error || "未完成生成验证"}`) + ` · ${result.latencyMs ?? 0} ms`, draft.verified ? "info" : "error");
71
+ }
72
+ const checkIdentity = config => JSON.stringify([config.api, config.baseUrl, config.apiKey || ""]);
73
+ async function acquireDraftModels(ctx, draft, agentDir, seedIds = draft.config.models.map(model => model.id)) {
74
+ const acquired = await acquireProviderModels(ctx, { name: draft.name, config: draft.config, agentDir, seedIds });
75
+ if (!acquired) return false;
76
+ draft.config.models = acquired.models;
77
+ draft.config.baseUrl = acquired.baseUrl;
78
+ draft.checks = acquired.checks;
79
+ draft.checkIdentity = checkIdentity(draft.config);
80
+ draft.requireVerifiedModels = true;
81
+ return true;
82
+ }
83
+ async function recheckDraftModels(ctx, draft) {
84
+ // Clear first: cancelled and unstarted IDs must never inherit earlier successes.
85
+ draft.checks = new Map();
86
+ const identity = checkIdentity(draft.config);
87
+ const batch = await runModelChecks(ctx, { name: draft.name, config: draft.config, ids: draft.config.models.map(model => model.id) });
88
+ if (identity !== checkIdentity(draft.config)) return;
89
+ for (const result of batch.results) if (result.ok) draft.checks.set(result.id, { ok: true, latencyMs: result.latencyMs });
90
+ draft.checkIdentity = identity;
91
+ }
92
+ async function saveSummary(ctx, draft, agentDir, isNew) {
93
+ if (!draft.requireVerifiedModels && draft.config.api === "anthropic-messages") draft.config.baseUrl = draft.config.baseUrl.replace(/\/v1$/i, "");
94
+ for (;;) {
95
+ if (draft.requireVerifiedModels && draft.checkIdentity !== checkIdentity(draft.config)) draft.checks = new Map();
96
+ const allVerified = draft.config.models.length > 0 && draft.config.models.every(model => draft.checks?.get(model.id)?.ok === true);
97
+ const options = draft.requireVerifiedModels ? (allVerified
98
+ ? ["重新测试已选模型", "保存配置", "取消"] : ["重新选择模型", "重新测试已选模型", "取消"])
99
+ : ["验证后返回摘要", "保存配置", "取消"];
100
+ const choice = await select(ctx, `SAVE // ${summary(draft, agentDir)}`, options);
101
+ if (!choice || choice === "取消") return false;
102
+ if (choice === "验证后返回摘要") { await verifyDraft(ctx, draft); continue; }
103
+ if (choice === "重新测试已选模型") { await recheckDraftModels(ctx, draft); continue; }
104
+ if (choice === "重新选择模型") { await acquireDraftModels(ctx, draft, agentDir); continue; }
105
+ if (draft.requireVerifiedModels && (!allVerified || draft.checkIdentity !== checkIdentity(draft.config))) {
106
+ ctx.ui.notify("所选模型未通过验证,请重新选择或重新测试", "error"); continue;
107
+ }
108
+ try {
109
+ if (isNew && getProvider(draft.name, { agentDir })) throw new Error("名称已存在,请进入已有项编辑");
110
+ if (!draft.config.models.length) throw new Error("请先配置实际模型 ID");
111
+ saveProvider({ name: draft.name, providerConfig: draft.config, isPrivate: draft.isPrivate, agentDir });
112
+ ctx.ui.notify("已保存,重启 OMP 后加载配置", "info");
113
+ return true;
114
+ } catch (error) { ctx.ui.notify(`保存失败,未完成保存: ${error.message}`, "error"); }
115
+ }
116
+ }
117
+ async function addDraft(ctx, agentDir, seed = {}) {
118
+ const name = await inputField(ctx, "Provider 名称", seed.name || "例如 my-provider", value => {
119
+ validName(value);
120
+ if (getProvider(value, { agentDir })) throw new Error("名称已存在,请进入已有项编辑");
121
+ return value;
122
+ });
123
+ if (name === undefined) return;
124
+ const api = await chooseApi(ctx);
125
+ if (!api) return;
126
+ const baseUrl = await inputField(ctx, "Base URL", seed.baseUrl || "https://api.example.com/v1", validUrl);
127
+ if (!baseUrl) return;
128
+ const apiKey = await ctx.ui.input("API Key", "留空表示无 Key", { secret: true });
129
+ if (apiKey === undefined) return;
130
+ const isPrivate = await chooseScope(ctx);
131
+ if (isPrivate === undefined) return;
132
+ const draft = { name, isPrivate, config: { baseUrl, api, apiKey, models: [] }, verified: false };
133
+ if (!await acquireDraftModels(ctx, draft, agentDir, seed.model ? [seed.model] : [])) return;
134
+ await saveSummary(ctx, draft, agentDir, true);
135
+ }
136
+ async function editDraft(ctx, name, agentDir, supplied) {
137
+ const provider = getProvider(name, { agentDir });
138
+ if (!provider) return ctx.ui.notify(`Provider '${name}' not found`, "warning");
139
+ const draft = supplied || fromProvider(provider);
140
+ for (;;) {
141
+ const field = await select(ctx, `EDIT // ${name}`, ["协议", "地址", "Key", "存储范围", "模型", "保存", "放弃"]);
142
+ if (!field || field === "放弃") return;
143
+ if (field === "协议") {
144
+ const api = await chooseApi(ctx);
145
+ if (api && api !== draft.config.api) {
146
+ draft.config.api = api;
147
+ draft.verified = false;
148
+ draft.checks = new Map();
149
+ }
150
+ } else if (field === "地址") {
151
+ const value = await inputField(ctx, `Base URL // ${draft.config.baseUrl}`, "留空保留现值", value => value ? validUrl(value) : draft.config.baseUrl);
152
+ if (value && value !== draft.config.baseUrl) {
153
+ draft.config.baseUrl = value;
154
+ draft.verified = false;
155
+ draft.checks = new Map();
156
+ }
157
+ } else if (field === "Key") {
158
+ const operation = await select(ctx, "KEY // 凭据", ["保留", "替换", "清除"]);
159
+ if (operation === "替换") {
160
+ const value = await ctx.ui.input("API Key", "留空表示无 Key", { secret: true });
161
+ if (value !== undefined && value !== draft.config.apiKey) {
162
+ draft.config.apiKey = value;
163
+ draft.verified = false;
164
+ draft.checks = new Map();
165
+ }
166
+ } else if (operation === "清除") {
167
+ if (draft.config.apiKey !== "") {
168
+ draft.config.apiKey = "";
169
+ draft.verified = false;
170
+ draft.checks = new Map();
171
+ }
172
+ }
173
+ } else if (field === "存储范围") {
174
+ const scope = await chooseScope(ctx);
175
+ if (scope !== undefined) draft.isPrivate = scope;
176
+ } else if (field === "模型") await acquireDraftModels(ctx, draft, agentDir);
177
+ else if (field === "保存" && await saveSummary(ctx, draft, agentDir, false)) return;
178
+ }
179
+ }
180
+ async function deleteProvider(ctx, name, agentDir) {
181
+ const provider = getProvider(name, { agentDir });
182
+ if (!provider) return ctx.ui.notify(`Provider '${name}' not found`, "warning");
183
+ const roles = rolesFor(name, agentDir);
184
+ if (roles.length) {
185
+ ctx.ui.notify(`${name} 绑定角色: ${roles.join(", ")};请先通过 /role 改绑`, "warning"); return;
186
+ }
187
+ if (await ctx.ui.confirm(`删除 ${name}`, `名称: ${name}\n绑定角色: 无\n确认从两处配置删除?`)) {
188
+ removeProvider({ name, agentDir });
189
+ ctx.ui.notify(`已删除 ${name},重启 OMP 后加载配置`, "info");
190
+ }
191
+ }
192
+
193
+ export async function runProviderMenu(pi, ctx, { agentDir, action, name, draft } = {}) {
194
+ if (!ctx.hasUI) return;
195
+ if (action === "add" || action === "wizard") return addDraft(ctx, agentDir, draft);
196
+ if (action === "edit") return editDraft(ctx, name, agentDir, draft);
197
+ if (action === "test") {
198
+ const provider = getProvider(name, { agentDir });
199
+ return provider ? verifyDraft(ctx, fromProvider(provider)) : ctx.ui.notify(`Provider '${name}' not found`, "warning");
200
+ }
201
+ if (action === "rm" || action === "remove") return deleteProvider(ctx, name, agentDir);
202
+ for (;;) {
203
+ const providers = listProviders({ agentDir });
204
+ const choice = await select(ctx, "PROVIDER // CONTROL", [
205
+ { label: "+ 添加 Provider", description: "协议 / 地址 / Key / 模型" },
206
+ { label: "≡ 管理已有 Provider", description: `${providers.length} 个 Provider` }, "× 退出",
207
+ ]);
208
+ if (!choice || choice === "× 退出") return;
209
+ if (choice === "+ 添加 Provider") { await addDraft(ctx, agentDir); continue; }
210
+ for (;;) {
211
+ const current = listProviders({ agentDir });
212
+ if (!current.length) { ctx.ui.notify("尚未配置 Provider", "info"); break; }
213
+ const chosen = await select(ctx, "PROVIDER // LIST", current.map(p => ({ label: p.name,
214
+ description: `${p.api} · ${p.isPrivate ? "PRIVATE" : "PUBLIC"} · ${p.models.length} models` })));
215
+ if (!chosen) break;
216
+ for (;;) {
217
+ const provider = getProvider(chosen, { agentDir });
218
+ if (!provider) break;
219
+ const operation = await select(ctx, `PROVIDER // ${chosen}`, ["查看详情", "编辑配置", "验证连接", "删除", "返回"]);
220
+ if (!operation || operation === "返回") break;
221
+ if (operation === "查看详情") ctx.ui.notify(summary(fromProvider(provider), agentDir), "info");
222
+ if (operation === "编辑配置") await editDraft(ctx, chosen, agentDir);
223
+ if (operation === "验证连接") await verifyDraft(ctx, fromProvider(provider));
224
+ if (operation === "删除") { await deleteProvider(ctx, chosen, agentDir); if (!getProvider(chosen, { agentDir })) break; }
225
+ }
226
+ }
227
+ }
228
+ }
229
+
230
+ const ADD_USAGE = "Usage: /provider add <name> <url> [key] [--api <openai-completions|openai-responses|anthropic-messages>] [--model <id>] [--private|--public]";
231
+ function parseAdd(tokens) {
232
+ const positional = []; const options = { isPrivate: true, api: "openai-completions" };
233
+ for (let i = 0; i < tokens.length; i++) {
234
+ const token = tokens[i];
235
+ if (token === "--private" || token === "--public") options.isPrivate = token === "--private";
236
+ else if (token === "--api" || token === "--model") {
237
+ const value = tokens[++i];
238
+ if (!value || value.startsWith("--")) throw new Error(ADD_USAGE);
239
+ options[token.slice(2)] = value;
240
+ } else if (token.startsWith("--")) throw new Error(ADD_USAGE);
241
+ else positional.push(token);
242
+ }
243
+ if (positional.length > 3) throw new Error(ADD_USAGE);
244
+ return { ...options, name: positional[0], baseUrl: positional[1], apiKey: positional[2] || "" };
245
+ }
246
+ export function providerCompletions(prefix = "", agentDir) {
247
+ const parts = prefix.split(/\s+/); const sub = parts[0].toLowerCase();
248
+ if (parts.length === 1) return ["add", "wizard", "ls", "list", "edit", "test", "rm", "remove"]
249
+ .filter(value => value.startsWith(sub)).map(value => ({ value, description: "Provider configuration" }));
250
+ if (["edit", "test", "rm", "remove"].includes(sub) && parts.length === 2) {
251
+ try { return listProviders({ agentDir }).filter(p => p.name.toLowerCase().startsWith(parts[1].toLowerCase()))
252
+ .map(p => ({ value: prefix.slice(0, prefix.length - parts[1].length) + p.name, label: p.name, description: `${p.api} · ${p.isPrivate ? "PRIVATE" : "PUBLIC"}` })); }
253
+ catch { return null; }
254
+ }
255
+ if (["add", "wizard"].includes(sub)) {
256
+ const last = parts.at(-1);
257
+ const values = parts.at(-2) === "--api" ? APIS : ["--api", "--model", "--private", "--public"];
258
+ return values.filter(value => value.startsWith(last)).map(value => ({ value: prefix.slice(0, prefix.length - last.length) + value, label: value, description: "Provider option" }));
259
+ }
260
+ return null;
261
+ }
262
+ export async function handleProviderCommand(pi, ctx, args, agentDir) {
263
+ try {
264
+ const tokens = (args || "").trim().split(/\s+/).filter(Boolean);
265
+ if (!tokens.length && ctx.hasUI) return await runProviderMenu(pi, ctx, { agentDir });
266
+ const [sub = "ls", name] = tokens;
267
+ if (sub === "ls" || sub === "list") {
268
+ const providers = listProviders({ agentDir });
269
+ ctx.ui.notify(providers.length ? `Providers:\n${providers.map(p => `${p.name} · ${p.api} · ${p.isPrivate ? "PRIVATE" : "PUBLIC"} · ${p.models.length} models [roles: ${rolesFor(p.name, agentDir).join(", ") || "none"}]`).join("\n")}` : "No providers configured in public or private stores.", "info");
270
+ return;
271
+ }
272
+ if (["edit", "test", "rm", "remove"].includes(sub)) {
273
+ if (!name || tokens.length !== 2) throw new Error(`Usage: /provider ${sub} <name>`);
274
+ if (ctx.hasUI) return await runProviderMenu(pi, ctx, { agentDir, action: sub, name });
275
+ if (sub === "edit" || sub === "test") throw new Error(`Usage: /provider ${sub} <name> (requires interactive UI)`);
276
+ const roles = rolesFor(name, agentDir);
277
+ if (roles.length) {
278
+ ctx.ui.notify(`Provider '${name}' 绑定角色: ${roles.join(", ")};请先通过 /role 改绑`, "warning");
279
+ return;
280
+ }
281
+ ctx.ui.notify(removeProvider({ name, agentDir }) ? `Removed provider '${name}'` : `Provider '${name}' not found`, "info"); return;
282
+ }
283
+ if (sub === "add" || sub === "wizard") {
284
+ const options = parseAdd(tokens.slice(1));
285
+ if (ctx.hasUI && (!options.name || !options.baseUrl)) return await runProviderMenu(pi, ctx, { agentDir, action: "add", draft: options });
286
+ if (!options.name || !options.baseUrl) throw new Error(ADD_USAGE);
287
+ validName(options.name); options.baseUrl = validUrl(options.baseUrl);
288
+ if (!APIS.includes(options.api)) throw new Error("Unknown API: " + options.api);
289
+ if (options.api === "anthropic-messages") options.baseUrl = options.baseUrl.replace(/\/v1$/i, "");
290
+ if (getProvider(options.name, { agentDir })) throw new Error("名称已存在,请进入已有项编辑");
291
+ if (ctx.hasUI) {
292
+ const draft = { name: options.name, isPrivate: options.isPrivate, verified: false,
293
+ config: { api: options.api, baseUrl: options.baseUrl, apiKey: options.apiKey, models: [] } };
294
+ if (!await acquireDraftModels(ctx, draft, agentDir, options.model ? [options.model] : [])) return;
295
+ await saveSummary(ctx, draft, agentDir, true);
296
+ return;
297
+ }
298
+ const result = await probeProvider({ ...options, testModelId: options.model, providerName: options.name });
299
+ if (!result.ok && !options.model) throw new Error(result.error);
300
+ const models = result.ok ? result.models : [inferModelCapabilities(options.model, options.name)];
301
+ if (options.model && !models.some(model => model.id === options.model)) models.push(inferModelCapabilities(options.model, options.name));
302
+ saveProvider({ name: options.name, providerConfig: { baseUrl: result.ok ? result.normalizedBaseUrl : options.baseUrl,
303
+ api: options.api, apiKey: options.apiKey, models }, isPrivate: options.isPrivate, agentDir });
304
+ ctx.ui.notify("已保存(未验证),重启 OMP 后加载配置", "info"); return;
305
+ }
306
+ throw new Error("Usage: /provider [ls|add|edit <name>|test <name>|rm <name>]");
307
+ } catch (error) { ctx.ui.notify(`Provider command error: ${error.message}`, "error"); }
308
+ }
@@ -0,0 +1,223 @@
1
+ import { probeProvider, filterChatModels, inferModelCapabilities } from "./prober.js";
2
+ import { listProviders } from "./provider-store.js";
3
+
4
+ const POPULAR = {
5
+ "openai-completions": ["gpt-4.1-mini", "gpt-4o-mini", "gpt-5.4", "deepseek-v4-flash", "deepseek-v4-pro", "gemini-2.5-flash", "kimi-k2.5", "glm-5"],
6
+ "openai-responses": ["gpt-6.1-sol", "gpt-6.1-terra", "gpt-5.4", "gpt-5.4-mini", "gpt-5.3-codex", "gpt-4.1-mini"],
7
+ "anthropic-messages": ["claude-sonnet-4-6", "claude-opus-4-7", "claude-haiku-4-5"],
8
+ };
9
+ const unique = ids => [...new Set(ids.filter(id => typeof id === "string").map(id => id.trim()).filter(Boolean))];
10
+ const sorted = ids => unique(ids).sort((a, b) => a.localeCompare(b, "en", { numeric: true }));
11
+ function address(value, api) {
12
+ try {
13
+ if (typeof value !== "string") return;
14
+ const url = new URL(value.trim());
15
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) return;
16
+ let normalized = url.href.replace(/\/+$/, "");
17
+ if (api === "anthropic-messages") normalized = normalized.replace(/\/v1$/i, "");
18
+ return { normalized, hostname: url.hostname.toLowerCase() };
19
+ } catch { return; }
20
+ }
21
+
22
+ /** Local hints only. Availability is established exclusively by target generation requests. */
23
+ export function recommendModelIds({ api, baseUrl, name = "", configuredProviders = [], catalog = [] }) {
24
+ const target = address(baseUrl, api);
25
+ const groups = [[], [], []];
26
+ if (target) {
27
+ for (const provider of configuredProviders) {
28
+ if (provider?.api !== api || address(provider.baseUrl, api)?.normalized !== target.normalized) continue;
29
+ groups[0].push(...filterChatModels(Array.isArray(provider.models) ? provider.models : []).map(m => typeof m === "string" ? m : m.id));
30
+ }
31
+ for (const model of catalog) {
32
+ if (!model || model.api !== api || (model.kind && model.kind !== "chat") ||
33
+ (model.input !== undefined && (!Array.isArray(model.input) || !model.input.includes("text")))) continue;
34
+ const id = model.requestModelId || model.id;
35
+ if (typeof id !== "string" || !filterChatModels([id]).length) continue;
36
+ const url = address(model.baseUrl, api);
37
+ if (!url) continue;
38
+ if (url.hostname === target.hostname) groups[1].push(id);
39
+ const provider = typeof model.provider === "string" ? model.provider.toLowerCase() : "";
40
+ if (provider && (provider === name.toLowerCase() || target.hostname.split(".").includes(provider))) groups[2].push(id);
41
+ }
42
+ }
43
+ return { intelligent: unique(groups.flatMap(sorted)).slice(0, 12), popular: [...(POPULAR[api] || [])] };
44
+ }
45
+
46
+ /** Two workers, stable output order, no retries, and no invented unstarted results. */
47
+ export async function testModelCandidates({ name, config, ids, signal, onResult }) {
48
+ const candidates = unique(ids), results = new Array(candidates.length);
49
+ let cursor = 0;
50
+ const worker = async () => {
51
+ while (!signal?.aborted && cursor < candidates.length) {
52
+ const index = cursor++, id = candidates[index];
53
+ const probe = await probeProvider({ ...config, providerName: name, testModelId: id, verify: true, timeout: 10000, signal });
54
+ const result = { id, ok: probe.ok && probe.verified === true, latencyMs: probe.latencyMs ?? 0,
55
+ ...(!probe.ok || probe.verified !== true ? { error: probe.error || "Generation not verified" } : {}) };
56
+ results[index] = result;
57
+ onResult?.(result);
58
+ }
59
+ };
60
+ await Promise.all([worker(), worker()]);
61
+ return { results: results.filter(Boolean), cancelled: Boolean(signal?.aborted) };
62
+ }
63
+
64
+ async function withProgress(ctx, { title, run, onProgress }) {
65
+ const batch = new AbortController(), dialog = new AbortController();
66
+ let completed = false, dialogError;
67
+ ctx.ui.setWidget("provider-model-check", [title]);
68
+ const selection = Promise.resolve().then(() => ctx.ui.select(title, ["取消测试"], {
69
+ signal: dialog.signal, outline: true, helpText: "Esc 取消",
70
+ })).then(() => { if (!completed) batch.abort(); }, error => {
71
+ if (!completed) { dialogError = error; batch.abort(); }
72
+ });
73
+ try {
74
+ const result = await run(batch.signal, lines => {
75
+ ctx.ui.setWidget("provider-model-check", lines);
76
+ onProgress?.(lines);
77
+ });
78
+ if (dialogError) throw dialogError;
79
+ return result;
80
+ } finally {
81
+ completed = true;
82
+ dialog.abort();
83
+ await selection;
84
+ ctx.ui.setWidget("provider-model-check", undefined);
85
+ }
86
+ }
87
+
88
+ export async function runModelChecks(ctx, { name, config, ids }) {
89
+ const candidates = unique(ids);
90
+ ctx.ui.notify(`将测试 ${candidates.length} 个候选,最多同时 2 个短生成请求,可能产生费用;Esc 可取消`, "info");
91
+ let completed = 0;
92
+ return withProgress(ctx, { title: `测试模型 0/${candidates.length}`, run: (signal, update) =>
93
+ testModelCandidates({ name, config, ids: candidates, signal, onResult: result => {
94
+ completed++;
95
+ update([`测试模型 ${completed}/${candidates.length}`, `${result.id} · ${result.ok ? "可用" : result.error} · ${result.latencyMs} ms`]);
96
+ } }) });
97
+ }
98
+
99
+ const SOURCE_NAMES = ["接口", "智能", "主流", "手动"];
100
+ const dialogSelect = (ctx, title, options) => ctx.ui.select(title, options, { outline: true, helpText: "↑↓ 选择 · Enter 确认 · Esc 返回" });
101
+ const parseIds = value => unique(value.split(/[,\n\r]+/));
102
+
103
+ async function showFailures(ctx, cache) {
104
+ const failed = [...cache.values()].filter(result => !result.ok);
105
+ let page = 0;
106
+ for (;;) {
107
+ const rows = failed.slice(page * 10, page * 10 + 10).map(result =>
108
+ `${result.id} · ${result.error} · ${result.latencyMs} ms`);
109
+ const choice = await dialogSelect(ctx, `失败详情 · ${page + 1}/${Math.ceil(failed.length / 10)}`, [
110
+ ...rows, ...(page ? ["上一页"] : []), ...((page + 1) * 10 < failed.length ? ["下一页"] : []), "返回",
111
+ ]);
112
+ if (!choice || choice === "返回") return;
113
+ if (choice === "上一页") page--;
114
+ if (choice === "下一页") page++;
115
+ }
116
+ }
117
+
118
+ /** Acquire a verified subset without mutating config, the registry, or either store. */
119
+ export async function acquireProviderModels(ctx, { name, config, agentDir, seedIds = [] }) {
120
+ if (typeof ctx.ui.askDialog !== "function") {
121
+ ctx.ui.notify("当前宿主不支持空格多选,请升级 OMP", "error");
122
+ return;
123
+ }
124
+ const working = { ...config }, existing = new Map((config.models || []).map(model => [model.id, model]));
125
+ if (working.api === "anthropic-messages") working.baseUrl = working.baseUrl.trim().replace(/\/+$/, "").replace(/\/v1$/i, "");
126
+ let configuredProviders;
127
+ try { configuredProviders = listProviders({ agentDir }); }
128
+ catch (error) { ctx.ui.notify(`模型配置读取失败: ${error.message}`, "error"); return; }
129
+ let catalog = [];
130
+ try {
131
+ if (typeof ctx.modelRegistry?.getAll !== "function") throw new Error("Registry unavailable");
132
+ catalog = ctx.modelRegistry.getAll("chat");
133
+ if (!Array.isArray(catalog)) throw new Error("Invalid registry");
134
+ } catch { catalog = []; ctx.ui.notify("本机模型目录不可用", "warning"); }
135
+ const cache = new Map(), sources = new Map(), stageIds = [[], [], [], []];
136
+ let stage = 0, mode = "stage", retry = false;
137
+ const available = () => [...sources.keys()].filter(id => cache.get(id)?.ok);
138
+ const check = async (ids, source) => {
139
+ ids = unique(ids);
140
+ for (const id of ids) if (!sources.has(id)) sources.set(id, SOURCE_NAMES[source]);
141
+ const pending = ids.filter(id => !cache.has(id));
142
+ if (pending.length) {
143
+ const batch = await runModelChecks(ctx, { name, config: working, ids: pending });
144
+ for (const result of batch.results) cache.set(result.id, result);
145
+ if (batch.cancelled) return false;
146
+ }
147
+ return true;
148
+ };
149
+ const manual = async () => {
150
+ for (;;) {
151
+ const value = await ctx.ui.input("模型 ID(逗号或换行分隔)", "输入实际模型 ID");
152
+ if (value === undefined) return;
153
+ const ids = parseIds(value);
154
+ if (ids.length) return ids;
155
+ ctx.ui.notify("至少输入一个实际模型 ID", "error");
156
+ }
157
+ };
158
+ for (;;) {
159
+ if (mode === "stage") {
160
+ const before = new Set(available());
161
+ let ids;
162
+ if (stage === 0) {
163
+ const result = await withProgress(ctx, { title: "查询模型接口", run: signal =>
164
+ probeProvider({ ...working, providerName: name, verify: false, signal }) });
165
+ if (result.cancelled) return;
166
+ if (result.ok) working.baseUrl = result.normalizedBaseUrl;
167
+ else ctx.ui.notify(`模型接口不可用: ${result.error}`, "warning");
168
+ ids = unique([...seedIds, ...(result.ok ? result.models.map(model => model.id) : []), ...(retry ? stageIds[0] : [])]);
169
+ } else if (stage < 3) {
170
+ ids = retry ? stageIds[stage].filter(id => !cache.get(id)?.ok) :
171
+ recommendModelIds({ ...working, name, configuredProviders, catalog })[stage === 1 ? "intelligent" : "popular"];
172
+ } else {
173
+ ids = await manual();
174
+ if (!ids) { mode = "menu"; continue; }
175
+ }
176
+ stageIds[stage] = unique([...stageIds[stage], ...ids]);
177
+ if (retry) for (const id of ids) if (!cache.get(id)?.ok) cache.delete(id);
178
+ retry = false;
179
+ if (!await check(ids, stage)) return;
180
+ if (ids.some(id => cache.get(id)?.ok && !before.has(id))) { mode = "select"; continue; }
181
+ ctx.ui.notify(stage === 3 ? "没有可用模型,不能保存" : `${SOURCE_NAMES[stage]}候选没有可用模型`, "warning");
182
+ if (stage < 3) { stage++; continue; }
183
+ mode = "menu";
184
+ }
185
+ if (mode === "select") {
186
+ const labels = new Map(available().map(id => [id, id]));
187
+ const result = await ctx.ui.askDialog([{
188
+ id: "provider-models", header: "MODELS", question: "选择已验证模型 · 空格勾选 · Enter 确认 · Esc 返回", multi: true,
189
+ options: [...labels.keys()].map(id => ({ label: id,
190
+ description: `可用 · ${cache.get(id).latencyMs} ms · 来源: ${sources.get(id)}` })),
191
+ }]);
192
+ if (!result || result.kind !== "submit") { mode = "menu"; continue; }
193
+ const answer = result.results?.find(item => item.id === "provider-models");
194
+ if (typeof answer?.customInput === "string" && answer.customInput.trim()) {
195
+ const ids = parseIds(answer.customInput);
196
+ stageIds[3] = unique([...stageIds[3], ...ids]);
197
+ if (!await check(ids, 3)) return;
198
+ ctx.ui.notify("新增候选已测试,请重新勾选需保存的模型", "info");
199
+ continue;
200
+ }
201
+ const selected = answer?.selectedOptions;
202
+ if (!Array.isArray(selected) || selected.some(label => !labels.has(label))) {
203
+ ctx.ui.notify("所选模型未通过验证", "error"); continue;
204
+ }
205
+ if (!selected.length) { ctx.ui.notify("至少选择一个已验证模型", "error"); continue; }
206
+ const ids = unique(selected.map(label => labels.get(label)));
207
+ return { models: ids.map(id => existing.get(id) || inferModelCapabilities(id, name)), baseUrl: working.baseUrl,
208
+ checks: new Map(ids.map(id => [id, { ok: true, latencyMs: cache.get(id).latencyMs }])) };
209
+ }
210
+ if (mode === "menu") {
211
+ const choice = await dialogSelect(ctx, `MODELS // ${SOURCE_NAMES[stage]}`, [
212
+ ...(available().length ? ["多选可用模型"] : []), ...(stage < 3 ? ["继续下一来源"] : []),
213
+ "手动输入模型 ID", ...([...cache.values()].some(result => !result.ok) ? ["查看失败详情"] : []), "重试本阶段", "返回",
214
+ ]);
215
+ if (!choice || choice === "返回") return;
216
+ if (choice === "多选可用模型") mode = "select";
217
+ else if (choice === "查看失败详情") await showFailures(ctx, cache);
218
+ else if (choice === "继续下一来源") { stage++; mode = "stage"; }
219
+ else if (choice === "手动输入模型 ID") { stage = 3; mode = "stage"; }
220
+ else if (choice === "重试本阶段") { retry = true; mode = "stage"; }
221
+ }
222
+ }
223
+ }