dsh-mo-image 0.6.0 → 1.0.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.
@@ -0,0 +1,1628 @@
1
+ /**
2
+ * 配置域:归一化、按 mtime 的读写缓存、凭据解析、当前模型快照与任务级配置快照。
3
+ *
4
+ * 从 lib/index.js 拆出来后,配置读写和工具/路由注册分开;这个模块只依赖
5
+ * adapters 的纯函数与 status 的模型能力判断,不 import index,避免循环依赖。
6
+ */
7
+ import { readFileSync, statSync } from 'node:fs';
8
+ import { readFile, stat, writeFile, rename, unlink } from 'node:fs/promises';
9
+ import { randomUUID } from 'node:crypto';
10
+ import { isIP } from 'node:net';
11
+
12
+ import {
13
+ resolveAdapter, parseSize, sizePolicyFor, sizeSpecFor, nearestTier, nearestAspect, sizeForAspect,
14
+ qualityForAdapter, qualityOptionsFor, operationFieldsFor, A1111_PARAMS, SIZE_CONTROLS, adapterTakesParamRows,
15
+ upgradeLegacyProtocol, normalizeProtocolOptions, concreteProtocolId, presetProtocolOf, PROVIDER_PRESETS, LOCAL_PRESETS
16
+ } from './adapters.js';
17
+ import { normalizeAuthSpec, resolveHttpUrl } from './adapter-kit.js';
18
+ import { normalizeOperations, normalizeResponseOverrides } from './provider-operations.js';
19
+ import { MAPPING_KEYS, PROMPT_ROLE_NAMES } from './comfy-workflow.js';
20
+ import { applyFields } from './field-templates.js';
21
+ import { GEMINI_25_IMAGE } from './model-rules.js';
22
+ import { buildImageStatus, editCapableModels, normalizeKeySource } from './status.js';
23
+ import { localizedError } from './localized-error.js';
24
+
25
+ export function emptyConfig() {
26
+ return {
27
+ version: 1, providers: [], active: { providerId: '', model: '' },
28
+ defaults: { quality: 'high', auto: true, width: 1024, height: 1024, promptOptimization: true }
29
+ };
30
+ }
31
+ /** 质量值由适配器的 options 决定;这里只保留旧配置里的合法字符串,具体对齐交给 adapter。 */
32
+ const QUALITY_VALUES = new Set(['off', 'low', 'medium', 'high', 'xhigh', 'max', 'auto', 'standard', 'hd', 'default', 'quality', 'turbo']);
33
+ export function normalizeQuality(value) {
34
+ const raw = String(value || '').trim().toLowerCase();
35
+ // 档位不再锁死在白名单里:模型选项支持自定义档位,合法性在发送时按解析出的 options 判断。
36
+ if (!raw) return 'high';
37
+ if (!/^[a-z0-9][a-z0-9._-]{0,31}$/.test(raw)) return 'high';
38
+ return raw;
39
+ }
40
+ export function normalizeDefaults(raw) {
41
+ const source = raw && typeof raw === 'object' ? raw : {};
42
+ const side = (value, fallback) => {
43
+ const number = Number(value);
44
+ if (!Number.isFinite(number) || number <= 0) return fallback;
45
+ return Math.min(4096, Math.max(64, Math.round(number)));
46
+ };
47
+ let width = side(source.width, 0);
48
+ let height = side(source.height, 0);
49
+ if (!width || !height) {
50
+ // 兼容上一版的 { size: "1024x1024" }
51
+ const legacy = /^(\d{2,5})x(\d{2,5})$/.exec(String(source.size || '').trim().toLowerCase().replace(/[×*]/g, 'x'));
52
+ if (legacy) { width = side(legacy[1], 1024); height = side(legacy[2], 1024); }
53
+ }
54
+ const finalWidth = width || 1024;
55
+ const finalHeight = height || 1024;
56
+ return {
57
+ quality: normalizeQuality(source.quality),
58
+ auto: source.auto === undefined ? true : !!source.auto,
59
+ width: finalWidth,
60
+ height: finalHeight,
61
+ // 比例/档位/白名单值:与 width/height 并存,谁生效由适配器的 control 决定。
62
+ // 档位在这里只做字符串清洗(要按模型就近取档得有 adapter,那是 resolveSizeRequest 的事)。
63
+ aspect: String(source.aspect || '').trim() || nearestAspect(finalWidth, finalHeight),
64
+ tier: String(source.tier || '').trim(),
65
+ preset: String(source.preset || '').trim() || (finalWidth + 'x' + finalHeight),
66
+ strict: !!source.strict,
67
+ promptOptimization: source.promptOptimization === undefined ? true : !!source.promptOptimization
68
+ };
69
+ }
70
+ /** 选择器上的质量模式。只有 Auto 允许工具挑选当前模型支持的档位。 */
71
+ export function resolveQuality(defaults) {
72
+ return normalizeQuality(defaults && defaults.quality);
73
+ }
74
+
75
+ export function imageSettingsMismatch(message) {
76
+ const error = new Error('生图配置不匹配(未提交):' + message
77
+ + '。先用 mo_image_settings({"refresh":true}) 获取完整配置,纠正参数后只重试一次。');
78
+ error.code = 'image_settings_mismatch';
79
+ return error;
80
+ }
81
+
82
+ export function resolveToolQuality(provider, model, defaults, args, adapter) {
83
+ const selected = resolveQuality(defaults);
84
+ const wanted = String(args?.quality || '').trim().toLowerCase();
85
+ const spec = qualityOptionsFor(provider, model, adapter);
86
+ if (!spec) return undefined;
87
+ if (selected !== 'auto') return qualityForAdapter(provider, model, selected, adapter);
88
+ if (!wanted || wanted === 'auto') return undefined;
89
+ const options = spec.options.map((item) => item.value).filter((value) => value !== 'auto');
90
+ if (options.includes(wanted)) return wanted;
91
+ throw imageSettingsMismatch('当前模型不支持质量档位 ' + wanted.slice(0, 32) + '。可选:' + options.join(' / '));
92
+ }
93
+ export function resolveSizeArg(defaults) {
94
+ if (defaults && defaults.auto === false) return (defaults.width || 1024) + 'x' + (defaults.height || 1024);
95
+ return 'none';
96
+ }
97
+ /**
98
+ * 尺寸请求:控件的形态决定用户的选择怎么变成一次具体的请求。
99
+ *
100
+ * - wh / prompt:两个宽高输入框直接拼 WxH;
101
+ * - aspect:比例 + 档位合成像素(16:9 + 1K → 1368×768),编码器另外发比例与档位;
102
+ * - preset:档位名原样发("2K"),custom 时允许直接写 WxH。
103
+ *
104
+ * 自动尺寸下一切交给对话模型:它传了 size 就用它,没传就不带尺寸。
105
+ * @returns {{arg:string, nominal:{width:number,height:number}|null, control:string, aspect:string, tier:string, note:string, stitch:boolean}}
106
+ */
107
+ export function resolveSizeRequest(provider, model, defaults, args, adapter) {
108
+ const policy = sizePolicyFor(provider, model, adapter);
109
+ const allowed = Array.isArray(policy.allowed) ? policy.allowed.filter(Boolean) : [];
110
+ const control = String(policy.control
111
+ || (allowed.length ? 'preset' : (policy.style === 'aspect' ? 'aspect' : 'wh')));
112
+ const auto = !(defaults && defaults.auto === false);
113
+ const asked = String((args && args.size) || '').trim();
114
+ const out = {
115
+ arg: 'none', nominal: null, control: control,
116
+ aspect: '', tier: '', note: '', stitch: policy.stitch === true
117
+ };
118
+
119
+ if (auto) {
120
+ if (!asked) return out;
121
+ if (/^[1-9]\d{0,3}:[1-9]\d{0,3}$/.test(asked)) {
122
+ const firstTier = policy.tiers?.find((item) => Number(item?.pixels) > 0);
123
+ const { width, height } = sizeForAspect(asked, firstTier?.pixels || 1024 * 1024);
124
+ out.arg = width + 'x' + height;
125
+ if (policy.aspects?.includes(asked)) out.aspect = asked;
126
+ return out;
127
+ }
128
+ out.arg = asked;
129
+ const parsed = parseSize(asked);
130
+ if (parsed) out.nominal = { width: parsed.width, height: parsed.height };
131
+ return out;
132
+ }
133
+
134
+ const width = Number(defaults && defaults.width) || 1024;
135
+ const height = Number(defaults && defaults.height) || 1024;
136
+
137
+ if (control === 'aspect') {
138
+ const aspects = Array.isArray(policy.aspects) && policy.aspects.length ? policy.aspects : ['1:1'];
139
+ const wantedAspect = String((defaults && defaults.aspect) || '');
140
+ const aspect = aspects.includes(wantedAspect) ? wantedAspect : nearestAspect(width, height, aspects);
141
+ const tiers = Array.isArray(policy.tiers) ? policy.tiers : [];
142
+ const wantedTier = String((defaults && defaults.tier) || '');
143
+ const tier = tiers.find((item) => String(item && item.value) === wantedTier)
144
+ || (tiers.length ? nearestTier(tiers, width * height) : null);
145
+ if (wantedTier && tier && String(tier.value) !== wantedTier) {
146
+ out.note = '档位 ' + wantedTier + ' 不在当前模型的合法档位里,已改用 ' + tier.value;
147
+ }
148
+ const budget = tier ? Number(tier.pixels) : 1024 * 1024;
149
+ const size = sizeForAspect(aspect, budget);
150
+ out.arg = size.width + 'x' + size.height;
151
+ out.nominal = size;
152
+ out.aspect = aspect;
153
+ out.tier = tier ? String(tier.value) : '';
154
+ return out;
155
+ }
156
+
157
+ if (control === 'preset') {
158
+ const tiers = Array.isArray(policy.tiers) ? policy.tiers : [];
159
+ const candidates = tiers.length ? tiers.map((item) => String(item && item.value)) : allowed;
160
+ const custom = policy.custom === true;
161
+ const wanted = String((defaults && defaults.preset) || '')
162
+ || (width + 'x' + height);
163
+ let value = candidates.includes(wanted) ? wanted : '';
164
+ if (!value && custom && parseSize(wanted)) value = wanted;
165
+ if (!value) {
166
+ const tier = tiers.length ? nearestTier(tiers, width * height) : null;
167
+ value = tier ? String(tier.value) : (candidates[0] || (width + 'x' + height));
168
+ if (wanted && wanted !== value) {
169
+ out.note = '尺寸 ' + wanted + ' 不在当前模型的可选范围里,已改用 ' + value;
170
+ }
171
+ }
172
+ out.arg = value;
173
+ const tier = tiers.find((item) => String(item && item.value) === value);
174
+ if (tier) {
175
+ out.tier = value;
176
+ const side = Math.round(Math.sqrt(Number(tier.pixels))) || 0;
177
+ if (side) out.nominal = { width: side, height: side };
178
+ } else {
179
+ const parsed = parseSize(value);
180
+ if (parsed) out.nominal = { width: parsed.width, height: parsed.height };
181
+ }
182
+ return out;
183
+ }
184
+
185
+ out.arg = width + 'x' + height;
186
+ out.nominal = { width: width, height: height };
187
+ if (asked) out.note = '尺寸已由选择器固定为 ' + out.arg + ',已忽略 size:' + asked;
188
+ return out;
189
+ }
190
+ /** 每个模型的可选配置(目前只有自定义工作流),只保留仍存在的模型,限制体积。 */
191
+ const MODEL_WORKFLOW_MAX = 2000000;
192
+ /**
193
+ * 映射要么完整,要么没有:任何一项形状不对就整体丢弃,
194
+ * 免得生成时一半注入一半不注入,产出用户看不懂的图。
195
+ */
196
+ function sanitizeMapping(raw) {
197
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
198
+ const out = {};
199
+ for (const key of MAPPING_KEYS) {
200
+ if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
201
+ const value = raw[key];
202
+ if (value === null) { out[key] = null; continue; }
203
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
204
+ const node = typeof value.node === 'string' ? value.node.trim() : '';
205
+ const input = typeof value.input === 'string' ? value.input.trim() : '';
206
+ if (!node || !input) return undefined;
207
+ out[key] = { node, input };
208
+ }
209
+ return Object.keys(out).length ? out : undefined;
210
+ }
211
+
212
+ /* ── 一张参数表,两种绑定 ──────────────────────────────────────────────
213
+ *
214
+ * 行有两种绑定,**只看形状**区分(没有顶层判别键,也不新增键):
215
+ *
216
+ * 工作流行 { node, input, type, default?, description?, expose?, options?, role?, name?, locked? }
217
+ * `node` + `input` 指向工作流里哪个节点的哪个输入(ComfyUI);
218
+ * `name` 是给对话模型用的参数键,省略时等于 `input`。
219
+ * HTTP 行 { name, type, default?, description?, expose?, options?, role?, locked? }
220
+ * `name` 是请求体里的路径(A1111 的 sdapi 字段名也走这条)。
221
+ *
222
+ * `locked: true` 是行级锁:一键配置/自动检测不会改写这一行(不写 = 未锁)。
223
+ *
224
+ * 两张表共用同一个数组(`modelOptions[m].params`),所以 `sanitizeParams` 逐行分派:
225
+ * 有节点落点的按工作流行校验,其余按参数表校验。坏行逐条丢掉——宁可少一行,
226
+ * 也不要留一条默认值/落点说不清的行。
227
+ *
228
+ * 类型词表也统一成四个值(text / number / boolean / enum)。老的 ComfyUI 配置里
229
+ * 写的 INT / FLOAT / STRING 在这里折过来,读一次就完成迁移。
230
+ */
231
+
232
+ /** 内置四行的 role(只有这四行跟 fields 里的逻辑字段对应)。 */
233
+ const PARAM_ROLES = ['prompt', 'negative', 'model', 'n'];
234
+ /** 老工作流参数的类型词表:读进来折成参数表的四个值(text / number / boolean / enum)。 */
235
+ const LEGACY_PARAM_TYPES = {
236
+ int: 'number', integer: 'number', float: 'number', double: 'number', number: 'number',
237
+ string: 'text', str: 'text', text: 'text',
238
+ bool: 'boolean', boolean: 'boolean',
239
+ enum: 'enum', json: 'json'
240
+ };
241
+ const PARAM_ROWS_MAX = 64;
242
+ const PARAM_NAME_MAX = 64;
243
+ const PARAM_DEFAULT_MAX = 120;
244
+ const PARAM_DESCRIPTION_MAX = 200;
245
+ const PARAM_OPTION_MAX = 40;
246
+ const PARAM_OPTIONS_MAX = 64;
247
+
248
+ /** 这一项是不是工作流行(有节点落点)。 */
249
+ function isWorkflowParamShape(item) {
250
+ return Boolean(item) && typeof item === 'object' && !Array.isArray(item)
251
+ && (Object.prototype.hasOwnProperty.call(item, 'node')
252
+ || Object.prototype.hasOwnProperty.call(item, 'input')
253
+ || Object.prototype.hasOwnProperty.call(item, 'candidates'));
254
+ }
255
+
256
+ /** 选项:数组或逗号分隔的字符串都收;去空、去重、限长限量。 */
257
+ function sanitizeParamOptions(raw) {
258
+ let list = [];
259
+ if (Array.isArray(raw)) list = raw;
260
+ else if (typeof raw === 'string') list = raw.split(/[,,]/);
261
+ else return [];
262
+ const out = [];
263
+ for (const item of list) {
264
+ const value = String(item === undefined || item === null ? '' : item).trim().slice(0, PARAM_OPTION_MAX);
265
+ if (!value || out.includes(value)) continue;
266
+ out.push(value);
267
+ if (out.length >= PARAM_OPTIONS_MAX) break;
268
+ }
269
+ return out;
270
+ }
271
+
272
+ /** 四个值以外的类型(INT / FLOAT / STRING …)按老词表折;认不出的当文本。 */
273
+ function paramTypeOf(raw) {
274
+ const text = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase();
275
+ return LEGACY_PARAM_TYPES[text] || 'text';
276
+ }
277
+
278
+ function paramDescriptionOf(raw) {
279
+ return typeof raw === 'string' ? raw.trim().slice(0, PARAM_DESCRIPTION_MAX) : '';
280
+ }
281
+
282
+ function paramDefaultOf(raw, maxLength = PARAM_DEFAULT_MAX) {
283
+ if (raw === undefined || raw === null) return '';
284
+ if (typeof raw === 'object') {
285
+ try { return JSON.stringify(raw).slice(0, maxLength); } catch (_error) { return ''; }
286
+ }
287
+ return String(raw).trim().slice(0, maxLength);
288
+ }
289
+
290
+ /**
291
+ * 工作流行:`node` + `input` 是落点,`name` 是给对话模型看的键。
292
+ *
293
+ * `name` 缺省时等于 `input`(解析出来的候选就是这样);显式写了空名字算坏行,
294
+ * 免得一条没有键的行悄悄占住位置。
295
+ */
296
+ function sanitizeWorkflowRow(item) {
297
+ const node = typeof item.node === 'string' ? item.node.trim() : '';
298
+ const input = typeof item.input === 'string' ? item.input.trim() : '';
299
+ if (!node || !input) return null;
300
+ let name = input;
301
+ if (item.name !== undefined) {
302
+ if (typeof item.name !== 'string') return null;
303
+ name = item.name.trim().slice(0, PARAM_NAME_MAX);
304
+ if (!name) return null;
305
+ }
306
+ const row = {
307
+ name: name,
308
+ node: node,
309
+ input: input,
310
+ type: paramTypeOf(item.type)
311
+ };
312
+ if (Object.prototype.hasOwnProperty.call(item, 'default')) row.default = paramDefaultOf(item.default);
313
+ const description = paramDescriptionOf(item.description);
314
+ if (description) row.description = description;
315
+ if (item.expose === true) row.expose = true;
316
+ else if (item.expose === false) row.expose = false;
317
+ // 行级锁:只存 true(不写 = 未锁)。一键配置/自动检测只改未锁的行。
318
+ if (item.locked === true) row.locked = true;
319
+ if (item.role === true) row.role = true;
320
+ const options = sanitizeParamOptions(item.options);
321
+ if (options.length) row.options = options;
322
+ if (Array.isArray(item.candidates)) {
323
+ const seen = new Set();
324
+ const candidates = [];
325
+ for (const candidate of item.candidates) {
326
+ if (!candidate || typeof candidate !== 'object') continue;
327
+ const cNode = typeof candidate.node === 'string' ? candidate.node.trim() : '';
328
+ const cInput = typeof candidate.input === 'string' ? candidate.input.trim() : '';
329
+ const key = cNode + '::' + cInput;
330
+ if (!cNode || !cInput || seen.has(key)) continue;
331
+ seen.add(key);
332
+ candidates.push({ node: cNode, input: cInput });
333
+ }
334
+ if (candidates.length) row.candidates = candidates;
335
+ }
336
+ return row;
337
+ }
338
+
339
+ /**
340
+ * 离散参数表(HTTP 行):一行一个参数。坏行逐条丢掉(名字为空),其余字段尽量归一。
341
+ * 提示词行是固定行:无论存成什么样,落盘都必须是 text / 空默认 / 暴露。
342
+ */
343
+ function sanitizeTableRow(item, roles) {
344
+ const name = typeof item.name === 'string' ? item.name.trim().slice(0, PARAM_NAME_MAX) : '';
345
+ if (!name) return null;
346
+ const role = PARAM_ROLES.includes(String(item.role || '').toLowerCase())
347
+ ? String(item.role).toLowerCase()
348
+ : '';
349
+ // 内置 role 只允许一行:重复的当用户行处理会把它变成「假的内置行」,干脆丢掉。
350
+ if (role && roles.has(role)) return null;
351
+ if (role) roles.add(role);
352
+ const type = role === 'prompt' ? 'text' : paramTypeOf(item.type);
353
+ const param = {
354
+ name,
355
+ type,
356
+ default: role === 'prompt' ? '' : paramDefaultOf(item.default, type === 'json' ? 8192 : PARAM_DEFAULT_MAX),
357
+ description: paramDescriptionOf(item.description)
358
+ };
359
+ // 模型行的暴露是运行时按「选择器是不是自动」推导的(modelRowExposed),行上的值没人读;
360
+ // 写进来只会在 config.json 里留下「看着生效其实无效」的字段(expose:false 尤其误导)。
361
+ if (role !== 'model') param.expose = role === 'prompt' ? true : item.expose === true;
362
+ // 行级锁:只存 true(不写 = 未锁)。一键配置/自动检测只改未锁的行。
363
+ if (item.locked === true) param.locked = true;
364
+ if (role) param.role = role;
365
+ const options = sanitizeParamOptions(item.options);
366
+ if (options.length) param.options = options;
367
+ return param;
368
+ }
369
+
370
+ function validateAdvancedRows(provider) {
371
+ const table = provider.modelOptions;
372
+ if (!table || typeof table !== 'object') return;
373
+ for (const [model, entry] of Object.entries(table)) {
374
+ if (!Array.isArray(entry?.params)) continue;
375
+ for (const row of entry.params) {
376
+ if (row?.type !== 'json' || row.default === undefined || row.default === null) continue;
377
+ const value = typeof row.default === 'string' ? row.default.trim() : JSON.stringify(row.default);
378
+ if (value === '') continue;
379
+ try {
380
+ if (value.length > 8192) throw new Error('too large');
381
+ JSON.parse(value);
382
+ } catch (_error) {
383
+ throw new Error(model + ' 的参数 ' + row.name + ' 需要有效的 JSON 默认值,长度至多 8192 字符');
384
+ }
385
+ }
386
+ }
387
+ }
388
+
389
+ /** 行序:四个内置 role 按固定顺序排在前面(提示词永远第一),其余保持原序。 */
390
+ function sortParamRows(rows) {
391
+ const rank = (param) => (param.role ? PARAM_ROLES.indexOf(param.role) : PARAM_ROLES.length);
392
+ return rows.sort((a, b) => rank(a) - rank(b));
393
+ }
394
+
395
+ /** 只收 HTTP 行的那张表(老入口,行为不变)。 */
396
+ export function sanitizeParamTable(raw) {
397
+ if (!Array.isArray(raw)) return undefined;
398
+ const roles = new Set();
399
+ const out = [];
400
+ for (const item of raw) {
401
+ if (out.length >= PARAM_ROWS_MAX) break;
402
+ if (!item || typeof item !== 'object' || Array.isArray(item)) continue;
403
+ if (isWorkflowParamShape(item)) continue; // 工作流行不属于这张表
404
+ const row = sanitizeTableRow(item, roles);
405
+ if (row) out.push(row);
406
+ }
407
+ return out.length ? sortParamRows(out) : undefined;
408
+ }
409
+
410
+ /**
411
+ * params 的入口:逐行按形状分派,两种绑定混在同一个数组里,保持用户的行序
412
+ * (只有内置 role 行会被提到最前,提示词永远第一)。
413
+ */
414
+ function sanitizeParams(raw) {
415
+ if (!Array.isArray(raw)) return undefined;
416
+ const roles = new Set();
417
+ const out = [];
418
+ for (const item of raw) {
419
+ if (out.length >= PARAM_ROWS_MAX) break;
420
+ if (!item || typeof item !== 'object' || Array.isArray(item)) continue;
421
+ if (isWorkflowParamShape(item)) {
422
+ const row = sanitizeWorkflowRow(item);
423
+ if (row) out.push(row);
424
+ continue;
425
+ }
426
+ const row = sanitizeTableRow(item, roles);
427
+ if (row) out.push(row);
428
+ }
429
+ const names = new Set();
430
+ const unique = sortParamRows(out).filter((row) => {
431
+ if (isWorkflowParamShape(row)) return true;
432
+ if (names.has(row.name)) return false;
433
+ names.add(row.name);
434
+ return true;
435
+ });
436
+ return unique.length ? unique : undefined;
437
+ }
438
+
439
+ /** 逐项暴露开关:只存布尔值,未出现的项按角色/可调参数各自默认。 */
440
+ function sanitizeExpose(raw) {
441
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
442
+ const out = {};
443
+ for (const [key, value] of Object.entries(raw)) {
444
+ const name = String(key || '').trim();
445
+ if (!name || typeof value !== 'boolean') continue;
446
+ out[name] = value;
447
+ }
448
+ return Object.keys(out).length ? out : undefined;
449
+ }
450
+
451
+ /** 「尺寸参数」覆盖:编码方式 / 参数名 / 分隔符 / 面板控件,全空就当没设。 */
452
+ export function sanitizeSizeOption(raw) {
453
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
454
+ const mode = ['wh-string', 'wh-fields', 'aspect', 'tier', 'prompt'].includes(String(raw.mode)) ? String(raw.mode) : '';
455
+ const field = typeof raw.field === 'string' ? raw.field.trim().slice(0, 120) : '';
456
+ // 分隔符允许自定义(`|`、`,`、`_` 之类),但只收 1-4 个可见字符,且不能带空白。
457
+ const separator = typeof raw.separator === 'string'
458
+ ? raw.separator.trim().replace(/\s+/g, '').slice(0, 4)
459
+ : '';
460
+ // 面板控件形态(向量模型那种「面板给比例、线上发像素」):只影响 UI,不影响 body。
461
+ const control = SIZE_CONTROLS.includes(String(raw.control)) ? String(raw.control) : '';
462
+ // 第二个字段:让一个模型同时收到比例和档位(Gemini 的 aspectRatio + imageSize)。
463
+ let second = null;
464
+ if (raw.second && typeof raw.second === 'object' && !Array.isArray(raw.second)) {
465
+ const secondField = typeof raw.second.field === 'string' ? raw.second.field.trim().slice(0, 120) : '';
466
+ if (secondField) {
467
+ second = { from: raw.second.from === 'tier' ? 'tier' : 'aspect', field: secondField };
468
+ }
469
+ }
470
+ if (!mode && !field && !separator && !second && !control) return null;
471
+ const out = {};
472
+ if (mode) out.mode = mode;
473
+ if (field) out.field = field;
474
+ if (separator) out.separator = separator;
475
+ if (second) out.second = second;
476
+ if (control) out.control = control;
477
+ return out;
478
+ }
479
+
480
+ /**
481
+ * 字段模板覆盖:六个逻辑字段各写「发到哪儿」。形状由 field-templates 认,
482
+ * 认不出来的整条丢掉(发送时还会再校验一次,坏模板宁可在这里就没掉)。
483
+ */
484
+ export function sanitizeFields(raw) {
485
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
486
+ const out = {};
487
+ for (const [key, spec] of Object.entries(raw)) {
488
+ const name = String(key || '').trim();
489
+ if (!['prompt', 'negative', 'model', 'n', 'image', 'quality'].includes(name)) continue;
490
+ if (spec === null || spec === false) { out[name] = null; continue; }
491
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) continue;
492
+ try {
493
+ applyFields({}, { [name]: spec }, {}); // 只编译,不写值:形状不对会抛
494
+ } catch (_error) {
495
+ continue;
496
+ }
497
+ out[name] = spec;
498
+ }
499
+ return Object.keys(out).length ? out : null;
500
+ }
501
+
502
+ /**
503
+ * 模型选项里可上锁的键:七个输入键(尺寸 / 质量 / 字段模板 / 参数表 …)加一个
504
+ * `operations`(「输出设置」整块)。锁状态只存「与默认不同」的那几个,默认值由客户端按
505
+ * 提供商来源算(预设全锁 / 自定义不锁 / ComfyUI 的输入键不锁),所以这里只做形状校验,不猜默认。
506
+ */
507
+ export const LOCK_KEYS = ['size', 'quality', 'prompt', 'negative', 'model', 'n', 'image', 'operations'];
508
+
509
+ /** 键锁:只认八个已知键上的布尔值;一个都不剩就当没设。 */
510
+ function sanitizeLocked(raw) {
511
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
512
+ const out = {};
513
+ for (const key of LOCK_KEYS) {
514
+ if (typeof raw[key] !== 'boolean') continue;
515
+ out[key] = raw[key];
516
+ }
517
+ return Object.keys(out).length ? out : undefined;
518
+ }
519
+
520
+ /**
521
+ * 「质量参数」覆盖:收不收 + 字段名 + 档位表 + 值映射 + 默认档。
522
+ *
523
+ * 形状(与 qualityOverrideOf() 读到的一致):
524
+ * { supported: boolean, field?, options?: [{ label, value, default }], map?, default? }
525
+ *
526
+ * 两种输入都收,输出一律是新形状——老配置(`options: ['low']` + 顶层 `default: 'low'`)
527
+ * 读进来按 `supported: true` + 空显示名处理,档位小写化、`off` 不落盘(它是全局固定档,
528
+ * 语义是"不发")。
529
+ *
530
+ * `supported` 永远写出来(哪怕 true):草稿与落盘的形状一致,回读才不会把「勾着」变成
531
+ * 「没配」。只有 `supported: false` 一项也算一份有效配置——那是用户明确说了「这个模型
532
+ * 不发质量参数」,丢了它下次就会被规则重新打开。
533
+ */
534
+ export function sanitizeQualityOption(raw) {
535
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
536
+ const field = typeof raw.field === 'string' ? raw.field.trim().slice(0, 120) : '';
537
+ const options = [];
538
+ for (const item of Array.isArray(raw.options) ? raw.options : []) {
539
+ const object = Boolean(item) && typeof item === 'object' && !Array.isArray(item);
540
+ const value = String(object
541
+ ? (item.value === undefined || item.value === null ? '' : item.value)
542
+ : (item === undefined || item === null ? '' : item))
543
+ .trim().toLowerCase();
544
+ if (!value || value === 'off' || options.some((option) => option.value === value)) continue;
545
+ const label = object && typeof item.label === 'string' ? item.label.trim().slice(0, 40) : '';
546
+ options.push({ label: label, value: value, default: object && item.default === true });
547
+ }
548
+ const map = {};
549
+ if (raw.map && typeof raw.map === 'object' && !Array.isArray(raw.map)) {
550
+ for (const [key, value] of Object.entries(raw.map)) {
551
+ const name = String(key || '').trim().toLowerCase();
552
+ if (!name || name === 'off') continue;
553
+ if (typeof value !== 'string') continue;
554
+ map[name] = value;
555
+ }
556
+ }
557
+ // 默认档只有一处:新形状挂在某一条上,老形状在顶层。两处打架时以标了 default 的那条
558
+ // 为准(那是用户在面板里点过单选的),而且必须落在自己的档位表里。
559
+ const flagged = options.find((option) => option.default);
560
+ const declared = String(raw.default || '').trim().toLowerCase();
561
+ const wanted = flagged ? flagged.value : declared;
562
+ const chosen = wanted && wanted !== 'off' && options.some((option) => option.value === wanted) ? wanted : '';
563
+ for (const option of options) option.default = Boolean(chosen) && option.value === chosen;
564
+ const supported = raw.supported === false ? false : true;
565
+ if (!field && !options.length && !Object.keys(map).length && raw.supported !== false) return null;
566
+ const out = { supported: supported };
567
+ if (field) out.field = field;
568
+ if (options.length) out.options = options;
569
+ if (Object.keys(map).length) out.map = map;
570
+ if (chosen) out.default = chosen;
571
+ return out;
572
+ }
573
+
574
+ /** 旧的一键配置把 Gemini 原生输入写成了覆盖。仅清理整套匹配的旧默认值。 */
575
+ function clearLegacyGeminiInputs(entry, model) {
576
+ const { fields, locked, size } = entry;
577
+ const prompt = fields?.prompt;
578
+ if (!prompt || prompt.path !== 'contents[0].parts[]' || prompt.wrap !== 'text'
579
+ || Object.keys(prompt).length !== 2
580
+ || !LOCK_KEYS.every((key) => key === 'operations' || locked?.[key] === true)) return;
581
+
582
+ const legacyDefaultSize = size?.mode === 'aspect' && !size.separator && !size.control
583
+ && ((size.field === 'aspect_ratio' && !size.second)
584
+ || (size.field === 'generationConfig.imageConfig.aspectRatio'
585
+ && size.second?.from === 'tier' && size.second.field === 'generationConfig.imageConfig.imageSize'));
586
+ const legacyWithoutSize = !size && GEMINI_25_IMAGE.test(model)
587
+ && fields.negative?.appendToPrompt === '\n\nAvoid: ';
588
+ if (!legacyDefaultSize && !legacyWithoutSize) return;
589
+
590
+ delete fields.prompt;
591
+ if (!Object.keys(fields).length) delete entry.fields;
592
+ delete locked.prompt;
593
+ if (legacyDefaultSize) {
594
+ delete entry.size;
595
+ delete locked.size;
596
+ }
597
+ }
598
+
599
+ export function normalizeModelOptions(raw, models, adapter) {
600
+ const out = {};
601
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
602
+ const allowed = new Set(Array.isArray(models) ? models : []);
603
+ // A1111 没有工作流;其它适配器只要有尺寸/质量/字段模板/参数表就不强制要求工作流。
604
+ const paramsOnly = adapter === 'a1111';
605
+ for (const model of Object.keys(raw)) {
606
+ if (!allowed.has(model)) continue;
607
+ const entry = raw[model];
608
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
609
+ const workflow = typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
610
+ if (workflow.length > MODEL_WORKFLOW_MAX) continue;
611
+ const size = sanitizeSizeOption(entry.size);
612
+ const fields = sanitizeFields(entry.fields);
613
+ const quality = sanitizeQualityOption(entry.quality);
614
+ const locked = sanitizeLocked(entry.locked);
615
+ // 参数表也属于「只填了它」的合法配置(云端中转常见),不强制要求工作流。
616
+ const params = sanitizeParams(entry.params);
617
+ const operations = readOperations(entry.operations, true, adapter === 'custom');
618
+ // 只填了「尺寸/质量/字段参数/参数表」或只改了锁的模型也要留下。
619
+ if (!workflow && !paramsOnly && !size && !fields && !quality && !locked && !params && !operations) continue;
620
+ const mapping = sanitizeMapping(entry.mapping);
621
+ const expose = sanitizeExpose(entry.expose);
622
+ const next = {};
623
+ if (workflow) next.workflow = workflow;
624
+ if (mapping) next.mapping = mapping;
625
+ if (params) next.params = params;
626
+ if (expose) next.expose = expose;
627
+ if (size) next.size = size;
628
+ if (fields) next.fields = fields;
629
+ if (quality) next.quality = quality;
630
+ if (locked) next.locked = locked;
631
+ if (operations) next.operations = operations;
632
+ if (adapter === 'openai-images') clearLegacyGeminiInputs(next, model);
633
+ if (!Object.keys(next).length) continue;
634
+ out[model] = next;
635
+ }
636
+ return out;
637
+ }
638
+
639
+ /**
640
+ * 提供商的鉴权方式(`provider.auth`)——「协议 / 鉴权 / 输入 / 输出」四条里的第二条。
641
+ *
642
+ * 读的顺序(先写的赢):
643
+ * 1. 显式写下来的 `provider.auth`(新配置只有这一条路);
644
+ * 2. 老配置的 `protocolOptions.auth`(当年只有 bearer / api-key 两个取值);
645
+ * 3. 老协议 id 迁移表给的(azure-openai → api-key,见 upgradeLegacyProtocol)。
646
+ *
647
+ * 写回只写 `provider.auth`:`protocolOptions` 那一层不再出现 auth,但同层的其它选项
648
+ * (`edit`)原样留着——那些仍然是协议属性,不该被这次搬家带走。
649
+ *
650
+ * 认不出(mode 不在白名单、custom 没有合法头名、形状不对)就返回 null,等于没设:
651
+ * 请求时按协议默认(adapter.authHeader)回落,缺省 bearer。
652
+ */
653
+ function normalizeProviderAuth(item, upgraded) {
654
+ const legacy = item && item.protocolOptions && typeof item.protocolOptions === 'object'
655
+ ? item.protocolOptions.auth
656
+ : undefined;
657
+ return normalizeAuthSpec(item && item.auth)
658
+ || normalizeAuthSpec({ mode: legacy })
659
+ || normalizeAuthSpec(upgraded && upgraded.auth)
660
+ || null;
661
+ }
662
+
663
+ export function invalidProviderOperations(error) {
664
+ const message = error.message || String(error);
665
+ const wrapped = localizedError(new Error(message), 'provider.invalidOperations', { message });
666
+ wrapped.status = 400;
667
+ return wrapped;
668
+ }
669
+
670
+ function readOperations(raw, modelOnly, custom) {
671
+ // Keep invalid stored data visible for correction. Resolution will fail before submitting.
672
+ try { return (custom ? normalizeOperations : normalizeResponseOverrides)(raw, modelOnly); } catch (_error) { return raw; }
673
+ }
674
+
675
+ /* ── 预设身份推断(presetId 回填) ───────────────────────────────────────
676
+ *
677
+ * `provider.presetId` 记的是「这个提供商是从哪份预设建的」,客户端据此判「预设来源」:
678
+ * 协议设置整块不渲染、键默认全锁、一键配置不出现。这个字段是后加的,升级前建的
679
+ * 配置里没有它 —— 老用户于是被当成「自定义 API」,协议设置的折叠区又冒了出来,
680
+ * 与预设带来的字段模板、锁默认值都不一致。
681
+ *
682
+ * 回填**先分组、再消歧**,顺序固定、先命中先返回:
683
+ *
684
+ * 1. **按 adapter 收窄候选组**:只有 adapter 相同的预设进组(`custom` 不在清单里)。
685
+ * 2. **组内只有一条** → 就是它,地址完全不看:本地部署器的身份就是 adapter 本身,
686
+ * `:8189` 上的 ComfyUI 还是 ComfyUI,换端口、换主机名、挂在反向代理后面都算。
687
+ * 3. **组内按地址认**:归一化后地址完全相同 → 唯一命中就用它。共用 `openai-images`
688
+ * 的那 14 份预设靠这条分开(`api.openai.com/v1` 是 openai,`api.x.ai/v1` 是 xai)。
689
+ * 4. **组内按名称认**:提供商显示名与预设名相同 → 唯一命中就用它。地址里有占位符
690
+ * (azure 的 `YOUR-RESOURCE` 段)或换过域名的,靠这条落地。
691
+ * 5. **都不唯一 → 不填**:分组后仍然说不出是哪一家,就让它空着,别猜。
692
+ *
693
+ * 地址只在第 3 步当**组内的判别依据**:它能把共用 adapter 的几份预设分开,但跨组
694
+ * (adapter 不同)不算证据——那是「换了协议之后忘了改地址」的典型样子。
695
+ *
696
+ * **adapter 为空**(老配置 / 手动建的提供商)没有组可归:在**全部预设**里按地址找唯一
697
+ * 命中,地址认不出再按名称找唯一命中(名称只是次级证据)。不能拿「组内只有一条」当
698
+ * 身份——空 adapter 不是「只有一条」,是根本没分组。两个证据都必须唯一:重名、共用地址
699
+ * (sd-server / LocalAI、百炼两条)都只在不唯一时继续往下走,最后仍不唯一就不填。
700
+ *
701
+ * 组内认不出来时,不绑 adapter 的预设(目前只有 `openai`,它的 adapter 由地址/模型现选)
702
+ * 单独兜底:再按**地址**在它们里面找一次。它们**不参与第 2 步**「组内只有一条」
703
+ * (否则任何没填 adapter 的提供商都会被认成 OpenAI)。这条兜底只看地址:adapter 都
704
+ * 已经能分组了,名称就不再越组当证据。
705
+ */
706
+
707
+ /** 回环主机名:这三种写法指向同一台机器(`[::1]` 是 URL 里 IPv6 的方括号形态)。 */
708
+ const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);
709
+ /** 回环主机的规范名:比对之前统一成它。 */
710
+ const LOOPBACK_HOST_CANONICAL = '127.0.0.1';
711
+
712
+ /**
713
+ * 主机的比对形态:回环的三种写法算同一台机器,端口照留。
714
+ *
715
+ * 只做这一条等价。`192.168.1.5:8188` 上多半也跑着 ComfyUI,但「端口相同」不等于
716
+ * 「同一台机器」——共享主机、反向代理后面挂的是什么都有可能,猜错比不填更糟。
717
+ */
718
+ function hostKeyOf(host) {
719
+ const match = /^(\[[^\]]+\]|[^:]+)(:\d+)?$/.exec(host);
720
+ if (!match) return host;
721
+ const name = LOOPBACK_HOSTNAMES.has(match[1]) ? LOOPBACK_HOST_CANONICAL : match[1];
722
+ return name + (match[2] || '');
723
+ }
724
+
725
+ /**
726
+ * 地址的身份键:主机(回环归一、端口保留)+ 路径(小写、去尾斜杠、末尾 `/v1` 视为可省)。
727
+ *
728
+ * 只归一化「同一个地址的写法差异」:大小写、尾部斜杠、带不带 `/v1` —— 这几样是手抄地址
729
+ * 时最常见的偏差,不代表换了服务。带查询串 / 片段的一律不算预设地址(预设里没有这些,
730
+ * 出现它只能是用户手改过的)。
731
+ */
732
+ function presetUrlKey(baseUrl) {
733
+ const raw = String(baseUrl || '').trim();
734
+ if (!raw) return '';
735
+ let url;
736
+ try { url = new URL(raw); } catch (_error) { return ''; }
737
+ if (url.search || url.hash) return '';
738
+ const host = hostKeyOf(url.host.toLowerCase());
739
+ const path = url.pathname.replace(/\/+$/, '').toLowerCase().replace(/\/v1$/, '');
740
+ return host + path;
741
+ }
742
+
743
+ /** 名称的身份键:去空白、小写(显示名是用户可改的,这里只做最保守的归一)。 */
744
+ function presetNameKey(name) {
745
+ return String(name || '').trim().toLowerCase();
746
+ }
747
+
748
+ /**
749
+ * 预设的分组(模块级只算一次):adapter → 预设列表;不绑 adapter 的另存一份。
750
+ *
751
+ * 组内是「可能属于这一组的预设」,判唯一交给调用方——撞车本来就存在
752
+ * (sd-server 与 LocalAI 共用 `127.0.0.1:8080/v1`,百炼两条预设共用一个地址)。
753
+ */
754
+ let presetGroupCache = null;
755
+ function presetGroups() {
756
+ if (presetGroupCache) return presetGroupCache;
757
+ const byAdapter = new Map();
758
+ const unbound = [];
759
+ const all = PROVIDER_PRESETS.concat(LOCAL_PRESETS);
760
+ for (const preset of all) {
761
+ const adapter = String(preset.adapter || '').trim().toLowerCase();
762
+ if (!adapter) { unbound.push(preset); continue; }
763
+ const list = byAdapter.get(adapter);
764
+ if (list) list.push(preset); else byAdapter.set(adapter, [preset]);
765
+ }
766
+ presetGroupCache = { byAdapter, unbound, all };
767
+ return presetGroupCache;
768
+ }
769
+
770
+ /**
771
+ * 在一组预设里消歧:先地址、再名称,都要唯一命中。
772
+ *
773
+ * `single` 为真时「组内只有一条」直接就是答案(adapter 唯一确定身份的那种);
774
+ * 不绑 adapter 的兜底组传 false —— 单条不等于身份,那组里的每份预设都要地址或名称来认。
775
+ *
776
+ * @returns {string} preset id,或空串(认不出 / 有歧义)
777
+ */
778
+ function pickPreset(group, baseUrl, name, single) {
779
+ if (!group.length) return '';
780
+ if (single && group.length === 1) return group[0].id;
781
+ const urlKey = presetUrlKey(baseUrl);
782
+ if (urlKey) {
783
+ const hits = group.filter((preset) => presetUrlKey(preset.baseUrl) === urlKey);
784
+ if (hits.length === 1) return hits[0].id;
785
+ }
786
+ const nameKey = presetNameKey(name);
787
+ if (nameKey) {
788
+ const hits = group.filter((preset) => presetNameKey(preset.name) === nameKey);
789
+ if (hits.length === 1) return hits[0].id;
790
+ }
791
+ return '';
792
+ }
793
+
794
+ /**
795
+ * 提供商预设来源的判定(normalizeConfig 的入口)。
796
+ *
797
+ * adapter 是用户在设置里显式选的,所以它先决定候选组;组内再按地址、按名称消歧。
798
+ * adapter 为空时没有组可归,改在全部预设里按地址、再按名称消歧(见文件顶部)。
799
+ * 认不出就返回空串,客户端会在面板顶部明说一句「没认出提供商预设」——宁可不填,也不猜错。
800
+ *
801
+ * @returns {string} preset id,或空串(认不出 / 有歧义)
802
+ */
803
+ export function presetIdForProvider(adapter, baseUrl, name) {
804
+ const id = String(adapter || '').trim().toLowerCase();
805
+ if (id === 'custom') return '';
806
+ const groups = presetGroups();
807
+ // adapter 为空 = 说不出协议组:在**全部预设**里按地址认唯一命中,地址认不出再按名称
808
+ // 认唯一命中。名称是次级证据,但同样必须唯一(见文件顶部)。
809
+ // 以前这里只按地址在「不绑 adapter」的 openai 一份里兜底,火山方舟 Agent Plan 这类
810
+ // 名称与地址都和预设一致、adapter 却是空串的老配置就认不出来。
811
+ if (!id) return pickPreset(groups.all, baseUrl, name, false);
812
+ const group = groups.byAdapter.get(id) || [];
813
+ const hit = pickPreset(group, baseUrl, name, true);
814
+ if (hit) return hit;
815
+ // 组内认不出来时,不绑 adapter 的预设按地址兜底一次;adapter 能分组时名称不越组,
816
+ // 所以这条兜底只看地址(name 传空 = 不比名称)。理由见文件顶部。
817
+ if (group.length) return pickPreset(groups.unbound, baseUrl, '', false);
818
+ return '';
819
+ }
820
+
821
+ const LEGACY_OPENROUTER_FLUX = 'black-forest-labs/flux-2-pro';
822
+ const OPENROUTER_FLUX = 'black-forest-labs/flux.2-pro';
823
+
824
+ function isOfficialOpenRouter(adapter, baseUrl) {
825
+ if (adapter !== 'openrouter-images') return false;
826
+ try { return new URL(baseUrl).hostname === 'openrouter.ai'; } catch (_error) { return false; }
827
+ }
828
+
829
+ export function normalizeConfig(raw) {
830
+ const out = emptyConfig();
831
+ if (!raw || typeof raw !== 'object') return out;
832
+ const providers = Array.isArray(raw.providers) ? raw.providers : [];
833
+ for (const item of providers) {
834
+ if (!item || typeof item !== 'object') continue;
835
+ // 协议序:老版本的六条 OpenAI Images 家族协议已经合并成 openai-images,
836
+ // 这里按 upgradeLegacyProtocol(迁移表 LEGACY_PROTOCOL_ALIASES)改写一次,
837
+ // 连同它们的编辑形态选项。
838
+ // 幂等:改写后的值不再命中迁移表,再跑一遍什么都不会变。
839
+ // 改写只动 adapter / protocol / protocolOptions,presetId 与 modelOptions 原样留下。
840
+ const upgraded = upgradeLegacyProtocol({
841
+ adapter: String(item.adapter || ''),
842
+ protocol: String(item.protocol || ''),
843
+ protocolOptions: item.protocolOptions
844
+ });
845
+ // 协议:`adapter` 才是「用户选了哪条」的那一栏;老配置把协议 id 记在 `protocol` 里
846
+ // (同一个 id 空间),这里直接落到 adapter。`openai-images` / `auto` / `images` 是
847
+ // 「看 adapter」的意思,不算具体协议——否则每一份老配置都像选过一条协议。
848
+ let adapterId = String(upgraded.protocol).trim().toLowerCase() === 'custom'
849
+ ? 'custom'
850
+ : String(upgraded.adapter || '').trim().toLowerCase();
851
+ if (!adapterId) adapterId = concreteProtocolId(upgraded.protocol);
852
+ const key = String(item.key || '');
853
+ const trimmed = (value) => String(value || '').trim();
854
+ const rawEndpoints = item.customEndpoints && typeof item.customEndpoints === 'object' ? item.customEndpoints : {};
855
+ const customEndpoints = {
856
+ generate: trimmed(rawEndpoints.generate),
857
+ edit: trimmed(rawEndpoints.edit),
858
+ models: trimmed(rawEndpoints.models)
859
+ };
860
+ let baseUrl = trimmed(item.baseUrl).replace(/\/+$/, '');
861
+ // A fully qualified endpoint is also enough to establish the provider origin.
862
+ if (!baseUrl && adapterId === 'custom') {
863
+ const candidates = ['generate', 'edit', 'models'].map((kind) => item.operations?.[kind]?.path ?? customEndpoints[kind]);
864
+ const endpoint = candidates.map((value) => resolveHttpUrl(value)).find(Boolean);
865
+ if (endpoint) baseUrl = new URL(endpoint).origin;
866
+ }
867
+ // 预设来源:从提供商/本地预设创建时客户端记下的 id(开箱即用的那批)。
868
+ // 它是「这个提供商的字段模板与锁都来自预设」的唯一凭据——没有它就算用户自配。
869
+ //
870
+ // 老配置(这个字段还不存在)补一次:先按 adapter 收窄候选组,组内只有一条就直接用,
871
+ // 多条再按地址、按名称消歧;adapter 为空则在全部预设里按地址、再按名称消歧
872
+ // (见 presetIdForProvider 上面那五步)。补上的只是来源——
873
+ // adapter、协议选项、地址、鉴权全都原样保留,请求行为一字不变;变的只是 UI 判据与
874
+ // 锁的默认值。
875
+ // 自定义协议不推断:它本来就不是从预设来的,而且它的请求格式编辑器正住在
876
+ // 「协议设置」里——补一个来源会把用户自己写的 JSON 藏起来。
877
+ // 幂等:已有合法 presetId 的提供商一律不动,补过的再跑一遍读到的是同一个值。
878
+ // 预设来源:从提供商/本地预设创建时客户端记下的 id(开箱即用的那批)。
879
+ // 它是「这个提供商的字段模板与锁都来自预设」的唯一凭据——没有它就算用户自配。
880
+ //
881
+ // 老配置(这个字段还不存在)补一次:先按 adapter 收窄候选组,组内只有一条就直接用,
882
+ // 多条再按地址、按名称消歧;adapter 为空则在全部预设里按地址、再按名称消歧
883
+ // (见 presetIdForProvider 上面那五步)。补上的只是来源——
884
+ // adapter、协议选项、地址、鉴权全都原样保留,请求行为一字不变;变的只是 UI 判据与
885
+ // 锁的默认值。
886
+ // 自定义协议不推断:它本来就不是从预设来的,而且它的请求格式编辑器正住在
887
+ // 「协议设置」里——补一个来源会把用户自己写的 JSON 藏起来。
888
+ // 幂等:已有合法 presetId 的提供商一律不动,补过的再跑一遍读到的是同一个值。
889
+ //
890
+ // 顺序:来源先算,因为下面还要拿它把 adapter 补齐(从预设建的提供商,协议就是
891
+ // 预设里写的那条)。
892
+ const declaredPresetId = typeof item.presetId === 'string' ? item.presetId.trim() : '';
893
+ let presetId = '';
894
+ if (item.presetId === '' || (declaredPresetId && PRESET_ID.test(declaredPresetId))) {
895
+ presetId = declaredPresetId;
896
+ } else if (adapterId !== 'custom') {
897
+ presetId = presetIdForProvider(adapterId, baseUrl, String(item.name || '')) || '';
898
+ }
899
+ // 从预设建的提供商,协议就是预设里写的那条:补上 adapter 让它显式写下来。
900
+ // 「未选择」= adapter 为空 = 宿主不发请求(见 selectedProtocolOf),预设来源不该落在那个状态:
901
+ // 老配置里 adapter 为空、presetId 在的那批(客户端当年就是这么存的)靠这条自愈。
902
+ // 协议级选项一起来了:协议换了,同一套的选项也得跟上(用户写过的优先,见下面 Object.assign)。
903
+ let presetOptions = {};
904
+ if (!adapterId && presetId) {
905
+ const declared = presetProtocolOf(presetId);
906
+ if (declared) {
907
+ adapterId = declared.adapter;
908
+ presetOptions = declared.protocolOptions;
909
+ }
910
+ }
911
+ const protocolOptions = normalizeProtocolOptions(adapterId,
912
+ Object.assign({}, presetOptions, upgraded.protocolOptions));
913
+ const auth = normalizeProviderAuth(item, upgraded);
914
+ const listedModels = (Array.isArray(item.models) ? item.models : []).map(trimmed).filter(Boolean);
915
+ const repairOpenRouter = listedModels.includes(LEGACY_OPENROUTER_FLUX) && isOfficialOpenRouter(adapterId, baseUrl);
916
+ const models = Array.from(new Set(listedModels.map((model) =>
917
+ repairOpenRouter && model === LEGACY_OPENROUTER_FLUX ? OPENROUTER_FLUX : model)));
918
+ const names = {};
919
+ for (const model of models) {
920
+ const stored = item.names?.[model];
921
+ const legacy = repairOpenRouter && model === OPENROUTER_FLUX ? item.names?.[LEGACY_OPENROUTER_FLUX] : undefined;
922
+ const name = typeof stored === 'string' ? stored : legacy;
923
+ if (typeof name === 'string') names[model] = name;
924
+ }
925
+ const oldOptions = repairOpenRouter ? item.modelOptions?.[LEGACY_OPENROUTER_FLUX] : undefined;
926
+ const options = oldOptions && typeof oldOptions === 'object' && !Array.isArray(oldOptions)
927
+ ? { ...item.modelOptions, [OPENROUTER_FLUX]: { ...oldOptions, ...item.modelOptions[OPENROUTER_FLUX] } }
928
+ : item.modelOptions;
929
+ const modelOptions = normalizeModelOptions(options, models, adapterId);
930
+ const provider = {
931
+ id: String(item.id || randomUUID()), name: String(item.name || ''),
932
+ baseUrl: baseUrl,
933
+ apiKeyEnv: validKeyRef(item.apiKeyEnv),
934
+ optionalKey: !!item.optionalKey,
935
+ protocol: String(upgraded.protocol || 'openai-images'), adapter: adapterId, models, names
936
+ };
937
+ // 协议级选项(edit):只存用户真的选过的值,没写 = 协议默认。
938
+ // 鉴权方式不在这一层:它是 provider.auth(见 normalizeProviderAuth),跟着提供商走。
939
+ if (Object.keys(protocolOptions).length) provider.protocolOptions = protocolOptions;
940
+ if (auth) provider.auth = auth;
941
+ if (adapterId === 'custom') provider.customEndpoints = customEndpoints;
942
+ const operations = readOperations(item.operations, false, adapterId === 'custom');
943
+ if (operations) provider.operations = operations;
944
+ // 预设来源(上面已算好):显式写的空串表示「自定义 API」,它不是预设来源。
945
+ if (item.presetId === '' || presetId) provider.presetId = presetId;
946
+ // Responses API 需要一个能调工具的主模型;只有这个适配器要留。
947
+ if (provider.adapter === 'openai-responses') {
948
+ const hostModel = String(item.hostModel || '').trim();
949
+ if (hostModel) provider.hostModel = hostModel;
950
+ }
951
+ // 工作流与映射只有 ComfyUI 读,参数开关只有 A1111 读;尺寸/质量这类通用选项谁都要留。
952
+ const keepsWorkflow = provider.adapter === 'comfyui';
953
+ const keepsParams = keepsWorkflow || provider.adapter === 'a1111';
954
+ for (const model of Object.keys(modelOptions)) {
955
+ const entry = modelOptions[model];
956
+ if (!keepsWorkflow) { delete entry.workflow; delete entry.mapping; }
957
+ if (!keepsParams) {
958
+ delete entry.expose;
959
+ // 一张表两种绑定:工作流行只属于 ComfyUI / A1111,云端只留 HTTP 行。
960
+ if (Array.isArray(entry.params) && entry.params.length) {
961
+ const kept = entry.params.filter((row) => !isWorkflowParamShape(row));
962
+ if (kept.length) entry.params = kept; else delete entry.params;
963
+ }
964
+ }
965
+ if (!Object.keys(entry).length) delete modelOptions[model];
966
+ }
967
+ if (Object.keys(modelOptions).length > 0) provider.modelOptions = modelOptions;
968
+ if (key) provider.key = key;
969
+ out.providers.push(provider);
970
+ }
971
+ const wanted = raw.active && typeof raw.active === 'object' ? raw.active : {};
972
+ const provider = out.providers.find((p) => p.id === wanted.providerId);
973
+ // "auto" 是选择器里的特殊行:允许对话模型在提供商列表内自选模型。
974
+ let wantedModel = String(wanted.model || '').trim();
975
+ if (wantedModel === LEGACY_OPENROUTER_FLUX && provider && isOfficialOpenRouter(provider.adapter, provider.baseUrl)) {
976
+ wantedModel = OPENROUTER_FLUX;
977
+ }
978
+ const keepModel = wantedModel === 'auto' || (provider && provider.models.includes(wantedModel));
979
+ out.active = { providerId: provider ? provider.id : '', model: keepModel ? wantedModel : '' };
980
+ out.defaults = normalizeDefaults(raw.defaults);
981
+ return out;
982
+ }
983
+ /** DSH 凭据库(ctx.credentials)里的引用名;只允许我们自己的 MO_IMAGE_ 命名空间。 */
984
+ const KEY_REF_PREFIX = 'MO_IMAGE_';
985
+ const KEY_REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
986
+ /** 预设 id:与 adapters.js 里的 PROVIDER_PRESETS / LOCAL_PRESETS id 同一套字符集。 */
987
+ const PRESET_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
988
+ export function createConfigStore(options) {
989
+ return {
990
+ configFile: options.configFile,
991
+ ensureDirs: options.ensureDirs,
992
+ logHost: options.logHost,
993
+ credentialsAccessor: options.credentialsAccessor,
994
+ cache: null,
995
+ activeStates: new WeakMap(),
996
+ stamp: '',
997
+ webOriginHost: '',
998
+ keyMigration: null,
999
+ writeQueue: Promise.resolve(),
1000
+ saveQueue: Promise.resolve()
1001
+ };
1002
+ }
1003
+ export function credentialsService(store) {
1004
+ if (!store || typeof store.credentialsAccessor !== 'function') return undefined;
1005
+ try { return store.credentialsAccessor(); } catch (_error) { return undefined; }
1006
+ }
1007
+ export function validKeyRef(value) {
1008
+ const ref = String(value || '').trim();
1009
+ return KEY_REF_PATTERN.test(ref) && ref.startsWith(KEY_REF_PREFIX) ? ref : '';
1010
+ }
1011
+ /** 按 provider id 生成稳定的环境变量名,例如 MO_IMAGE_P_ABC_API_KEY。 */
1012
+ export function deriveKeyRef(id, used) {
1013
+ const stem = String(id || 'provider').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'PROVIDER';
1014
+ const base = KEY_REF_PREFIX + stem + '_API_KEY';
1015
+ let ref = base;
1016
+ for (let n = 2; used && used.has(ref); n++) ref = base.replace(/_API_KEY$/, '_' + n + '_API_KEY');
1017
+ return ref;
1018
+ }
1019
+ export function hasLegacyKeys(config) {
1020
+ return (config.providers || []).some((provider) => provider.key || !validKeyRef(provider.apiKeyEnv));
1021
+ }
1022
+ /** describe() 的 configured 也可能来自环境变量;只有不是 env fallback 才算已存进凭据库。 */
1023
+ export function credentialIsStored(info) {
1024
+ if (!info || !info.configured) return false;
1025
+ const source = String(info.source || '');
1026
+ return source !== 'env' && source !== 'project-env' && source !== 'user-env';
1027
+ }
1028
+
1029
+ function requestHostName(req) {
1030
+ const raw = String((req.headers && req.headers.host) || '').trim().toLowerCase();
1031
+ if (!raw) return '';
1032
+ const withoutPort = raw.replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
1033
+ return withoutPort;
1034
+ }
1035
+ /**
1036
+ * 配置写接口是本插件自己的本地 HTTP 路由,不走 DSH 的 remote 权限层,所以
1037
+ * 至少挡掉跨站浏览器请求和 DNS rebinding:Host 必须是回环、IP 字面量或
1038
+ * DSH_WEB_URL 公布的域名;Origin 必须同源;POST 必须是 application/json。
1039
+ * 同一 OS 用户的进程本来就能读凭据文件,这里不是对抗同 UID 进程的边界。
1040
+ */
1041
+ export function assertLocalRequest(store, req, write) {
1042
+ const hostName = requestHostName(req);
1043
+ if (!hostName) {
1044
+ const error = new Error('missing Host header'); error.status = 403; throw error;
1045
+ }
1046
+ const allowed = new Set(['127.0.0.1', 'localhost', '::1']);
1047
+ for (const value of [process.env.DSH_WEB_URL, store && store.webOriginHost]) {
1048
+ try {
1049
+ const parsed = new URL(String(value || ''));
1050
+ if (parsed.hostname) allowed.add(parsed.hostname.toLowerCase());
1051
+ } catch (_error) { /* ignore */ }
1052
+ }
1053
+ if (!allowed.has(hostName) && isIP(hostName) === 0) {
1054
+ const error = new Error('unexpected Host header'); error.status = 403; throw error;
1055
+ }
1056
+ const origin = req.headers && req.headers.origin;
1057
+ if (origin !== undefined) {
1058
+ let originUrl;
1059
+ try { originUrl = new URL(String(origin)); } catch (_error) {
1060
+ const error = new Error('invalid Origin'); error.status = 403; throw error;
1061
+ }
1062
+ const hostHeader = String(req.headers.host || '').toLowerCase();
1063
+ if (originUrl.host.toLowerCase() !== hostHeader) {
1064
+ const error = new Error('cross-origin request rejected'); error.status = 403; throw error;
1065
+ }
1066
+ }
1067
+ const site = req.headers && req.headers['sec-fetch-site'];
1068
+ if (site && site !== 'same-origin' && site !== 'none') {
1069
+ const error = new Error('cross-site request rejected'); error.status = 403; throw error;
1070
+ }
1071
+ if (write) {
1072
+ const type = String((req.headers && req.headers['content-type']) || '').toLowerCase();
1073
+ if (!type.startsWith('application/json')) {
1074
+ const error = new Error('content-type must be application/json'); error.status = 415; throw error;
1075
+ }
1076
+ }
1077
+ }
1078
+ /** 系统提示词节是同步渲染的,这里用 mtime 缓存一份配置副本。 */
1079
+ export function rememberConfig(store, config, stamp = '') {
1080
+ store.cache = config;
1081
+ store.stamp = stamp;
1082
+ }
1083
+ const configStampOf = (info) => [info.mtimeMs, info.ctimeMs, info.size, info.ino].join(':');
1084
+ export function readConfigSync(store) {
1085
+ try {
1086
+ const info = statSync(store.configFile);
1087
+ const stamp = configStampOf(info);
1088
+ if (!store.cache || stamp !== store.stamp) {
1089
+ store.cache = normalizeConfig(JSON.parse(readFileSync(store.configFile, 'utf8')));
1090
+ store.stamp = stamp;
1091
+ }
1092
+ } catch (_error) {
1093
+ if (!store.cache) store.cache = emptyConfig();
1094
+ }
1095
+ return store.cache;
1096
+ }
1097
+ export function modelImageState(provider, model, defaults, canEdit) {
1098
+ let adapter = null;
1099
+ try { adapter = resolveAdapter(provider, model); } catch (_error) { adapter = null; }
1100
+ const sizePolicy = adapter ? sizePolicyFor(provider, model, adapter) : null;
1101
+ const fixedSize = defaults.auto === false;
1102
+ const sizeRequest = adapter ? resolveSizeRequest(provider, model, defaults, {}, adapter) : null;
1103
+ const sizeTiers = sizePolicy && Array.isArray(sizePolicy.tiers) ? sizePolicy.tiers : [];
1104
+ const sizeAllowed = sizePolicy && Array.isArray(sizePolicy.allowed) ? sizePolicy.allowed : [];
1105
+ const sizeOptions = sizeTiers.length
1106
+ ? sizeTiers.map((tier) => String(tier.value))
1107
+ : sizeAllowed.map(String);
1108
+ return {
1109
+ provider, model, adapter, canEdit,
1110
+ editModel: model, editAdapter: adapter,
1111
+ workflowParams: workflowParamsOf(provider, model, adapter),
1112
+ qualitySpec: adapter ? qualityOptionsFor(provider, model, adapter) : null,
1113
+ quality: adapter ? qualityForAdapter(provider, model, resolveQuality(defaults), adapter) : undefined,
1114
+ sizeMode: fixedSize ? 'fixed' : 'auto',
1115
+ size: fixedSize ? (sizeRequest ? sizeRequest.arg : resolveSizeArg(defaults)) : undefined,
1116
+ strict: defaults.strict === true,
1117
+ control: sizeRequest ? sizeRequest.control : '',
1118
+ sizeOptions: sizeOptions.length ? sizeOptions : undefined,
1119
+ promptOptimization: defaults.promptOptimization !== false, defaults
1120
+ };
1121
+ }
1122
+
1123
+ /** 当前选中的生图模型;编辑也用同一个(严格模式,不做任何回退)。 */
1124
+ export function activeImageState(store, snapshot) {
1125
+ const config = snapshot || readConfigSync(store);
1126
+ const cache = store?.activeStates;
1127
+ if (cache?.has(config)) return cache.get(config);
1128
+ const provider = (config.providers || []).find((item) => item.id === config.active.providerId);
1129
+ const model = String((config.active && config.active.model) || '').trim();
1130
+ if (!provider || !model) {
1131
+ cache?.set(config, null);
1132
+ return null;
1133
+ }
1134
+ const models = provider.models || [];
1135
+ const editModels = editCapableModels(provider, models);
1136
+ const state = modelImageState(provider, model, config.defaults, model === 'auto' ? editModels.length > 0 : editModels.includes(model));
1137
+ state.models = models;
1138
+ state.editModels = editModels;
1139
+ cache?.set(config, state);
1140
+ return state;
1141
+ }
1142
+
1143
+ /** 凭据解析:状态服务与配置页共用同一套“哪里算有 Key”的口径。 */
1144
+ export async function resolveStatusKey(store, provider) {
1145
+ if (!provider) return { ok: false, source: '', ref: '' };
1146
+ if (provider.optionalKey || provider.auth?.mode === 'none') return { ok: true, source: 'optional', ref: '' };
1147
+ const ref = validKeyRef(provider.apiKeyEnv);
1148
+ const credentials = credentialsService(store);
1149
+ if (ref && credentials && typeof credentials.describe === 'function') {
1150
+ try {
1151
+ const info = await credentials.describe(ref);
1152
+ if (info && info.configured) return { ok: true, source: normalizeKeySource(info.source || 'credentials'), ref };
1153
+ } catch (error) {
1154
+ store.logHost('status credential describe failed for ' + ref + ': ' + String(error && error.message ? error.message : error));
1155
+ }
1156
+ }
1157
+ if (ref && String(process.env[ref] || '').trim()) return { ok: true, source: 'env', ref };
1158
+ if (provider.key) return { ok: true, source: 'config', ref };
1159
+ return { ok: false, source: '', ref };
1160
+ }
1161
+
1162
+ /** 只读状态快照:ctx.provide('moImageStatus').describe() 的实现。 */
1163
+ export async function describeImageStatus(store, version = "0.0.0") {
1164
+ const config = await readConfig(store);
1165
+ const active = config.active && typeof config.active === 'object' ? config.active : {};
1166
+ const provider = (config.providers || []).find((item) => item && item.id === active.providerId) || null;
1167
+ const key = await resolveStatusKey(store, provider);
1168
+ return buildImageStatus({ config, version: version, key });
1169
+ }
1170
+
1171
+ /**
1172
+ * 模型行(`role:'model'`)是否暴露给对话模型。
1173
+ *
1174
+ * 模型是特殊值:只有选择器停在「自动」时才需要它出现在参数清单里(这时模型还没定,
1175
+ * 由对话模型挑);选了一个具体模型,它就是选择器里那个,不该再被 `params` 改。
1176
+ * 所以这条判断只由选择器决定——行上存的 `expose`(老版本让用户点过眼睛)读进来也不认。
1177
+ *
1178
+ * @param {string} model 当前选择里的模型(`active.model`,可能是 'auto')
1179
+ */
1180
+ function modelRowExposed(model) {
1181
+ return String(model || '').trim() === 'auto';
1182
+ }
1183
+
1184
+ /** 内置行里模型那一行的 role(`role:'model'` 与工作流行上的 `role:true` 不是一回事)。 */
1185
+ const MODEL_PARAM_ROLE = 'model';
1186
+
1187
+ /**
1188
+ * 「自动」模式下没有固定的模型条目,模型行却住在每个模型自己的条目里:
1189
+ * 取第一个带模型行的条目把那一行补进清单(模型行是内置固定行,各条目只差一个可改的名字)。
1190
+ * 只补模型行——其它参数行各归各的模型,不跟过来。
1191
+ */
1192
+ function autoModelRowOf(options, adapter, takesHttpRows) {
1193
+ for (const entry of Object.values(options)) {
1194
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry) || !Array.isArray(entry.params)) continue;
1195
+ for (const row of entry.params) {
1196
+ if (!row || typeof row !== 'object' || Array.isArray(row)) continue;
1197
+ if (String(row.role || '').trim().toLowerCase() !== MODEL_PARAM_ROLE) continue;
1198
+ if (typeof row.name !== 'string' || !row.name.trim()) continue;
1199
+ if (isWorkflowParamShape(row)) {
1200
+ if (adapter.id !== 'comfyui' || !row.node || !row.input) continue;
1201
+ } else if (!takesHttpRows) continue;
1202
+ return Object.assign({}, row, { expose: true });
1203
+ }
1204
+ }
1205
+ return null;
1206
+ }
1207
+
1208
+ /**
1209
+ * 这个模型能交给对话模型的参数清单。两处来源合成一张:
1210
+ *
1211
+ * - 工作流行(有 node/input):只有 ComfyUI 会按落点写进工作流;
1212
+ * - HTTP 行(name 是请求体路径):通用路径与 A1111 会写进请求体。
1213
+ *
1214
+ * 暴露口径统一成「行的 expose 为 true」或「老配置的 expose 开关表里为 true」——
1215
+ * 老配置(A1111 只有开关表、ComfyUI 只有整表开关)升级后行为不变。
1216
+ * **模型行例外**:它不看行上的值,只按选择器推导(见 modelRowExposed)。
1217
+ * 提示词与负面词永远不出现:它们走工具自己的参数。
1218
+ */
1219
+ export function workflowParamsOf(provider, model, adapter) {
1220
+ try {
1221
+ if (!adapter) return undefined;
1222
+ const options = provider && provider.modelOptions ? provider.modelOptions : null;
1223
+ if (!options || typeof options !== 'object') return undefined;
1224
+ const modelAuto = modelRowExposed(model);
1225
+ // A1111 的老行为允许「换一个模型行」兜底:WebUI 的参数开关本来就是整个部署的。
1226
+ let source = options[model] && typeof options[model] === 'object' ? options[model] : null;
1227
+ if (!source && adapter.id === 'a1111') {
1228
+ source = Object.values(options).find((item) => item && typeof item === 'object'
1229
+ && (Array.isArray(item.params) || (item.expose && typeof item.expose === 'object'))) || null;
1230
+ }
1231
+ const expose = source && source.expose && typeof source.expose === 'object' ? source.expose : {};
1232
+ const rows = source && Array.isArray(source.params) ? source.params : [];
1233
+ const takesHttpRows = adapterTakesParamRows(adapter);
1234
+ const exposed = [];
1235
+ let sawModelRow = false;
1236
+ for (const row of rows) {
1237
+ if (!row || typeof row !== 'object' || Array.isArray(row)) continue;
1238
+ const name = typeof row.name === 'string' ? row.name.trim() : '';
1239
+ if (!name || PROMPT_ROLE_NAMES.has(name)) continue;
1240
+ const modelRow = String(row.role || '').trim().toLowerCase() === MODEL_PARAM_ROLE;
1241
+ if (modelRow) {
1242
+ // 模型行不看行上的 expose,也不看老开关表:暴露只由选择器推导。
1243
+ sawModelRow = true;
1244
+ if (!modelAuto) continue;
1245
+ } else if (row.expose !== true && expose[name] !== true) continue;
1246
+ // 推导出来的行把结论写进输出的 expose:下游按 expose 过滤时不会把这一行再滤掉。
1247
+ const out = modelRow ? Object.assign({}, row, { expose: true }) : row;
1248
+ if (isWorkflowParamShape(row)) {
1249
+ // 工作流行只对 ComfyUI 有意义;落点不全的行写不进去,别报给模型。
1250
+ if (adapter.id !== 'comfyui' || !row.node || !row.input) continue;
1251
+ exposed.push(out);
1252
+ continue;
1253
+ }
1254
+ if (!takesHttpRows) continue;
1255
+ exposed.push(out);
1256
+ }
1257
+ // A1111 老配置只有开关表、没有行:按内置清单兜底(默认值此时是空的,等于「不勾就不发」)。
1258
+ if (adapter.id === 'a1111' && !rows.length) {
1259
+ const legacy = A1111_PARAMS
1260
+ .filter((param) => expose[param.name] === true)
1261
+ .map((param) => ({ name: param.name, type: param.type }));
1262
+ if (legacy.length) return legacy;
1263
+ }
1264
+ if (modelAuto && !sawModelRow) {
1265
+ const fallback = autoModelRowOf(options, adapter, takesHttpRows);
1266
+ if (fallback) exposed.push(fallback);
1267
+ }
1268
+ return exposed.length ? exposed : undefined;
1269
+ } catch (_error) { return undefined; }
1270
+ }
1271
+
1272
+ /**
1273
+ * `params` 里哪些键这次真的用不上,翻成一句要回报给对话模型的话(没有就返回空串)。
1274
+ *
1275
+ * 有暴露行的模型不再说「不支持工作流参数」——那是上一轮的误报:A1111 与通用路径
1276
+ * 都认参数行,只有真的没暴露/不认识的键才需要提。
1277
+ *
1278
+ * 自己拼 body 的 ComfyUI / A1111 在 `execute()` 里已经逐一核对并回报,这里不再重复
1279
+ * (同一句话出现两次比不说更糟)。
1280
+ */
1281
+ const SELF_REPORTING_ADAPTERS = new Set(['comfyui', 'a1111']);
1282
+
1283
+ export function paramNoticeOf(provider, model, adapter, names) {
1284
+ try {
1285
+ if (!adapter || !Array.isArray(names) || !names.length) return '';
1286
+ if (SELF_REPORTING_ADAPTERS.has(String(adapter.id || ''))) return '';
1287
+ const exposed = new Set((workflowParamsOf(provider, model, adapter) || []).map((param) => param.name));
1288
+ const ignored = names.filter((name) => !exposed.has(name));
1289
+ if (!ignored.length) return '';
1290
+ return (exposed.size
1291
+ ? '这些参数没有暴露给当前模型,已忽略:'
1292
+ : '当前模型没有暴露任何可调参数,已忽略:') + ignored.join('、');
1293
+ } catch (_error) { return ''; }
1294
+ }
1295
+ export function canUseCredentials(store) {
1296
+ const credentials = credentialsService(store);
1297
+ return !!(credentials && typeof credentials.describe === 'function' && typeof credentials.resolve === 'function' && typeof credentials.set === 'function');
1298
+ }
1299
+ /** 浏览器只拿 hasKey/keySource,永远拿不到明文密钥。 */
1300
+ export async function publicConfig(store, config) {
1301
+ const credentials = credentialsService(store);
1302
+ const providers = await Promise.all((config.providers || []).map(async (provider) => {
1303
+ const copy = Object.assign({}, provider);
1304
+ delete copy.key;
1305
+ const ref = validKeyRef(provider.apiKeyEnv);
1306
+ let hasKey = false;
1307
+ let keySource = '';
1308
+ if (ref && credentials && typeof credentials.describe === 'function') {
1309
+ try {
1310
+ const info = await credentials.describe(ref);
1311
+ hasKey = !!info.configured;
1312
+ keySource = info.source || '';
1313
+ } catch (error) { store.logHost('credential describe failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
1314
+ }
1315
+ if (!hasKey && ref && process.env[ref]) { hasKey = true; keySource = 'env'; }
1316
+ if (!hasKey && provider.key) { hasKey = true; keySource = 'config'; }
1317
+ return Object.assign(copy, { hasKey: hasKey, keySource: keySource });
1318
+ }));
1319
+ return Object.assign({}, config, { providers: providers });
1320
+ }
1321
+ /**
1322
+ * 参考图的「宿主声明」:编辑操作、预设与模型规则合成的模板。
1323
+ *
1324
+ * 面板拿它当「支持参考图」的默认勾选值,所以必须只看声明层:用户取消勾选时写的是
1325
+ * `fields.image = null`(显式不发),要是把覆盖层也算进来,取消一次就再也没法继承回
1326
+ * 预设的模板了。adapter 已解析具体模型的编辑操作,重新合成时只摘掉表单字段覆盖。
1327
+ *
1328
+ * 认不出的形状(数组、null)一律当「没有声明」:面板只需要「有模板 / 没模板」。
1329
+ */
1330
+ function imageCapabilityOf(provider, model, adapter) {
1331
+ if (!adapter) return null;
1332
+ try {
1333
+ const declared = operationFieldsFor(adapter, { ...provider, modelOptions: {} }, model, 'edit');
1334
+ const spec = declared && declared.image;
1335
+ return spec && typeof spec === 'object' && !Array.isArray(spec) ? spec : null;
1336
+ } catch (_error) { return null; }
1337
+ }
1338
+
1339
+ /** 选择器用的模型能力表:每个模型可用哪些质量档、尺寸控件长什么样、参考图默认发到哪。 */
1340
+ export function capabilityManifest(config) {
1341
+ return (config.providers || []).map((provider) => ({
1342
+ providerId: provider.id,
1343
+ models: (provider.models || []).map((model) => {
1344
+ let adapter = null;
1345
+ let quality = null;
1346
+ try { adapter = resolveAdapter(provider, model); quality = qualityOptionsFor(provider, model, adapter); } catch (_error) { adapter = null; quality = null; }
1347
+ return {
1348
+ model: model,
1349
+ quality: quality,
1350
+ size: sizeSpecFor(provider, model, adapter),
1351
+ image: imageCapabilityOf(provider, model, adapter)
1352
+ };
1353
+ })
1354
+ }));
1355
+ }
1356
+ /**
1357
+ * 把旧版 config.json 里的明文 key 迁到 DSH 凭据库,并在配置里只留下 apiKeyEnv 引用。
1358
+ * 凭据服务不存在(自定义 composition)时保持旧字段,避免把用户锁死。
1359
+ */
1360
+ export async function migrateConfigKeys(store, input) {
1361
+ if (!canUseCredentials(store)) return input;
1362
+ const credentials = credentialsService(store);
1363
+ const config = normalizeConfig(input);
1364
+ const reserved = new Set(config.providers.map((provider) => provider.apiKeyEnv).filter(Boolean));
1365
+ const used = new Set();
1366
+ let migrated = 0;
1367
+ let changed = false;
1368
+ for (const provider of config.providers) {
1369
+ let ref = provider.apiKeyEnv;
1370
+ if (!ref || used.has(ref)) {
1371
+ ref = deriveKeyRef(provider.id, reserved);
1372
+ reserved.add(ref);
1373
+ provider.apiKeyEnv = ref;
1374
+ changed = true;
1375
+ }
1376
+ used.add(ref);
1377
+ if (!provider.key) continue;
1378
+ try {
1379
+ const info = await credentials.describe(ref);
1380
+ if (!credentialIsStored(info)) {
1381
+ await credentials.set(ref, provider.key);
1382
+ migrated++;
1383
+ }
1384
+ delete provider.key;
1385
+ changed = true;
1386
+ } catch (error) {
1387
+ store.logHost('credential migration failed for provider ' + provider.id + ': ' + String(error && error.message ? error.message : error));
1388
+ }
1389
+ }
1390
+ if (!changed) return config;
1391
+ const saved = await writeConfig(store, config);
1392
+ if (migrated > 0) store.logHost('migrated ' + migrated + ' API key(s) to credentials store');
1393
+ return saved;
1394
+ }
1395
+ export function migrateKeysOnce(store, config) {
1396
+ if (!store.keyMigration) store.keyMigration = migrateConfigKeys(store, config).finally(() => { store.keyMigration = null; });
1397
+ return store.keyMigration;
1398
+ }
1399
+ /**
1400
+ * 这次读盘需不需要把协议写回去。
1401
+ *
1402
+ * 只认一件事:盘上那份 `adapter` 空着,而 `normalizeConfig` 补出了一条**具体的**协议。
1403
+ * 补出来的三条来源都是「已知」:预设来源(`presetId`)、老配置 `protocol` 里的协议 id、
1404
+ * 老协议 id 的迁移表。都没有就补不出来,那才是真正的「未选择」——不该被写。
1405
+ *
1406
+ * 按序号对齐,两边长度不一致就放弃(配置被丢过条目时别把协议写到别人身上)。
1407
+ */
1408
+ function protocolRepairNeeded(raw, normalized) {
1409
+ const before = raw && Array.isArray(raw.providers) ? raw.providers : null;
1410
+ const after = normalized && Array.isArray(normalized.providers) ? normalized.providers : null;
1411
+ if (!before || !after || before.length !== after.length) return false;
1412
+ return before.some((item, index) => {
1413
+ if (String((item && item.adapter) || '').trim()) return false;
1414
+ return Boolean(String((after[index] && after[index].adapter) || '').trim());
1415
+ });
1416
+ }
1417
+
1418
+ export async function readConfig(store) {
1419
+ try {
1420
+ const stamp = configStampOf(await stat(store.configFile));
1421
+ let raw = null;
1422
+ let config;
1423
+ if (store.stamp === stamp && store.cache) {
1424
+ config = store.cache;
1425
+ } else {
1426
+ raw = JSON.parse(await readFile(store.configFile, 'utf8'));
1427
+ config = normalizeConfig(raw);
1428
+ }
1429
+ if (hasLegacyKeys(config) && canUseCredentials(store)) {
1430
+ try {
1431
+ config = await migrateKeysOnce(store, config);
1432
+ if (store.cache === config && store.stamp !== stamp) return config;
1433
+ } catch (error) { store.logHost('config key migration failed: ' + String(error && error.message ? error.message : error)); }
1434
+ }
1435
+ rememberConfig(store, config, stamp);
1436
+ // 协议自愈(见 protocolRepairNeeded):补上并**写回盘上**——「未选择」不该长期停在
1437
+ // 一条本来就有预设的提供商上(火山方舟 Agent Plan 那种)。写失败不影响这次读取。
1438
+ if (raw && protocolRepairNeeded(raw, config)) {
1439
+ try {
1440
+ config = await writeConfig(store, config);
1441
+ } catch (error) {
1442
+ store.logHost('protocol backfill failed: ' + String(error && error.message ? error.message : error));
1443
+ }
1444
+ }
1445
+ return config;
1446
+ } catch (error) {
1447
+ if (error?.code !== 'ENOENT') return store.cache || emptyConfig();
1448
+ if (store.stamp !== 'missing') rememberConfig(store, emptyConfig(), 'missing');
1449
+ return store.cache;
1450
+ }
1451
+ }
1452
+ export async function writeConfig(store, config) {
1453
+ const next = normalizeConfig(config);
1454
+ const task = store.writeQueue.then(async () => {
1455
+ store.ensureDirs();
1456
+ const tempFile = store.configFile + '.tmp-' + process.pid + '-' + randomUUID().slice(0, 8);
1457
+ try {
1458
+ await writeFile(tempFile, JSON.stringify(next, null, 2), { encoding: 'utf8', mode: 0o600 });
1459
+ await rename(tempFile, store.configFile);
1460
+ } finally {
1461
+ try { await unlink(tempFile); } catch (_error) { /* rename 成功后临时文件已不存在 */ }
1462
+ }
1463
+ let stamp = '';
1464
+ try { stamp = configStampOf(await stat(store.configFile)); } catch (_error) { /* refresh on next read */ }
1465
+ rememberConfig(store, next, stamp);
1466
+ return next;
1467
+ });
1468
+ store.writeQueue = task.catch(() => {});
1469
+ return task;
1470
+ }
1471
+ /** 每次请求才解析一次密钥;不在内存里长期缓存,轮换后下一请求生效。 */
1472
+ export async function resolveProviderCredential(store, provider) {
1473
+ if (provider.auth?.mode === 'none') return provider;
1474
+ const ref = validKeyRef(provider.apiKeyEnv);
1475
+ const credentials = credentialsService(store);
1476
+ if (ref) {
1477
+ if (credentials && typeof credentials.resolve === 'function') {
1478
+ try {
1479
+ const hit = await credentials.resolve(ref);
1480
+ if (hit && typeof hit.value === 'string' && hit.value.trim().length > 0) {
1481
+ return Object.assign({}, provider, { key: hit.value.trim() });
1482
+ }
1483
+ } catch (error) { store.logHost('credential resolve failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
1484
+ }
1485
+ const env = process.env[ref];
1486
+ if (env && env.trim()) return Object.assign({}, provider, { key: env.trim() });
1487
+ }
1488
+ if (provider.key) return provider;
1489
+ if (provider.optionalKey) return provider;
1490
+ throw localizedError(
1491
+ new Error('生图提供商「' + (provider.name || provider.id) + '」缺少 API Key,请到 DSH 设置 → 生图模型填写'
1492
+ + (ref ? '(凭据 ' + ref + ')' : '') + '。'),
1493
+ ref ? 'provider.missingKeyWithRef' : 'provider.missingKey',
1494
+ { provider: provider.name || provider.id, ref: ref }
1495
+ );
1496
+ }
1497
+ /** 保存配置前先把每个 provider 的新 key 写进凭据库,配置文件只保留 apiKeyEnv。 */
1498
+ export function validateProviderDraft(provider, { resolve = true } = {}) {
1499
+ if (!provider || typeof provider !== 'object') return;
1500
+ if (provider.auth?.mode && !normalizeAuthSpec(provider.auth)) {
1501
+ const error = localizedError(new Error('检查鉴权方式、请求头名或查询参数名。'), 'provider.invalidAuth');
1502
+ error.status = 400;
1503
+ throw error;
1504
+ }
1505
+ const custom = provider.adapter === 'custom' || provider.protocol === 'custom';
1506
+ const validate = custom ? normalizeOperations : normalizeResponseOverrides;
1507
+ try {
1508
+ validateAdvancedRows(provider);
1509
+ const { operations, modelOptions, customEndpoints, baseUrl } = provider;
1510
+ validate(operations);
1511
+ for (const model of Object.values(modelOptions || {})) validate(model?.operations, true);
1512
+ if (!custom) return;
1513
+ if (baseUrl && !resolveHttpUrl(String(baseUrl).trim())) throw new Error('API 地址需要使用 HTTP(S)');
1514
+ const normalized = normalizeConfig({ providers: [provider] }).providers[0];
1515
+ if (resolve) {
1516
+ for (const model of new Set(['', ...Object.keys(modelOptions || {})])) resolveAdapter(normalized, model);
1517
+ }
1518
+ for (const value of Object.values(customEndpoints || {})) {
1519
+ if (!value || !String(value).trim()) continue;
1520
+ const path = String(value).trim();
1521
+ if (/^\/\//.test(path) || /^[a-z][a-z\d+.-]*:/i.test(path) && !resolveHttpUrl(path)) {
1522
+ throw new Error('端点需要 HTTP(S) 地址或相对于 API 地址的路径');
1523
+ }
1524
+ }
1525
+ } catch (error) {
1526
+ throw invalidProviderOperations(error);
1527
+ }
1528
+ }
1529
+
1530
+ export function saveConfigWithCredentials(store, raw) {
1531
+ const task = store.saveQueue.then(() => persistConfigWithCredentials(store, raw));
1532
+ store.saveQueue = task.catch(() => {});
1533
+ return task;
1534
+ }
1535
+
1536
+ async function persistConfigWithCredentials(store, raw) {
1537
+ for (const provider of Array.isArray(raw?.providers) ? raw.providers : []) {
1538
+ validateProviderDraft(provider);
1539
+ }
1540
+ const incoming = normalizeConfig(raw);
1541
+ const current = await readConfig(store);
1542
+ const credentials = credentialsService(store);
1543
+ const canStore = !!(credentials && typeof credentials.set === 'function');
1544
+ const canDescribe = !!(credentials && typeof credentials.describe === 'function');
1545
+ const currentById = new Map(current.providers.map((provider) => [provider.id, provider]));
1546
+ const owners = new Map();
1547
+ for (const provider of current.providers) {
1548
+ if (provider.apiKeyEnv && !owners.has(provider.apiKeyEnv)) owners.set(provider.apiKeyEnv, provider.id);
1549
+ }
1550
+ // Reserve existing and explicitly requested references before deriving one for any new provider.
1551
+ const reserved = new Set(owners.keys());
1552
+ for (const provider of incoming.providers) if (provider.apiKeyEnv) reserved.add(provider.apiKeyEnv);
1553
+ const used = new Set();
1554
+ const originals = new Map();
1555
+ const credentialChanges = [];
1556
+ const providers = [];
1557
+ for (const provider of incoming.providers) {
1558
+ const old = currentById.get(provider.id);
1559
+ let ref = provider.apiKeyEnv || old?.apiKeyEnv;
1560
+ if (!ref || used.has(ref) || (owners.has(ref) && owners.get(ref) !== provider.id)) {
1561
+ ref = deriveKeyRef(provider.id, reserved);
1562
+ reserved.add(ref);
1563
+ }
1564
+ used.add(ref);
1565
+ provider.apiKeyEnv = ref;
1566
+ const newKey = String(provider.key || '').trim();
1567
+ delete provider.key;
1568
+ if (newKey) {
1569
+ if (!canStore) throw localizedError(new Error('DSH 凭据服务未挂载,无法安全保存 API Key;请确认 base composition 包含 dsh-credentials-local。'), 'config.credentialsUnavailable');
1570
+ credentialChanges.push({ ref, value: newKey, legacy: false });
1571
+ } else if (old && old.key) {
1572
+ if (canStore && canDescribe) {
1573
+ try {
1574
+ const info = await credentials.describe(ref);
1575
+ if (!credentialIsStored(info)) credentialChanges.push({ ref, value: old.key, legacy: true });
1576
+ } catch (error) {
1577
+ const message = String(error && error.message ? error.message : error);
1578
+ throw localizedError(new Error('旧 API Key 迁移失败:' + message), 'config.legacyKeyMigrationFailed', { message: message });
1579
+ }
1580
+ } else {
1581
+ provider.key = old.key;
1582
+ }
1583
+ }
1584
+ providers.push(provider);
1585
+ }
1586
+ incoming.providers = providers;
1587
+ let saved;
1588
+ try {
1589
+ for (const { ref, value, legacy } of credentialChanges) {
1590
+ try {
1591
+ const description = canDescribe ? await credentials.describe(ref) : null;
1592
+ const existing = credentialIsStored(description);
1593
+ const previous = existing && typeof credentials.resolve === 'function' ? await credentials.resolve(ref) : null;
1594
+ if (previous?.value === value) continue;
1595
+ originals.set(ref, { existing, value: previous?.value });
1596
+ await credentials.set(ref, value);
1597
+ } catch (error) {
1598
+ const message = String(error && error.message ? error.message : error);
1599
+ throw localizedError(new Error('保存 API Key 失败:' + message),
1600
+ legacy ? 'config.legacyKeyMigrationFailed' : 'config.credentialSaveFailed', { message });
1601
+ }
1602
+ }
1603
+ try {
1604
+ saved = await writeConfig(store, incoming);
1605
+ } catch (error) {
1606
+ const message = String(error && error.message ? error.message : error);
1607
+ throw localizedError(new Error('保存生图配置失败:' + message), 'config.writeFailed', { message });
1608
+ }
1609
+ } catch (error) {
1610
+ for (const [ref, previous] of [...originals].reverse()) {
1611
+ try {
1612
+ if (typeof previous.value === 'string') await credentials.set(ref, previous.value);
1613
+ else if (!previous.existing && canDescribe && typeof credentials.unset === 'function') await credentials.unset(ref);
1614
+ } catch (_rollbackError) { store.logHost('credential rollback failed for ' + ref); }
1615
+ }
1616
+ throw error;
1617
+ }
1618
+ if (credentials && typeof credentials.unset === 'function') {
1619
+ const kept = new Set(providers.map((provider) => provider.id));
1620
+ for (const old of current.providers) {
1621
+ if (kept.has(old.id)) continue;
1622
+ const ref = validKeyRef(old.apiKeyEnv);
1623
+ if (!ref || used.has(ref)) continue;
1624
+ try { await credentials.unset(ref); } catch (error) { store.logHost('credential removal failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
1625
+ }
1626
+ }
1627
+ return saved;
1628
+ }