dsh-mo-image 0.7.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.
@@ -1,19 +1,24 @@
1
- /**
1
+ /**
2
2
  * 配置域:归一化、按 mtime 的读写缓存、凭据解析、当前模型快照与任务级配置快照。
3
3
  *
4
4
  * 从 lib/index.js 拆出来后,配置读写和工具/路由注册分开;这个模块只依赖
5
5
  * adapters 的纯函数与 status 的模型能力判断,不 import index,避免循环依赖。
6
6
  */
7
- import { existsSync, readFileSync, statSync } from 'node:fs';
8
- import { readFile, writeFile, rename, unlink } from 'node:fs/promises';
7
+ import { readFileSync, statSync } from 'node:fs';
8
+ import { readFile, stat, writeFile, rename, unlink } from 'node:fs/promises';
9
9
  import { randomUUID } from 'node:crypto';
10
10
  import { isIP } from 'node:net';
11
11
 
12
12
  import {
13
13
  resolveAdapter, parseSize, sizePolicyFor, sizeSpecFor, nearestTier, nearestAspect, sizeForAspect,
14
- qualityOptionsFor, A1111_PARAMS
14
+ qualityForAdapter, qualityOptionsFor, operationFieldsFor, A1111_PARAMS, SIZE_CONTROLS, adapterTakesParamRows,
15
+ upgradeLegacyProtocol, normalizeProtocolOptions, concreteProtocolId, presetProtocolOf, PROVIDER_PRESETS, LOCAL_PRESETS
15
16
  } from './adapters.js';
16
- import { MAPPING_KEYS, DEFAULT_EXPOSED } from './comfy-workflow.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';
17
22
  import { buildImageStatus, editCapableModels, normalizeKeySource } from './status.js';
18
23
  import { localizedError } from './localized-error.js';
19
24
 
@@ -27,7 +32,10 @@ export function emptyConfig() {
27
32
  const QUALITY_VALUES = new Set(['off', 'low', 'medium', 'high', 'xhigh', 'max', 'auto', 'standard', 'hd', 'default', 'quality', 'turbo']);
28
33
  export function normalizeQuality(value) {
29
34
  const raw = String(value || '').trim().toLowerCase();
30
- return QUALITY_VALUES.has(raw) ? raw : 'high';
35
+ // 档位不再锁死在白名单里:模型选项支持自定义档位,合法性在发送时按解析出的 options 判断。
36
+ if (!raw) return 'high';
37
+ if (!/^[a-z0-9][a-z0-9._-]{0,31}$/.test(raw)) return 'high';
38
+ return raw;
31
39
  }
32
40
  export function normalizeDefaults(raw) {
33
41
  const source = raw && typeof raw === 'object' ? raw : {};
@@ -59,10 +67,29 @@ export function normalizeDefaults(raw) {
59
67
  promptOptimization: source.promptOptimization === undefined ? true : !!source.promptOptimization
60
68
  };
61
69
  }
62
- /** 质量、尺寸都只取选择器默认值;工具不再接受模型传入的参数。 */
70
+ /** 选择器上的质量模式。只有 Auto 允许工具挑选当前模型支持的档位。 */
63
71
  export function resolveQuality(defaults) {
64
72
  return normalizeQuality(defaults && defaults.quality);
65
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
+ }
66
93
  export function resolveSizeArg(defaults) {
67
94
  if (defaults && defaults.auto === false) return (defaults.width || 1024) + 'x' + (defaults.height || 1024);
68
95
  return 'none';
@@ -77,8 +104,8 @@ export function resolveSizeArg(defaults) {
77
104
  * 自动尺寸下一切交给对话模型:它传了 size 就用它,没传就不带尺寸。
78
105
  * @returns {{arg:string, nominal:{width:number,height:number}|null, control:string, aspect:string, tier:string, note:string, stitch:boolean}}
79
106
  */
80
- export function resolveSizeRequest(adapter, model, defaults, args) {
81
- const policy = sizePolicyFor(adapter, model);
107
+ export function resolveSizeRequest(provider, model, defaults, args, adapter) {
108
+ const policy = sizePolicyFor(provider, model, adapter);
82
109
  const allowed = Array.isArray(policy.allowed) ? policy.allowed.filter(Boolean) : [];
83
110
  const control = String(policy.control
84
111
  || (allowed.length ? 'preset' : (policy.style === 'aspect' ? 'aspect' : 'wh')));
@@ -91,6 +118,13 @@ export function resolveSizeRequest(adapter, model, defaults, args) {
91
118
 
92
119
  if (auto) {
93
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
+ }
94
128
  out.arg = asked;
95
129
  const parsed = parseSize(asked);
96
130
  if (parsed) out.nominal = { width: parsed.width, height: parsed.height };
@@ -175,43 +209,231 @@ function sanitizeMapping(raw) {
175
209
  return Object.keys(out).length ? out : undefined;
176
210
  }
177
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
+
178
339
  /**
179
- * 可调参数清单来自解析结果,形状固定:name/node/input/type/default[/options]。
180
- * 任何一项不合法就整体丢弃——宁可不让模型看到,也不要报一个假的默认值。
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 行会被提到最前,提示词永远第一)。
181
413
  */
182
414
  function sanitizeParams(raw) {
183
415
  if (!Array.isArray(raw)) return undefined;
416
+ const roles = new Set();
184
417
  const out = [];
185
418
  for (const item of raw) {
186
- if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
187
- const name = typeof item.name === 'string' ? item.name.trim() : '';
188
- const node = typeof item.node === 'string' ? item.node.trim() : '';
189
- const input = typeof item.input === 'string' ? item.input.trim() : '';
190
- // ComfyUI 的参数必须带节点位置;A1111 的参数只是 sdapi 字段名,没有节点。
191
- if (!name) return undefined;
192
- if ((node && !input) || (!node && input)) return undefined;
193
- const param = { name, type: String(item.type || 'string') };
194
- if (node && input) { param.node = node; param.input = input; }
195
- if (Array.isArray(item.options)) param.options = item.options.map(String).slice(0, 64);
196
- if (item.role === true) param.role = true;
197
- if (item.expose === false) param.expose = false;
198
- if (Array.isArray(item.candidates)) {
199
- const seen = new Set();
200
- param.candidates = [];
201
- for (const candidate of item.candidates) {
202
- if (!candidate || typeof candidate !== 'object') continue;
203
- const node = typeof candidate.node === 'string' ? candidate.node.trim() : '';
204
- const input = typeof candidate.input === 'string' ? candidate.input.trim() : '';
205
- const key = node + '::' + input;
206
- if (!node || !input || seen.has(key)) continue;
207
- seen.add(key);
208
- param.candidates.push({ node, input });
209
- }
210
- if (!param.candidates.length) delete param.candidates;
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;
211
425
  }
212
- out.push(param);
426
+ const row = sanitizeTableRow(item, roles);
427
+ if (row) out.push(row);
213
428
  }
214
- return out.length ? out : undefined;
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;
215
437
  }
216
438
 
217
439
  /** 逐项暴露开关:只存布尔值,未出现的项按角色/可调参数各自默认。 */
@@ -226,11 +448,159 @@ function sanitizeExpose(raw) {
226
448
  return Object.keys(out).length ? out : undefined;
227
449
  }
228
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
+
229
599
  export function normalizeModelOptions(raw, models, adapter) {
230
600
  const out = {};
231
601
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
232
602
  const allowed = new Set(Array.isArray(models) ? models : []);
233
- // A1111 只有参数开关,没有工作流;其它适配器仍然要求工作流。
603
+ // A1111 没有工作流;其它适配器只要有尺寸/质量/字段模板/参数表就不强制要求工作流。
234
604
  const paramsOnly = adapter === 'a1111';
235
605
  for (const model of Object.keys(raw)) {
236
606
  if (!allowed.has(model)) continue;
@@ -238,57 +608,373 @@ export function normalizeModelOptions(raw, models, adapter) {
238
608
  if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
239
609
  const workflow = typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
240
610
  if (workflow.length > MODEL_WORKFLOW_MAX) continue;
241
- if (!workflow && !paramsOnly) continue;
242
- const mapping = sanitizeMapping(entry.mapping);
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
+ // 参数表也属于「只填了它」的合法配置(云端中转常见),不强制要求工作流。
243
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);
244
621
  const expose = sanitizeExpose(entry.expose);
245
622
  const next = {};
246
623
  if (workflow) next.workflow = workflow;
247
624
  if (mapping) next.mapping = mapping;
248
625
  if (params) next.params = params;
249
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);
250
633
  if (!Object.keys(next).length) continue;
251
634
  out[model] = next;
252
635
  }
253
636
  return out;
254
637
  }
255
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
+
256
829
  export function normalizeConfig(raw) {
257
830
  const out = emptyConfig();
258
831
  if (!raw || typeof raw !== 'object') return out;
259
832
  const providers = Array.isArray(raw.providers) ? raw.providers : [];
260
833
  for (const item of providers) {
261
834
  if (!item || typeof item !== 'object') continue;
262
- const models = Array.from(new Set((Array.isArray(item.models) ? item.models : [])
263
- .map((m) => String(m || '').trim()).filter(Boolean)));
264
- const names = {};
265
- if (item.names && typeof item.names === 'object') for (const model of models) if (typeof item.names[model] === 'string') names[model] = item.names[model];
266
- const modelOptions = normalizeModelOptions(item.modelOptions, models, item.adapter);
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);
267
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);
268
930
  const provider = {
269
931
  id: String(item.id || randomUUID()), name: String(item.name || ''),
270
- baseUrl: String(item.baseUrl || '').replace(/\/+$/, ''),
932
+ baseUrl: baseUrl,
271
933
  apiKeyEnv: validKeyRef(item.apiKeyEnv),
272
934
  optionalKey: !!item.optionalKey,
273
- protocol: String(item.protocol || 'openai-images'), adapter: String(item.adapter || ''), models, names
935
+ protocol: String(upgraded.protocol || 'openai-images'), adapter: adapterId, models, names
274
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;
275
946
  // Responses API 需要一个能调工具的主模型;只有这个适配器要留。
276
947
  if (provider.adapter === 'openai-responses') {
277
948
  const hostModel = String(item.hostModel || '').trim();
278
949
  if (hostModel) provider.hostModel = hostModel;
279
950
  }
280
- // 自定义工作流只有 ComfyUI 适配器会读;别的提供商留着也没用,直接丢弃。
281
- // ComfyUI 读工作流与映射,A1111 只读参数开关;其它适配器不认这些。
282
- if ((provider.adapter === 'comfyui' || provider.adapter === 'a1111') && Object.keys(modelOptions).length > 0) {
283
- provider.modelOptions = modelOptions;
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];
284
966
  }
967
+ if (Object.keys(modelOptions).length > 0) provider.modelOptions = modelOptions;
285
968
  if (key) provider.key = key;
286
969
  out.providers.push(provider);
287
970
  }
288
971
  const wanted = raw.active && typeof raw.active === 'object' ? raw.active : {};
289
972
  const provider = out.providers.find((p) => p.id === wanted.providerId);
290
973
  // "auto" 是选择器里的特殊行:允许对话模型在提供商列表内自选模型。
291
- const wantedModel = String(wanted.model || '').trim();
974
+ let wantedModel = String(wanted.model || '').trim();
975
+ if (wantedModel === LEGACY_OPENROUTER_FLUX && provider && isOfficialOpenRouter(provider.adapter, provider.baseUrl)) {
976
+ wantedModel = OPENROUTER_FLUX;
977
+ }
292
978
  const keepModel = wantedModel === 'auto' || (provider && provider.models.includes(wantedModel));
293
979
  out.active = { providerId: provider ? provider.id : '', model: keepModel ? wantedModel : '' };
294
980
  out.defaults = normalizeDefaults(raw.defaults);
@@ -297,6 +983,8 @@ export function normalizeConfig(raw) {
297
983
  /** DSH 凭据库(ctx.credentials)里的引用名;只允许我们自己的 MO_IMAGE_ 命名空间。 */
298
984
  const KEY_REF_PREFIX = 'MO_IMAGE_';
299
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}$/;
300
988
  export function createConfigStore(options) {
301
989
  return {
302
990
  configFile: options.configFile,
@@ -304,10 +992,12 @@ export function createConfigStore(options) {
304
992
  logHost: options.logHost,
305
993
  credentialsAccessor: options.credentialsAccessor,
306
994
  cache: null,
995
+ activeStates: new WeakMap(),
307
996
  stamp: '',
308
997
  webOriginHost: '',
309
998
  keyMigration: null,
310
- writeQueue: Promise.resolve()
999
+ writeQueue: Promise.resolve(),
1000
+ saveQueue: Promise.resolve()
311
1001
  };
312
1002
  }
313
1003
  export function credentialsService(store) {
@@ -386,14 +1076,15 @@ export function assertLocalRequest(store, req, write) {
386
1076
  }
387
1077
  }
388
1078
  /** 系统提示词节是同步渲染的,这里用 mtime 缓存一份配置副本。 */
389
- export function rememberConfig(store, config) {
1079
+ export function rememberConfig(store, config, stamp = '') {
390
1080
  store.cache = config;
391
- store.stamp = '';
1081
+ store.stamp = stamp;
392
1082
  }
1083
+ const configStampOf = (info) => [info.mtimeMs, info.ctimeMs, info.size, info.ino].join(':');
393
1084
  export function readConfigSync(store) {
394
1085
  try {
395
1086
  const info = statSync(store.configFile);
396
- const stamp = info.mtimeMs + ':' + info.size;
1087
+ const stamp = configStampOf(info);
397
1088
  if (!store.cache || stamp !== store.stamp) {
398
1089
  store.cache = normalizeConfig(JSON.parse(readFileSync(store.configFile, 'utf8')));
399
1090
  store.stamp = stamp;
@@ -403,44 +1094,56 @@ export function readConfigSync(store) {
403
1094
  }
404
1095
  return store.cache;
405
1096
  }
406
- /** 当前选中的生图模型;编辑也用同一个(严格模式,不做任何回退)。 */
407
- export function activeImageState(store, snapshot) {
408
- const config = snapshot || readConfigSync(store);
409
- const provider = (config.providers || []).find((item) => item.id === config.active.providerId);
410
- const model = String((config.active && config.active.model) || '').trim();
411
- if (!provider || !model) return null;
1097
+ export function modelImageState(provider, model, defaults, canEdit) {
412
1098
  let adapter = null;
413
1099
  try { adapter = resolveAdapter(provider, model); } catch (_error) { adapter = null; }
414
- const models = provider.models || [];
415
- const editModels = editCapableModels(provider, models);
416
- const sizeSpec = adapter && adapter.size ? adapter.size : null;
417
- const fixedSize = config.defaults.auto === false;
418
- const sizeRequest = adapter ? resolveSizeRequest(adapter, model, config.defaults, {}) : null;
419
- const sizeOptions = sizeSpec
420
- ? (Array.isArray(sizeSpec.tiers) && sizeSpec.tiers.length
421
- ? sizeSpec.tiers.map((tier) => String(tier.value))
422
- : (Array.isArray(sizeSpec.allowed) ? sizeSpec.allowed.map(String) : []))
423
- : [];
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);
424
1108
  return {
425
- provider, model, adapter, models, editModels,
426
- canEdit: model === 'auto' ? editModels.length > 0 : editCapableModels(provider, [model]).length > 0,
1109
+ provider, model, adapter, canEdit,
427
1110
  editModel: model, editAdapter: adapter,
428
- // 只有 ComfyUI 部署才有工作流参数;用户关掉暴露时不返回。
429
1111
  workflowParams: workflowParamsOf(provider, model, adapter),
430
- // 自动尺寸下模型可以自己填 size;固定尺寸下选择器说了算。
1112
+ qualitySpec: adapter ? qualityOptionsFor(provider, model, adapter) : null,
1113
+ quality: adapter ? qualityForAdapter(provider, model, resolveQuality(defaults), adapter) : undefined,
431
1114
  sizeMode: fixedSize ? 'fixed' : 'auto',
432
- size: fixedSize ? (sizeRequest ? sizeRequest.arg : resolveSizeArg(config.defaults)) : undefined,
433
- strict: config.defaults.strict === true,
1115
+ size: fixedSize ? (sizeRequest ? sizeRequest.arg : resolveSizeArg(defaults)) : undefined,
1116
+ strict: defaults.strict === true,
434
1117
  control: sizeRequest ? sizeRequest.control : '',
435
1118
  sizeOptions: sizeOptions.length ? sizeOptions : undefined,
436
- promptOptimization: config.defaults.promptOptimization !== false, defaults: config.defaults
1119
+ promptOptimization: defaults.promptOptimization !== false, defaults
437
1120
  };
438
1121
  }
439
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
+
440
1143
  /** 凭据解析:状态服务与配置页共用同一套“哪里算有 Key”的口径。 */
441
1144
  export async function resolveStatusKey(store, provider) {
442
1145
  if (!provider) return { ok: false, source: '', ref: '' };
443
- if (provider.optionalKey) return { ok: true, source: 'optional', ref: '' };
1146
+ if (provider.optionalKey || provider.auth?.mode === 'none') return { ok: true, source: 'optional', ref: '' };
444
1147
  const ref = validKeyRef(provider.apiKeyEnv);
445
1148
  const credentials = credentialsService(store);
446
1149
  if (ref && credentials && typeof credentials.describe === 'function') {
@@ -465,33 +1168,130 @@ export async function describeImageStatus(store, version = "0.0.0") {
465
1168
  return buildImageStatus({ config, version: version, key });
466
1169
  }
467
1170
 
468
- /** 当前模型的工作流可调参数;非 ComfyUI 或用户逐项关闭时不返回。 */
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
+ */
469
1219
  export function workflowParamsOf(provider, model, adapter) {
470
1220
  try {
471
1221
  if (!adapter) return undefined;
472
1222
  const options = provider && provider.modelOptions ? provider.modelOptions : null;
473
1223
  if (!options || typeof options !== 'object') return undefined;
474
- if (adapter.id === 'a1111') {
475
- // A1111 没有工作流,参数清单固定;默认全关,只返回用户勾上的。
476
- const own = options[model];
477
- const source = own && own.expose ? own : Object.values(options).find((entry) => entry && entry.expose);
478
- const expose = (source && source.expose) || {};
479
- const exposed = A1111_PARAMS.filter((param) => expose[param.name] === true);
480
- return exposed.length ? exposed : undefined;
481
- }
482
- if (adapter.id !== 'comfyui') return undefined;
483
- const entry = options[model];
484
- if (!entry || !Array.isArray(entry.params)) return undefined;
485
- const expose = entry.expose && typeof entry.expose === 'object' ? entry.expose : {};
486
- const exposed = entry.params.filter((param) => {
487
- if (!param) return false;
488
- const explicit = expose[param.name];
489
- if (explicit !== undefined) return explicit !== false;
490
- return DEFAULT_EXPOSED.has(param.name);
491
- });
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
+ }
492
1268
  return exposed.length ? exposed : undefined;
493
1269
  } catch (_error) { return undefined; }
494
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
+ }
495
1295
  export function canUseCredentials(store) {
496
1296
  const credentials = credentialsService(store);
497
1297
  return !!(credentials && typeof credentials.describe === 'function' && typeof credentials.resolve === 'function' && typeof credentials.set === 'function');
@@ -518,15 +1318,38 @@ export async function publicConfig(store, config) {
518
1318
  }));
519
1319
  return Object.assign({}, config, { providers: providers });
520
1320
  }
521
- /** 选择器用的模型能力表:每个模型可用哪些质量档、尺寸控件长什么样。 */
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
+ /** 选择器用的模型能力表:每个模型可用哪些质量档、尺寸控件长什么样、参考图默认发到哪。 */
522
1340
  export function capabilityManifest(config) {
523
1341
  return (config.providers || []).map((provider) => ({
524
1342
  providerId: provider.id,
525
1343
  models: (provider.models || []).map((model) => {
526
1344
  let adapter = null;
527
1345
  let quality = null;
528
- try { adapter = resolveAdapter(provider, model); quality = qualityOptionsFor(adapter, model); } catch (_error) { adapter = null; quality = null; }
529
- return { model: model, quality: quality, size: sizeSpecFor(adapter, model) };
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
+ };
530
1353
  })
531
1354
  }));
532
1355
  }
@@ -538,17 +1361,15 @@ export async function migrateConfigKeys(store, input) {
538
1361
  if (!canUseCredentials(store)) return input;
539
1362
  const credentials = credentialsService(store);
540
1363
  const config = normalizeConfig(input);
1364
+ const reserved = new Set(config.providers.map((provider) => provider.apiKeyEnv).filter(Boolean));
541
1365
  const used = new Set();
542
1366
  let migrated = 0;
543
1367
  let changed = false;
544
1368
  for (const provider of config.providers) {
545
- let ref = validKeyRef(provider.apiKeyEnv);
546
- if (!ref) {
547
- ref = deriveKeyRef(provider.id, used);
548
- provider.apiKeyEnv = ref;
549
- changed = true;
550
- } else if (used.has(ref)) {
551
- ref = deriveKeyRef(provider.id, used);
1369
+ let ref = provider.apiKeyEnv;
1370
+ if (!ref || used.has(ref)) {
1371
+ ref = deriveKeyRef(provider.id, reserved);
1372
+ reserved.add(ref);
552
1373
  provider.apiKeyEnv = ref;
553
1374
  changed = true;
554
1375
  }
@@ -575,20 +1396,58 @@ export function migrateKeysOnce(store, config) {
575
1396
  if (!store.keyMigration) store.keyMigration = migrateConfigKeys(store, config).finally(() => { store.keyMigration = null; });
576
1397
  return store.keyMigration;
577
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
+
578
1418
  export async function readConfig(store) {
579
1419
  try {
580
- if (!existsSync(store.configFile)) {
581
- const empty = emptyConfig();
582
- rememberConfig(store, empty);
583
- return empty;
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);
584
1428
  }
585
- let config = normalizeConfig(JSON.parse(await readFile(store.configFile, 'utf8')));
586
1429
  if (hasLegacyKeys(config) && canUseCredentials(store)) {
587
- try { config = await migrateKeysOnce(store, config); } catch (error) { store.logHost('config key migration failed: ' + String(error && error.message ? error.message : error)); }
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
+ }
588
1444
  }
589
- rememberConfig(store, config);
590
1445
  return config;
591
- } catch (_error) { return emptyConfig(); }
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
+ }
592
1451
  }
593
1452
  export async function writeConfig(store, config) {
594
1453
  const next = normalizeConfig(config);
@@ -601,7 +1460,9 @@ export async function writeConfig(store, config) {
601
1460
  } finally {
602
1461
  try { await unlink(tempFile); } catch (_error) { /* rename 成功后临时文件已不存在 */ }
603
1462
  }
604
- rememberConfig(store, next);
1463
+ let stamp = '';
1464
+ try { stamp = configStampOf(await stat(store.configFile)); } catch (_error) { /* refresh on next read */ }
1465
+ rememberConfig(store, next, stamp);
605
1466
  return next;
606
1467
  });
607
1468
  store.writeQueue = task.catch(() => {});
@@ -609,6 +1470,7 @@ export async function writeConfig(store, config) {
609
1470
  }
610
1471
  /** 每次请求才解析一次密钥;不在内存里长期缓存,轮换后下一请求生效。 */
611
1472
  export async function resolveProviderCredential(store, provider) {
1473
+ if (provider.auth?.mode === 'none') return provider;
612
1474
  const ref = validKeyRef(provider.apiKeyEnv);
613
1475
  const credentials = credentialsService(store);
614
1476
  if (ref) {
@@ -633,36 +1495,84 @@ export async function resolveProviderCredential(store, provider) {
633
1495
  );
634
1496
  }
635
1497
  /** 保存配置前先把每个 provider 的新 key 写进凭据库,配置文件只保留 apiKeyEnv。 */
636
- export async function saveConfigWithCredentials(store, raw) {
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
+ }
637
1540
  const incoming = normalizeConfig(raw);
638
1541
  const current = await readConfig(store);
639
1542
  const credentials = credentialsService(store);
640
1543
  const canStore = !!(credentials && typeof credentials.set === 'function');
641
1544
  const canDescribe = !!(credentials && typeof credentials.describe === 'function');
642
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);
643
1553
  const used = new Set();
1554
+ const originals = new Map();
1555
+ const credentialChanges = [];
644
1556
  const providers = [];
645
1557
  for (const provider of incoming.providers) {
646
1558
  const old = currentById.get(provider.id);
647
- let ref = validKeyRef(provider.apiKeyEnv) || validKeyRef(old && old.apiKeyEnv) || deriveKeyRef(provider.id, used);
648
- if (used.has(ref)) ref = deriveKeyRef(provider.id, used);
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
+ }
649
1564
  used.add(ref);
650
1565
  provider.apiKeyEnv = ref;
651
1566
  const newKey = String(provider.key || '').trim();
652
1567
  delete provider.key;
653
1568
  if (newKey) {
654
1569
  if (!canStore) throw localizedError(new Error('DSH 凭据服务未挂载,无法安全保存 API Key;请确认 base composition 包含 dsh-credentials-local。'), 'config.credentialsUnavailable');
655
- try {
656
- await credentials.set(ref, newKey);
657
- } catch (error) {
658
- const message = String(error && error.message ? error.message : error);
659
- throw localizedError(new Error('保存 API Key 失败:' + message), 'config.credentialSaveFailed', { message: message });
660
- }
1570
+ credentialChanges.push({ ref, value: newKey, legacy: false });
661
1571
  } else if (old && old.key) {
662
1572
  if (canStore && canDescribe) {
663
1573
  try {
664
1574
  const info = await credentials.describe(ref);
665
- if (!credentialIsStored(info)) await credentials.set(ref, old.key);
1575
+ if (!credentialIsStored(info)) credentialChanges.push({ ref, value: old.key, legacy: true });
666
1576
  } catch (error) {
667
1577
  const message = String(error && error.message ? error.message : error);
668
1578
  throw localizedError(new Error('旧 API Key 迁移失败:' + message), 'config.legacyKeyMigrationFailed', { message: message });
@@ -673,6 +1583,38 @@ export async function saveConfigWithCredentials(store, raw) {
673
1583
  }
674
1584
  providers.push(provider);
675
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
+ }
676
1618
  if (credentials && typeof credentials.unset === 'function') {
677
1619
  const kept = new Set(providers.map((provider) => provider.id));
678
1620
  for (const old of current.providers) {
@@ -682,11 +1624,5 @@ export async function saveConfigWithCredentials(store, raw) {
682
1624
  try { await credentials.unset(ref); } catch (error) { store.logHost('credential removal failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
683
1625
  }
684
1626
  }
685
- incoming.providers = providers;
686
- try {
687
- return await writeConfig(store, incoming);
688
- } catch (error) {
689
- const message = String(error && error.message ? error.message : error);
690
- throw localizedError(new Error('保存生图配置失败:' + message), 'config.writeFailed', { message: message });
691
- }
1627
+ return saved;
692
1628
  }