dsh-mo-image 0.5.1 → 0.7.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.
package/lib/adapters.js CHANGED
@@ -17,6 +17,22 @@ import { createRequire } from 'node:module';
17
17
  import { decodePng, encodePng, resizeRgba } from './png-scale.js';
18
18
  import { request } from './net.js';
19
19
  import { localizedError } from './localized-error.js';
20
+ import {
21
+ ASPECT_CHOICES, aspectLabel, nearestAspect, resolutionFor, baseUrlOf, headersFor,
22
+ keyedHeaders, sleep, readJsonResponse, jsonRequest, getPath, sniffType, looksLikeImage,
23
+ base64ToImage, fetchImageUrl, decodeImagePayload, classifyFailure, extractMessage,
24
+ readResponseBytes, MAX_IMAGE_BYTES, imageSizeOf,
25
+ readTaskEnvelope, taskPollUrls, taskStatusOf, taskImageOf, looseImageOf, taskMessageOf
26
+ } from './adapter-kit.js';
27
+ import { OPENAI_ADAPTERS } from './adapters/openai.js';
28
+ import { ASYNC_ADAPTERS } from './adapters/async.js';
29
+ import { CN_ADAPTERS } from './adapters/cn.js';
30
+
31
+ export {
32
+ ASPECT_CHOICES, aspectLabel, nearestAspect, resolutionFor, sniffType, looksLikeImage,
33
+ fetchImageUrl, decodeImagePayload, classifyFailure, extractMessage, readResponseBytes, MAX_IMAGE_BYTES, imageSizeOf,
34
+ readTaskEnvelope, taskPollUrls, taskStatusOf, taskImageOf, looseImageOf, taskMessageOf
35
+ };
20
36
 
21
37
  const require = createRequire(import.meta.url);
22
38
  const DEFAULT_SIZE = '1024x1024';
@@ -34,33 +50,107 @@ export function parseSize(raw) {
34
50
  return { width: width, height: height, text: width + 'x' + height };
35
51
  }
36
52
 
37
- function gcd(a, b) {
38
- let x = Math.abs(a);
39
- let y = Math.abs(b);
40
- while (y) {
41
- const t = x % y;
42
- x = y;
43
- y = t;
53
+ /**
54
+ * 合并出该模型真正适用的尺寸策略:基础策略 + sizeByModel 里第一个命中的覆盖。
55
+ * 同一平台内部规则按模型分叉(Ark 5.5 只有 1K/1.5K/2K,魔搭 Qwen-Image 上限 1664),
56
+ * 所以能力必须按模型算,不能只看适配器。
57
+ */
58
+ export function sizePolicyFor(adapter, model) {
59
+ const base = adapter && adapter.size && typeof adapter.size === 'object' ? adapter.size : {};
60
+ const overrides = adapter && Array.isArray(adapter.sizeByModel) ? adapter.sizeByModel : [];
61
+ const id = String(model || '');
62
+ for (const entry of overrides) {
63
+ if (!entry || !entry.size || !(entry.match instanceof RegExp)) continue;
64
+ entry.match.lastIndex = 0;
65
+ if (id && entry.match.test(id)) return Object.assign({}, base, entry.size);
44
66
  }
45
- return x || 1;
67
+ return base;
46
68
  }
47
69
 
48
- function aspectLabel(width, height) {
49
- const g = gcd(width, height);
50
- return width / g + ':' + height / g;
70
+ /**
71
+ * 下发给选择器的尺寸能力:控件形态 + 候选 + hint 代码。
72
+ * 客户端只按这个渲染,不再自己判断"这个模型收不收宽高"。
73
+ */
74
+ export function sizeSpecFor(adapter, model) {
75
+ if (!adapter) return { control: 'wh', aspects: [], tiers: [], custom: true, wire: [], stitch: false, hint: '' };
76
+ const policy = sizePolicyFor(adapter, model);
77
+ const allowed = Array.isArray(policy.allowed) ? policy.allowed.filter(Boolean).map(String) : [];
78
+ const control = String(policy.control || (allowed.length ? 'preset' : (policy.style === 'aspect' ? 'aspect' : 'wh')));
79
+ const tiers = (Array.isArray(policy.tiers) ? policy.tiers : [])
80
+ .filter((item) => item && item.value)
81
+ .map((item) => ({ value: String(item.value), pixels: Number(item.pixels) || 0 }));
82
+ return {
83
+ control: control,
84
+ aspects: Array.isArray(policy.aspects) ? policy.aspects.map(String) : [],
85
+ tiers: tiers.length ? tiers : allowed.map((value) => ({ value: value, pixels: 0 })),
86
+ custom: policy.custom === true,
87
+ wire: Array.isArray(policy.wire) ? policy.wire.map(String) : [],
88
+ stitch: policy.stitch === true,
89
+ hint: String(policy.hint || '')
90
+ };
51
91
  }
52
92
 
53
- function settle(size, adjusted, reason, requested) {
54
- const text = size && size.text ? size.text : String(size || DEFAULT_SIZE);
55
- const parsed = size && size.width ? size : parseSize(text);
56
- return {
93
+ /** 档位名("2K")解析成 {value, pixels};不是档位就退成 WxH 像素。 */export function parseTier(adapter, raw, model) {
94
+ const policy = sizePolicyFor(adapter, model);
95
+ const tiers = Array.isArray(policy.tiers) ? policy.tiers : [];
96
+ const text = String(raw || '').trim();
97
+ if (text) {
98
+ const wanted = text.toLowerCase();
99
+ const hit = tiers.find((item) => item && String(item.value || '').toLowerCase() === wanted);
100
+ const pixels = hit ? Number(hit.pixels) : 0;
101
+ if (hit && pixels > 0) return { value: String(hit.value), pixels: pixels };
102
+ }
103
+ const parsed = parseSize(text);
104
+ return parsed
105
+ ? { value: parsed.text, pixels: parsed.width * parsed.height, width: parsed.width, height: parsed.height }
106
+ : null;
107
+ }
108
+
109
+ /** 按像素预算挑最近的档位:只挑最近的可用档,不做阈值猜测。 */
110
+ export function nearestTier(tiers, pixels) {
111
+ const list = Array.isArray(tiers) ? tiers : [];
112
+ const target = Math.log(Math.max(1, Number(pixels) || 0));
113
+ let best = null;
114
+ let bestScore = Infinity;
115
+ for (const item of list) {
116
+ const value = Number(item && item.pixels);
117
+ if (!(value > 0)) continue;
118
+ const score = Math.abs(Math.log(value) - target);
119
+ if (score < bestScore) { bestScore = score; best = item; }
120
+ }
121
+ return best;
122
+ }
123
+
124
+ function round8(value) {
125
+ return Math.max(8, Math.round(Number(value) / 8) * 8);
126
+ }
127
+
128
+ /** 比例 + 像素预算 → 具体宽高(两侧对齐 8,会直接当成严格模式的落盘目标)。 */
129
+ export function sizeForAspect(aspect, budget) {
130
+ const parts = String(aspect || '1:1').split(':');
131
+ const a = Number(parts[0]) || 1;
132
+ const b = Number(parts[1]) || 1;
133
+ const total = Number(budget) > 0 ? Number(budget) : 1024 * 1024;
134
+ return { width: round8(Math.sqrt((total * a) / b)), height: round8(Math.sqrt((total * b) / a)) };
135
+ }
136
+
137
+ function settle(size, adjusted, reason, requested, extra) {
138
+ const text = size && size.text ? size.text : (size && size.size ? size.size : String(size || DEFAULT_SIZE));
139
+ const width = size && Number(size.width) ? Math.round(Number(size.width)) : 0;
140
+ const height = size && Number(size.height) ? Math.round(Number(size.height)) : 0;
141
+ const parsed = width && height ? { width: width, height: height } : parseSize(text);
142
+ return Object.assign({
57
143
  size: text,
58
144
  width: parsed ? parsed.width : 0,
59
145
  height: parsed ? parsed.height : 0,
60
146
  adjusted: !!adjusted,
61
147
  reason: reason || '',
62
- requested: requested || null
63
- };
148
+ requested: requested || null,
149
+ // 比例/档位/是否把尺寸写进提示词:编码器与严格模式都要用。
150
+ aspect: '',
151
+ tier: '',
152
+ stitch: false
153
+ }, extra || {});
64
154
  }
65
155
 
66
156
  function nearestAllowed(allowed, width, height) {
@@ -82,7 +172,7 @@ function nearestAllowed(allowed, width, height) {
82
172
  return best;
83
173
  }
84
174
 
85
- function clampPixels(width, height, minPixels, maxPixels, multiple) {
175
+ function clampPixels(width, height, minPixels, maxPixels, multiple, minSide, maxSide) {
86
176
  let w = width;
87
177
  let h = height;
88
178
  if (minPixels && w * h < minPixels) {
@@ -95,6 +185,18 @@ function clampPixels(width, height, minPixels, maxPixels, multiple) {
95
185
  w = Math.floor(w * k);
96
186
  h = Math.floor(h * k);
97
187
  }
188
+ // 有的网关只限制单边(魔搭是每边 [64, 2048]),按比例缩放到区间内,别把比例压扁。
189
+ // 先补下限再收上限:两个方向打架时(极端长宽比)宁可不超上限,否则一定被网关拒。
190
+ if (minSide && Math.min(w, h) < minSide) {
191
+ const k = minSide / Math.min(w, h);
192
+ w = Math.ceil(w * k);
193
+ h = Math.ceil(h * k);
194
+ }
195
+ if (maxSide && Math.max(w, h) > maxSide) {
196
+ const k = maxSide / Math.max(w, h);
197
+ w = Math.floor(w * k);
198
+ h = Math.floor(h * k);
199
+ }
98
200
  w = Math.max(multiple, Math.round(w / multiple) * multiple);
99
201
  h = Math.max(multiple, Math.round(h / multiple) * multiple);
100
202
  return { width: w, height: h };
@@ -104,80 +206,135 @@ function clampPixels(width, height, minPixels, maxPixels, multiple) {
104
206
  * 把用户要的尺寸落成该模型真正接受的尺寸。
105
207
  * 返回 { size, width, height, adjusted, reason, requested, rejected? }
106
208
  */
107
- export function fitSize(adapter, rawSize) {
108
- const policy = adapter && adapter.size ? adapter.size : {};
209
+ export function fitSize(adapter, request, model) {
210
+ const policy = sizePolicyFor(adapter, model);
109
211
  const allowed = Array.isArray(policy.allowed) ? policy.allowed : null;
212
+ // allowCustom:allowed 只是推荐值,白名单外照发(只受像素/倍数约束)。
213
+ const allowCustom = policy.allowCustom === true;
110
214
  const fallback = parseSize(policy.default || DEFAULT_SIZE) || parseSize(DEFAULT_SIZE);
111
- const requestedRaw = String(rawSize || '').trim();
215
+ const objectRequest = request && typeof request === 'object' ? request : null;
216
+ const requestedRaw = String(objectRequest ? (objectRequest.text || '') : (request === undefined || request === null ? '' : request)).trim();
112
217
  const requestedText = requestedRaw.toLowerCase().replace(/[×*]/g, 'x').replace(/\s+/g, '');
113
218
  const requested = parseSize(requestedText);
219
+ // 档位与比例在这里补齐:编码器只要读 fitted.tier / fitted.aspect,不必自己查策略。
220
+ const done = (value) => withTierAspect(policy, value);
114
221
 
115
222
  if (!requestedText || requestedText === 'none' || requestedText === 'auto') {
116
223
  // 用户选了「自动」:请求里干脆不带尺寸,让模型自己决定
117
- return { size: 'none', width: 0, height: 0, adjusted: false, reason: '', requested: null, omit: true };
224
+ return Object.assign(settle('none', false, '', null), { size: 'none', width: 0, height: 0, omit: true });
225
+ }
226
+
227
+ // 档位名("2K"):size 保留档位名(编码要原样发上去),宽高取该档像素。
228
+ const tier = parseTier(adapter, requestedText, model);
229
+ if (tier && !requested && tier.value) {
230
+ const side = Math.round(Math.sqrt(tier.pixels)) || 0;
231
+ return done(settle({ text: tier.value, width: side, height: side }, false, '', null, { tier: tier.value }));
118
232
  }
119
233
 
120
234
  if (!requested) {
121
- return settle(fallback, !!requestedRaw, requestedRaw ? '尺寸无法识别,改用 ' + fallback.text : '', null);
235
+ return done(settle(fallback, !!requestedRaw, requestedRaw ? '尺寸无法识别,改用 ' + fallback.text : '', null));
122
236
  }
123
237
 
124
- if (allowed && allowed.length) {
238
+ if (allowed && allowed.length && !allowCustom) {
125
239
  if (allowed.includes(requested.text)) {
126
- return settle(requested, false, '', requested);
240
+ return done(settle(requested, false, '', requested));
127
241
  }
128
242
  if (policy.onUnsupported === 'reject') {
129
- return Object.assign(settle(requested, false, '', requested), {
243
+ return done(Object.assign(settle(requested, false, '', requested), {
130
244
  rejected: true,
131
245
  reason: '该模型不支持 ' + requested.text + ',可用尺寸:' + allowed.join(' / ')
132
- });
246
+ }));
133
247
  }
134
248
  const chosen = nearestAllowed(allowed, requested.width, requested.height) || fallback;
135
- return settle(chosen, true, requested.text + ' → ' + chosen.text, requested);
249
+ return done(settle(chosen, true, requested.text + ' → ' + chosen.text, requested));
136
250
  }
137
251
 
138
252
  const multiple = Number(policy.multiple) || 1;
139
253
  const minPixels = Number(policy.minPixels) || 0;
140
254
  const maxPixels = Number(policy.maxPixels) || 0;
141
- const clamped = clampPixels(requested.width, requested.height, minPixels, maxPixels, multiple);
255
+ const minSide = Number(policy.minSide) || 0;
256
+ const maxSide = Number(policy.maxSide) || 0;
257
+ const clamped = clampPixels(requested.width, requested.height, minPixels, maxPixels, multiple, minSide, maxSide);
142
258
  const text = clamped.width + 'x' + clamped.height;
143
- return settle({ width: clamped.width, height: clamped.height, text: text }, text !== requested.text,
144
- text !== requested.text ? requested.text + ' → ' + text : '', requested);
145
- }
146
-
147
- /** 尺寸被上游拒了以后,往上抬一档再试。 */
148
- export function escalateSize(adapter, fitted) {
149
- if (fitted && fitted.omit) return fitted;
150
- const policy = adapter && adapter.size ? adapter.size : {};
151
- const allowed = Array.isArray(policy.allowed) ? policy.allowed : null;
152
- const currentPixels = (fitted.width || 0) * (fitted.height || 0);
153
- if (allowed && allowed.length) {
154
- let best = null;
155
- for (const item of allowed) {
156
- const parsed = parseSize(item);
157
- if (!parsed) continue;
158
- if (parsed.width * parsed.height > currentPixels && (!best || parsed.width * parsed.height < best.width * best.height)) best = parsed;
259
+ return done(settle({ width: clamped.width, height: clamped.height, text: text }, text !== requested.text,
260
+ text !== requested.text ? requested.text + ' → ' + text : '', requested));
261
+ }
262
+
263
+ /** 给落位后的尺寸补上档位与比例:编码器就不必自己再查一遍策略。 */
264
+ function withTierAspect(policy, fitted) {
265
+ if (!fitted || fitted.omit || !fitted.width || !fitted.height) return fitted;
266
+ if (!fitted.tier) {
267
+ const tiers = Array.isArray(policy.tiers) ? policy.tiers : [];
268
+ if (tiers.length) {
269
+ const tier = nearestTier(tiers, fitted.width * fitted.height);
270
+ if (tier) fitted.tier = String(tier.value);
159
271
  }
160
- if (best) return settle(best, true, '上游拒绝 ' + fitted.size + ',抬到 ' + best.text, fitted.requested);
161
272
  }
162
- const width = Math.max(1, Math.round((fitted.width || 1024) * 1.5));
163
- const height = Math.max(1, Math.round((fitted.height || 1024) * 1.5));
164
- if ((fitted.width || 0) * (fitted.height || 0) < 1024 * 1024) {
165
- // 没有尺寸白名单时,常见的最小预算是 1MP,一步抬到位,省一次往返
166
- const k = Math.sqrt((1024 * 1024) / Math.max(1, (fitted.width || 1024) * (fitted.height || 1024)));
167
- const w = Math.round((fitted.width || 1024) * k);
168
- const h = Math.round((fitted.height || 1024) * k);
169
- return settle({ width: w, height: h, text: w + 'x' + h }, true, '上游拒绝 ' + fitted.size + ',抬到 ' + w + 'x' + h, fitted.requested);
273
+ if (!fitted.aspect) {
274
+ const aspects = Array.isArray(policy.aspects) ? policy.aspects : null;
275
+ // 只处理冒号格式的比例表;Ideogram 这种 16x9 的由它自己的编码器转换。
276
+ if (aspects && aspects.length && String(aspects[0]).includes(':')) {
277
+ fitted.aspect = nearestAspect(fitted.width, fitted.height, aspects);
278
+ }
170
279
  }
171
- return settle({ width: width, height: height, text: width + 'x' + height }, true, '上游拒绝 ' + fitted.size + ',抬到 ' + width + 'x' + height, fitted.requested);
280
+ return fitted;
281
+ }
282
+
283
+ function megapixels(value) {
284
+ return (Number(value) / 1e6).toFixed(2);
285
+ }
286
+
287
+ /**
288
+ * 上游拒绝了尺寸以后,告诉用户这个模型到底能吃什么。
289
+ * 顺序:白名单 → 档位名 → 像素区间 → 单边区间 → 倍数 → 根本不收尺寸。
290
+ */
291
+ export function sizeHintText(adapter, model) {
292
+ const policy = sizePolicyFor(adapter, model);
293
+ const allowed = Array.isArray(policy.allowed) ? policy.allowed.filter(Boolean) : [];
294
+ if (allowed.length) return '支持的尺寸:' + allowed.join(' / ');
295
+ const tiers = Array.isArray(policy.tiers) ? policy.tiers.filter((item) => item && item.value) : [];
296
+ if (tiers.length) return '支持的档位:' + tiers.map((item) => item.value).join(' / ');
297
+ const parts = [];
298
+ const minPixels = Number(policy.minPixels) || 0;
299
+ const maxPixels = Number(policy.maxPixels) || 0;
300
+ const minSide = Number(policy.minSide) || 0;
301
+ const maxSide = Number(policy.maxSide) || 0;
302
+ const multiple = Number(policy.multiple) || 1;
303
+ if (minPixels && maxPixels) parts.push('总像素 ' + megapixels(minPixels) + '–' + megapixels(maxPixels) + 'MP');
304
+ else if (minPixels) parts.push('总像素不少于 ' + megapixels(minPixels) + 'MP');
305
+ else if (maxPixels) parts.push('总像素不超过 ' + megapixels(maxPixels) + 'MP');
306
+ if (minSide && maxSide) parts.push('每边 ' + minSide + '–' + maxSide + 'px');
307
+ else if (minSide) parts.push('每边不少于 ' + minSide + 'px');
308
+ else if (maxSide) parts.push('每边不超过 ' + maxSide + 'px');
309
+ if (multiple > 1) parts.push('宽高需为 ' + multiple + ' 的倍数');
310
+ const wire = Array.isArray(policy.wire) ? policy.wire : null;
311
+ if (!parts.length) return wire && !wire.length ? '该模型不接受尺寸参数' : '该模型没有声明尺寸范围';
312
+ return '支持的尺寸:' + parts.join(',');
172
313
  }
173
314
 
174
315
  /* -------------------------------------------------------------- adapters */
175
316
 
176
- function encodeSize(adapter, fitted) {
177
- const policy = adapter.size || {};
317
+ function encodeSize(adapter, fitted, model) {
318
+ const policy = sizePolicyFor(adapter, model);
178
319
  const field = policy.field || 'size';
179
320
  const style = policy.style || 'string';
180
321
  if (fitted.omit || fitted.size === 'none') return {};
322
+ // 少数平台只认档位名(火山方舟的 1K/1.5K/2K);已经就是档位就原样发,
323
+ // 是像素且贴近某一档才换成档位名,其余照发像素。
324
+ const tiers = Array.isArray(policy.tiers) && policy.tiers.length
325
+ ? policy.tiers
326
+ : (Array.isArray(policy.presets) ? policy.presets : null);
327
+ if (tiers) {
328
+ const parsed = parseSize(fitted.size);
329
+ const isLabel = !parsed && String(fitted.size || '').trim() !== '';
330
+ if (isLabel) return { [field]: fitted.size };
331
+ const pixels = (fitted.width || 1024) * (fitted.height || 1024);
332
+ for (const tier of tiers) {
333
+ if (!tier || !tier.pixels) continue;
334
+ if (Math.abs(pixels - tier.pixels) / tier.pixels <= 0.12) return { [field]: tier.value };
335
+ }
336
+ return { [field]: fitted.size };
337
+ }
181
338
  if (style === 'width-height') return { width: fitted.width, height: fitted.height };
182
339
  if (style === 'aspect') {
183
340
  const aspects = policy.aspects || ['1:1'];
@@ -217,8 +374,8 @@ export function qualityOptionsFor(adapter, model) {
217
374
  return { label: spec.label || '质量', options, default: fallback };
218
375
  }
219
376
 
220
- export function qualityForAdapter(adapter, value) {
221
- const spec = qualityOptionsFor(adapter);
377
+ export function qualityForAdapter(adapter, value, model) {
378
+ const spec = qualityOptionsFor(adapter, model);
222
379
  if (!spec) return undefined;
223
380
  const raw = String(value || '').trim().toLowerCase();
224
381
  if (raw === 'off') return 'off';
@@ -253,6 +410,21 @@ const NON_IMAGE_MODEL_KEYWORDS = [
253
410
  ];
254
411
  const EXACT_IMAGE_MODEL_IDS = new Set(['core']);
255
412
 
413
+ const ASPECT_CHOICES_14 = ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9', '1:4', '4:1', '1:8', '8:1'];
414
+
415
+ /** 这些主机有自己的适配器:模型名匹配不能抢在主机匹配前面。 */
416
+ const MAJOR_HOSTS = /(^|\.)openai\.azure\.com$|(^|\.)openrouter\.ai$|(^|\.)bfl\.ai$|(^|\.)queue\.fal\.run$|(^|\.)fal\.run$|(^|\.)falrun\.com$|(^|\.)api\.replicate\.com$/;
417
+
418
+ function hostOfBase(baseUrl) {
419
+ return String(baseUrl || '').replace(/^https?:\/\//i, '').split('/')[0].toLowerCase();
420
+ }
421
+
422
+ /** Ideogram 把模型写进路径:/v2/image/generate/{model}。 */
423
+ function ideogramPath(input) {
424
+ const model = String((input && input.model) || 'ideogram-3').trim().replace(/^\/+/, '') || 'ideogram-3';
425
+ return '/v2/image/generate/' + model;
426
+ }
427
+
256
428
  function normalizeModelId(model) {
257
429
  return String(model || '').trim().toLowerCase().replace(/[_\s./:]+/g, '-');
258
430
  }
@@ -270,57 +442,152 @@ export function filterImageModels(models) {
270
442
  return (Array.isArray(models) ? models : []).filter(isLikelyImageModel);
271
443
  }
272
444
 
273
- const ASPECT_CHOICES = ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9'];
445
+ /* ------------------------------------------------------------ ComfyUI 工作流 */
274
446
 
275
- function nearestAspect(width, height, choices = ASPECT_CHOICES) {
276
- const w = Number(width) || 1024;
277
- const h = Number(height) || 1024;
278
- const target = Math.log(w / h);
279
- let best = choices[0];
280
- let bestScore = Infinity;
281
- for (const item of choices) {
282
- const parts = String(item).split(':');
283
- const a = Number(parts[0]);
284
- const b = Number(parts[1]);
285
- if (!a || !b) continue;
286
- const score = Math.abs(Math.log(a / b) - target);
287
- if (score < bestScore) { bestScore = score; best = item; }
447
+ import { parseWorkflow, uiToApi, analyzeWorkflow, injectByMapping, applyWorkflowParams } from './comfy-workflow.js';
448
+
449
+ const OBJECT_INFO_TTL = 5 * 60 * 1000;
450
+ // 装了很多自定义节点的 ComfyUI,一次 /object_info 就能到 20MB+。
451
+ // 缓存必须有条数与字节上限,否则在设置页来回切换就会把整份签名长期钉在内存里。
452
+ const OBJECT_INFO_LIMIT = 50;
453
+ const OBJECT_INFO_BUDGET = 4 * 1024 * 1024;
454
+
455
+ /** 已完成的签名:key -> { at, bytes, data }。 */
456
+ const objectInfoCache = new Map();
457
+ /** 进行中的签名:key -> Promise。并发的设置页解析、模型列表和工作流执行共用一次请求。 */
458
+ const objectInfoInflight = new Map();
459
+ let objectInfoBytes = 0;
460
+
461
+ /**
462
+ * 凭据版本引用:换了 Key 就不能复用旧权限下取回的签名,所以凭据必须参与缓存键;
463
+ * 但键会长期留在 Map 里,不能出现明文 Key。这里只用长度 + FNV-1a 哈希做版本引用。
464
+ */
465
+ function credentialRef(provider) {
466
+ const key = String((provider && provider.key) || '');
467
+ if (!key) return 'anon';
468
+ let hash = 0x811c9dc5;
469
+ for (let i = 0; i < key.length; i++) {
470
+ hash ^= key.charCodeAt(i);
471
+ hash = Math.imul(hash, 0x01000193) >>> 0;
288
472
  }
289
- return best;
473
+ return key.length + ':' + hash.toString(16);
290
474
  }
291
475
 
292
- function resolutionFor(width, height) {
293
- const pixels = (Number(width) || 1024) * (Number(height) || 1024);
294
- if (pixels >= 2800 * 2800) return '4k';
295
- if (pixels >= 1800 * 1800) return '2k';
296
- return '1k';
476
+ /** 缓存键:baseUrl + 节点 + 字段 + 凭据版本。全量读没有节点/字段,两段留空。 */
477
+ function objectInfoKey(base, provider, node, field) {
478
+ return [String(base || ''), String(node || ''), String(field || ''), credentialRef(provider)].join('\u0000');
297
479
  }
298
480
 
299
- function keyedHeaders(provider, name, multipart) {
300
- const key = String((provider && provider.key) || '').trim();
301
- return headersFor(Object.assign({}, provider, { key: '' }), multipart, key ? { [name]: key } : {});
481
+ function evictObjectInfo(key) {
482
+ const entry = objectInfoCache.get(key);
483
+ if (!entry) return;
484
+ objectInfoBytes -= entry.bytes;
485
+ objectInfoCache.delete(key);
302
486
  }
303
487
 
304
- /* ------------------------------------------------------------ ComfyUI 工作流 */
488
+ /** 过期项在每次读写时清掉;超容量时按写入顺序淘汰最旧的。 */
489
+ function pruneObjectInfo(now) {
490
+ for (const [key, entry] of objectInfoCache) {
491
+ if (now - entry.at >= OBJECT_INFO_TTL) evictObjectInfo(key);
492
+ }
493
+ // 留一格给马上要写入的条目,避免刚放进来的缓存立刻被自己挤掉。
494
+ while (objectInfoCache.size >= OBJECT_INFO_LIMIT) {
495
+ const oldest = objectInfoCache.keys().next().value;
496
+ if (oldest === undefined) break;
497
+ evictObjectInfo(oldest);
498
+ }
499
+ }
500
+
501
+ function rememberObjectInfo(key, data) {
502
+ let bytes = 0;
503
+ try {
504
+ // 只需要量级判断:按 JSON 字符长度估算,不做逐字节统计。
505
+ bytes = JSON.stringify(data)?.length || 0;
506
+ } catch (_error) {
507
+ bytes = 0;
508
+ }
509
+ pruneObjectInfo(Date.now());
510
+ // Map 的插入顺序就是淘汰顺序:重写同一个键时先删再加,让它回到队尾。
511
+ evictObjectInfo(key);
512
+ objectInfoCache.set(key, { at: Date.now(), bytes, data });
513
+ objectInfoBytes += bytes;
514
+ // 超预算先淘汰旧条目,但永远保留刚写入的一条,否则超大签名会一次都缓存不上。
515
+ while (objectInfoBytes > OBJECT_INFO_BUDGET && objectInfoCache.size > 1) {
516
+ const oldest = objectInfoCache.keys().next().value;
517
+ if (oldest === undefined) break;
518
+ evictObjectInfo(oldest);
519
+ }
520
+ }
521
+
522
+ /** 同一个 key 的进行中请求只发一次;失败时占位也必须清掉(失败不缓存,下次还能重试)。 */
523
+ function trackObjectInfo(key, task) {
524
+ const pending = objectInfoInflight.get(key);
525
+ if (pending) return pending;
526
+ let tracked;
527
+ tracked = task.finally(() => {
528
+ if (objectInfoInflight.get(key) === tracked) objectInfoInflight.delete(key);
529
+ });
530
+ objectInfoInflight.set(key, tracked);
531
+ return tracked;
532
+ }
533
+
534
+ /** 测试用:清掉 ComfyUI 节点签名缓存和进行中占位。 */
535
+ export function resetComfyObjectInfoCache() {
536
+ objectInfoCache.clear();
537
+ objectInfoInflight.clear();
538
+ objectInfoBytes = 0;
539
+ }
540
+
541
+ /** 拉全量节点签名并缓存;UI 格式工作流和模型列表都靠它。 */
542
+ async function comfyObjectInfo(base, provider, signal) {
543
+ const key = objectInfoKey(base, provider, '', '');
544
+ const hit = objectInfoCache.get(key);
545
+ if (hit) {
546
+ if (Date.now() - hit.at < OBJECT_INFO_TTL) return hit.data;
547
+ evictObjectInfo(key);
548
+ }
549
+ const pending = objectInfoInflight.get(key);
550
+ if (pending) return pending;
551
+ const task = (async () => {
552
+ const response = await request(base + '/object_info', { headers: headersFor(provider, false), signal });
553
+ if (!response.ok) {
554
+ try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
555
+ throw new Error('读不到 ComfyUI 的节点签名(/object_info),请确认服务在运行。');
556
+ }
557
+ const data = await readJsonResponse(response, 40 * 1024 * 1024);
558
+ rememberObjectInfo(key, data);
559
+ return data;
560
+ })();
561
+ return trackObjectInfo(key, task);
562
+ }
305
563
 
306
564
  /**
307
565
  * 读某个 loader 节点可选的模型名。优先只取单节点,避免自定义节点很多时
308
566
  * /object_info 的 20MB+ 全量响应;节点级 404 时退回全量。
567
+ *
568
+ * 节点候选只合并进行中的相同请求,不做 TTL 缓存:用户往 models/ 里放个文件
569
+ * 就该在下次拉列表时看到,这里必须保持「当下装了什么」的语义。
309
570
  */
310
571
  async function comfyNodeOptions(base, provider, node, field, signal) {
311
- let response = await request(base + '/object_info/' + node, { headers: headersFor(provider, false), signal });
312
- if (!response.ok) {
313
- try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
314
- response = await request(base + '/object_info', { headers: headersFor(provider, false), signal });
315
- if (!response.ok) return [];
316
- }
317
- const payload = await readJsonResponse(response, 20 * 1024 * 1024);
318
- const entry = payload && payload[node];
319
- const inputs = entry && entry.input;
320
- const names = (inputs && inputs.required && inputs.required[field])
321
- || (inputs && inputs.optional && inputs.optional[field]);
322
- const list = Array.isArray(names) ? names[0] : null;
323
- return Array.isArray(list) ? list.map((name) => String(name)).filter(Boolean) : [];
572
+ const key = objectInfoKey(base, provider, node, field);
573
+ const pending = objectInfoInflight.get(key);
574
+ if (pending) return pending;
575
+ const task = (async () => {
576
+ let response = await request(base + '/object_info/' + node, { headers: headersFor(provider, false), signal });
577
+ if (!response.ok) {
578
+ try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
579
+ response = await request(base + '/object_info', { headers: headersFor(provider, false), signal });
580
+ if (!response.ok) return [];
581
+ }
582
+ const payload = await readJsonResponse(response, 20 * 1024 * 1024);
583
+ const entry = payload && payload[node];
584
+ const inputs = entry && entry.input;
585
+ const names = (inputs && inputs.required && inputs.required[field])
586
+ || (inputs && inputs.optional && inputs.optional[field]);
587
+ const list = Array.isArray(names) ? names[0] : null;
588
+ return Array.isArray(list) ? list.map((name) => String(name)).filter(Boolean) : [];
589
+ })();
590
+ return trackObjectInfo(key, task);
324
591
  }
325
592
 
326
593
  const FLUX2_NAME = /flux[._\-\s]?2/i;
@@ -539,6 +806,22 @@ async function comfyMossEditWorkflow(base, provider, { input, model, seed, signa
539
806
  };
540
807
  }
541
808
 
809
+ /**
810
+ * ComfyUI 队列轮询的退避曲线。
811
+ *
812
+ * 固定 700ms 会在排队久的任务上把本地服务刷成每秒 1.4 次查询;本地接口虽然便宜,
813
+ * 但 ComfyUI 单进程还要渲染,空转查询会抢它的时间片。改成 1s 起步、每次 ×1.15~1.3、
814
+ * 5s 封顶:刚提交时反应快,跑久了自动降频。抖动是必要的——多会话同时提交时,
815
+ * 没有抖动它们会一直同相位地一起打。
816
+ */
817
+ const COMFY_POLL_START_MS = 1000;
818
+ const COMFY_POLL_MAX_MS = 5000;
819
+
820
+ function nextComfyPollDelay(current) {
821
+ const factor = 1.15 + Math.random() * 0.15;
822
+ return Math.min(COMFY_POLL_MAX_MS, Math.round(current * factor));
823
+ }
824
+
542
825
  async function comfySubmitAndWait(base, provider, workflow, signal) {
543
826
  const submitted = await readJsonResponse(await request(base + '/prompt', {
544
827
  method: 'POST', headers: headersFor(provider, false),
@@ -546,11 +829,15 @@ async function comfySubmitAndWait(base, provider, workflow, signal) {
546
829
  }), 2 * 1024 * 1024);
547
830
  const promptId = submitted && submitted.prompt_id;
548
831
  if (!promptId) throw new Error('ComfyUI 没有返回 prompt_id');
832
+ // 总超时不变(5 分钟),只是查询频率随等待变长而下降。
549
833
  const deadline = Date.now() + 300000;
550
834
  let history = null;
835
+ let wait = COMFY_POLL_START_MS;
551
836
  while (Date.now() < deadline) {
552
837
  if (signal && signal.aborted) throw new Error('已取消');
553
- await sleep(700);
838
+ // 最后一次等待不能越过 deadline,否则「5 分钟超时」会被退避悄悄拉长。
839
+ await sleep(Math.min(wait, deadline - Date.now()));
840
+ wait = nextComfyPollDelay(wait);
554
841
  const poll = await request(base + '/history/' + encodeURIComponent(promptId), {
555
842
  headers: headersFor(provider, false), signal
556
843
  });
@@ -641,6 +928,20 @@ export function applyWorkflowTemplate(template, values, options) {
641
928
  return walk(template);
642
929
  }
643
930
 
931
+ /**
932
+ * 这个模型的尺寸能不能落到请求里。
933
+ * 自定义工作流既没有 {{width}} 占位符、映射里也没有宽高时,尺寸写不进去——
934
+ * 调用方据此改走「把尺寸写进提示词」,而不是静默丢掉。
935
+ */
936
+ export function comfySizeWritable(provider, model) {
937
+ const raw = comfyCustomWorkflow(provider, model);
938
+ if (!raw) return true;
939
+ if (/\{\{\s*width\s*\}\}/.test(raw) && /\{\{\s*height\s*\}\}/.test(raw)) return true;
940
+ const entry = provider && provider.modelOptions ? provider.modelOptions[model] : null;
941
+ const mapping = entry && entry.mapping ? entry.mapping : null;
942
+ return !!(mapping && mapping.width && mapping.height);
943
+ }
944
+
644
945
  /** 该模型有没有配置自定义工作流;没有就返回空串,走内置图。 */
645
946
  function comfyCustomWorkflow(provider, model) {
646
947
  const options = provider && provider.modelOptions;
@@ -650,41 +951,110 @@ function comfyCustomWorkflow(provider, model) {
650
951
  return typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
651
952
  }
652
953
 
653
- async function comfyCustomGraph(base, provider, { kind, input, model, width, height, seed, raw, signal }) {
654
- let template;
655
- try {
656
- template = JSON.parse(raw);
657
- } catch (error) {
658
- throw new Error('自定义工作流不是合法 JSON:' + String(error && error.message ? error.message : error));
954
+ /**
955
+ * 设置页解析用:把用户贴的工作流变成映射与候选。
956
+ * UI 格式缺签名的节点会导致悬空连线,所以这里当硬错误处理。
957
+ */
958
+ export async function analyzeComfyWorkflow({ base, provider, workflow, signal }) {
959
+ const parsed = parseWorkflow(workflow);
960
+ const info = await comfyObjectInfo(base, provider, signal);
961
+ let graph = parsed.graph;
962
+ if (parsed.format === 'ui') {
963
+ const converted = uiToApi(parsed.ui, info);
964
+ if (converted.missing.length) {
965
+ throw new Error('工作流里的节点没有安装:' + converted.missing.join('、')
966
+ + '。请在 ComfyUI 里装好它们,或改贴 API 格式的工作流。');
967
+ }
968
+ graph = converted.graph;
659
969
  }
660
- if (!template || typeof template !== 'object' || Array.isArray(template)) {
661
- throw new Error('自定义工作流必须是 ComfyUI 的 API 格式对象(节点 id → 节点)。');
970
+ const analysis = analyzeWorkflow(graph, info);
971
+ return { format: parsed.format, ...analysis };
972
+ }
973
+
974
+ async function comfyCustomGraph(base, provider, { kind, input, model, width, height, seed, raw, signal }) {
975
+ const parsed = parseWorkflow(raw);
976
+ let graph = parsed.graph;
977
+ if (parsed.format === 'ui') {
978
+ const info = await comfyObjectInfo(base, provider, signal);
979
+ const converted = uiToApi(parsed.ui, info);
980
+ if (converted.missing.length) {
981
+ throw new Error('工作流里的节点没有安装:' + converted.missing.join('、')
982
+ + '。请在 ComfyUI 里装好它们,或改贴 API 格式的工作流。');
983
+ }
984
+ graph = converted.graph;
662
985
  }
986
+
987
+ const entry = provider && provider.modelOptions ? provider.modelOptions[model] : null;
988
+ const mapping = entry && entry.mapping ? entry.mapping : null;
989
+ const hasPlaceholder = /\{\{\s*[A-Za-z_][A-Za-z0-9_]*\s*\}\}/.test(raw);
663
990
  const values = {
664
991
  prompt: input.prompt || '',
665
992
  negative_prompt: input.negativePrompt || '',
666
- width: width, height: height, seed: seed, model: model
993
+ negativePrompt: input.negativePrompt || '',
994
+ width, height, seed, model
667
995
  };
668
- const hasImageSlot = /\{\{\s*image\s*\}\}/.test(raw);
996
+
669
997
  if (kind === 'edit') {
670
- if (!hasImageSlot) {
671
- throw new Error('这个自定义工作流里没有 {{image}} 占位符,不能用于图生图;'
672
- + '请把参考图节点的 image 字段写成 {{image}}。');
998
+ const hasImageSlot = /\{\{\s*image\s*\}\}/.test(raw);
999
+ if (!hasImageSlot && !(mapping && mapping.image)) {
1000
+ throw new Error('这个自定义工作流里既没有 {{image}} 占位符,也没有可用的参考图映射,不能用于图生图;'
1001
+ + '请把参考图节点的 image 字段写成 {{image}},或在模型选项里解析并确认映射。');
673
1002
  }
674
1003
  const reference = input.images && input.images[0];
675
1004
  if (!reference || !reference.buffer) throw new Error('ComfyUI 编辑需要一张参考图');
676
1005
  values.image = await comfyUploadImage(base, provider, reference, signal);
677
- } else if (hasImageSlot) {
678
- values.image = '';
679
1006
  }
680
- return applyWorkflowTemplate(template, values);
1007
+
1008
+ let out;
1009
+ if (hasPlaceholder) out = applyWorkflowTemplate(graph, values);
1010
+ else if (mapping) out = injectByMapping(graph, mapping, values).graph;
1011
+ else throw new Error('这个自定义工作流没有注入映射,请先在模型选项里解析并确认。');
1012
+
1013
+ // 对话模型塞进来的可调参数:认得的写进去,认不得的记下来告诉它。
1014
+ const declared = entry && Array.isArray(entry.params) ? entry.params : [];
1015
+ const overrides = input && input.params && typeof input.params === 'object' ? input.params : null;
1016
+ if (overrides) {
1017
+ if (!declared.length) {
1018
+ return { graph: out, note: '当前模型没有暴露任何工作流参数,已忽略:' + Object.keys(overrides).join('、') };
1019
+ }
1020
+ const tuned = applyWorkflowParams(out, declared, overrides);
1021
+ const note = tuned.ignored.length
1022
+ ? '这些参数当前模型不支持或取值无效,已忽略:' + tuned.ignored.join('、')
1023
+ : '';
1024
+ return { graph: tuned.graph, note };
1025
+ }
1026
+ return { graph: out, note: '' };
1027
+ }
1028
+
1029
+ /** A1111 的采样参数:默认全部不暴露,用户在模型选项里逐项打开。 */
1030
+ export const A1111_PARAMS = [
1031
+ { name: 'steps', type: 'INT' },
1032
+ { name: 'cfg_scale', type: 'FLOAT' },
1033
+ { name: 'sampler_name', type: 'STRING' },
1034
+ { name: 'scheduler', type: 'STRING' },
1035
+ { name: 'seed', type: 'INT' },
1036
+ { name: 'denoising_strength', type: 'FLOAT' }
1037
+ ];
1038
+
1039
+ /** 只有图生图才认的参数。 */
1040
+ const A1111_EDIT_ONLY = new Set(['denoising_strength']);
1041
+
1042
+ function coerceA1111Param(type, raw) {
1043
+ if (type === 'STRING') {
1044
+ const text = String(raw === undefined || raw === null ? '' : raw).trim();
1045
+ return text ? text : undefined;
1046
+ }
1047
+ const value = typeof raw === 'number' ? raw : Number(String(raw).trim());
1048
+ if (!Number.isFinite(value)) return undefined;
1049
+ if (type === 'INT') return Number.isInteger(value) ? value : Math.round(value);
1050
+ return value;
681
1051
  }
682
1052
 
683
1053
  const ADAPTERS = [
684
1054
  {
685
1055
  id: 'dall-e-3',
686
1056
  label: 'OpenAI DALL·E 3',
687
- match: (provider, model) => /dall-?e-?3/i.test(model),
1057
+ match: (provider, model) => /dall-?e-?3/i.test(model) && !MAJOR_HOSTS.test(hostOfBase(baseUrlOf(provider))),
688
1058
  endpoints: { generate: '/images/generations', edit: '/images/edits' },
689
1059
  transport: { generate: 'json', edit: 'multipart' },
690
1060
  send: ['model', 'prompt', 'size', 'quality', 'response_format', 'n'],
@@ -705,21 +1075,25 @@ const ADAPTERS = [
705
1075
  {
706
1076
  id: 'gpt-image',
707
1077
  label: 'OpenAI GPT-Image',
708
- match: (provider, model) => /gpt-?image/i.test(model),
1078
+ match: (provider, model) => /gpt-?image/i.test(model) && !MAJOR_HOSTS.test(hostOfBase(baseUrlOf(provider))),
709
1079
  endpoints: { generate: '/images/generations', edit: '/images/edits' },
710
1080
  transport: { generate: 'json', edit: 'multipart' },
711
1081
  send: ['model', 'prompt', 'size', 'quality', 'n'],
712
- size: { style: 'string', field: 'size', allowed: ['1024x1024', '1536x1024', '1024x1536', 'auto'], default: '1024x1024', onUnsupported: 'nearest' },
1082
+ // gpt-image 2.x 起支持任意 W×H:16 的倍数、比例 1:3–3:1、像素 655360–8294400。
1083
+ size: { style: 'string', field: 'size', multiple: 16, minPixels: 655360, maxPixels: 8294400, default: '1024x1024', onUnsupported: 'nearest' },
713
1084
  quality: {
714
1085
  label: '质量', default: 'high', fallback: 'high',
715
- allowed: ['low', 'medium', 'high', 'auto'],
716
- options: [
717
- { value: 'off', label: 'Off' },
718
- { value: 'low', label: 'Low' },
719
- { value: 'medium', label: 'Medium' },
720
- { value: 'high', label: 'High' },
721
- { value: 'auto', label: 'Auto' }
722
- ]
1086
+ allowed: ['low', 'medium', 'high', 'xhigh', 'max', 'auto'],
1087
+ options: (model) => {
1088
+ const maxed = /2\.5-(sunburst|flare)/i.test(String(model || ''));
1089
+ return [
1090
+ { value: 'off', label: 'Off' },
1091
+ { value: 'low', label: 'Low' },
1092
+ { value: 'medium', label: 'Medium' },
1093
+ { value: 'high', label: 'High' }
1094
+ ].concat(maxed ? [{ value: 'xhigh', label: 'XHigh' }, { value: 'max', label: 'Max' }] : [])
1095
+ .concat([{ value: 'auto', label: 'Auto' }]);
1096
+ }
723
1097
  },
724
1098
  maxN: 10,
725
1099
  editFields: ['image[]', 'image']
@@ -731,7 +1105,31 @@ const ADAPTERS = [
731
1105
  local: false,
732
1106
  endpoints: { generate: '/models', edit: '/models' },
733
1107
  transport: { generate: 'json', edit: 'json' },
734
- size: { style: 'aspect', field: 'aspect_ratio', aspects: ASPECT_CHOICES, default: '1024x1024', onUnsupported: 'nearest' },
1108
+ size: {
1109
+ control: 'aspect', style: 'aspect', field: 'aspect_ratio', default: '1024x1024', onUnsupported: 'nearest',
1110
+ aspects: ['1:1', '1:4', '4:1', '1:8', '8:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9']
1111
+ },
1112
+ // imageSize 大小写敏感(必须大写 K),且 512 只有 3.1-flash-image 认。
1113
+ sizeByModel: [
1114
+ {
1115
+ match: /3\.1-flash-image/i,
1116
+ size: {
1117
+ tiers: [
1118
+ { value: '512', pixels: 262144 }, { value: '1K', pixels: 1048576 },
1119
+ { value: '2K', pixels: 4194304 }, { value: '4K', pixels: 16777216 }
1120
+ ]
1121
+ }
1122
+ },
1123
+ {
1124
+ match: /nano-banana|3-pro-image/i,
1125
+ size: {
1126
+ tiers: [
1127
+ { value: '1K', pixels: 1048576 }, { value: '2K', pixels: 4194304 }, { value: '4K', pixels: 16777216 }
1128
+ ]
1129
+ }
1130
+ },
1131
+ { match: /2\.5-flash-image/i, size: { wire: [], hint: 'noSizeField' } }
1132
+ ],
735
1133
  maxN: 1,
736
1134
  async listModels(provider, signal) {
737
1135
  return (await this.listModelEntries(provider, signal)).map((entry) => entry.id);
@@ -745,7 +1143,9 @@ const ADAPTERS = [
745
1143
  .filter((item) => {
746
1144
  const methods = item.supportedGenerationMethods;
747
1145
  if (Array.isArray(methods) && !methods.includes('generateContent')) return false;
748
- return /gemini/i.test(String(item.name || '')) && /image/i.test(String(item.name || '')) && !/imagen/i.test(String(item.name || ''));
1146
+ return /gemini/i.test(String(item.name || ''))
1147
+ && (/image/i.test(String(item.name || '')) || /nano-banana/i.test(String(item.name || '')))
1148
+ && !/imagen/i.test(String(item.name || ''));
749
1149
  })
750
1150
  .map((item) => {
751
1151
  const id = String(item.name || '').replace(/^models\//, '');
@@ -759,7 +1159,13 @@ const ADAPTERS = [
759
1159
  const model = String(input.model || '').replace(/^models\//, '').trim();
760
1160
  if (!model) throw new Error('Gemini 模型 ID 不能为空');
761
1161
  const images = input.images || [];
762
- if (images.length > 14) throw new Error('Gemini 一次最多支持 14 张参考图');
1162
+ const is25 = /gemini-2\.5-flash-image/i.test(model);
1163
+ const isFlash31 = /gemini-3\.1-flash-image/i.test(model);
1164
+ const isLite = /gemini-3\.1-flash-lite-image/i.test(model);
1165
+ const referenceLimit = is25 ? 3 : 14;
1166
+ if (images.length > referenceLimit) {
1167
+ throw new Error('Gemini 一次最多 ' + referenceLimit + ' 张参考图(该模型上限)');
1168
+ }
763
1169
  const parts = [];
764
1170
  for (const image of images) {
765
1171
  if (!image || !image.buffer) continue;
@@ -773,13 +1179,18 @@ const ADAPTERS = [
773
1179
  let prompt = String(input.prompt || '');
774
1180
  if (input.negativePrompt) prompt += '\n\nAvoid: ' + String(input.negativePrompt);
775
1181
  parts.push({ text: prompt });
776
- const width = input.fitted && !input.fitted.omit ? input.fitted.width : 1024;
777
- const height = input.fitted && !input.fitted.omit ? input.fitted.height : 1024;
778
- const generationConfig = {
779
- responseModalities: ['TEXT', 'IMAGE'],
780
- imageConfig: { aspectRatio: nearestAspect(width, height) }
781
- };
782
- if (/pro-image/i.test(model)) generationConfig.imageConfig.imageSize = resolutionFor(width, height).toUpperCase();
1182
+ // 自动尺寸:不下发 imageConfig,让模型自己决定比例与档位。
1183
+ const explicit = !!(input.fitted && !input.fitted.omit);
1184
+ const width = explicit ? input.fitted.width : 0;
1185
+ const height = explicit ? input.fitted.height : 0;
1186
+ const generationConfig = { responseModalities: ['TEXT', 'IMAGE'] };
1187
+ if (explicit) {
1188
+ const aspect = input.fitted.aspect || nearestAspect(width, height, is25 ? ASPECT_CHOICES : ASPECT_CHOICES_14);
1189
+ const imageConfig = { aspectRatio: aspect };
1190
+ // 档位与大小写由策略给出(512 只有 3.1-flash 认,必须大写 K)。
1191
+ if (input.fitted.tier) imageConfig.imageSize = String(input.fitted.tier);
1192
+ generationConfig.imageConfig = imageConfig;
1193
+ }
783
1194
  const response = await request(baseUrlOf(provider) + '/models/' + encodeURIComponent(model) + ':generateContent', {
784
1195
  method: 'POST',
785
1196
  headers: keyedHeaders(provider, 'x-goog-api-key', false),
@@ -788,8 +1199,11 @@ const ADAPTERS = [
788
1199
  });
789
1200
  const payload = await readJsonResponse(response, 48 * 1024 * 1024);
790
1201
  const partsOut = payload && payload.candidates && payload.candidates[0] && payload.candidates[0].content && payload.candidates[0].content.parts;
791
- for (const part of Array.isArray(partsOut) ? partsOut : []) {
792
- const inline = part && (part.inlineData || part.inline_data);
1202
+ // thinking 模型会先返回 thought 中间草图,结果取最后一张非 thought 图。
1203
+ const ordered = Array.isArray(partsOut) ? partsOut.slice().reverse() : [];
1204
+ for (const part of ordered) {
1205
+ if (!part || part.thought === true) continue;
1206
+ const inline = part.inlineData || part.inline_data;
793
1207
  if (!inline || !inline.data) continue;
794
1208
  const decoded = base64ToImage(inline.data);
795
1209
  if (!decoded) continue;
@@ -806,7 +1220,12 @@ const ADAPTERS = [
806
1220
  local: false,
807
1221
  endpoints: { generate: '/images/generations', edit: '' },
808
1222
  transport: { generate: 'json', edit: 'json' },
809
- size: { style: 'aspect', field: 'aspect_ratio', aspects: ASPECT_CHOICES, default: '1024x1024', onUnsupported: 'nearest' },
1223
+ size: {
1224
+ control: 'aspect', style: 'aspect', field: 'aspect_ratio', default: '1024x1024', onUnsupported: 'nearest',
1225
+ aspects: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3', '2:1', '1:2', '19.5:9', '9:19.5', '20:9', '9:20', '21:9', '5:2'],
1226
+ // xAI 的 resolution 是小写,而且只有两档;没有 4k。
1227
+ tiers: [{ value: '1k', pixels: 1048576 }, { value: '2k', pixels: 4194304 }]
1228
+ },
810
1229
  maxN: 1,
811
1230
  async listModels(provider, signal) {
812
1231
  const response = await request(baseUrlOf(provider) + '/models', { headers: headersFor(provider, false), signal });
@@ -824,10 +1243,13 @@ const ADAPTERS = [
824
1243
  if (input.negativePrompt) prompt += '\n\nAvoid: ' + String(input.negativePrompt);
825
1244
  const body = {
826
1245
  model: input.model, prompt: prompt, n: 1,
827
- response_format: 'url',
828
- aspect_ratio: nearestAspect(width, height),
829
- resolution: resolutionFor(width, height)
1246
+ response_format: 'url'
830
1247
  };
1248
+ // 自动尺寸:不下发比例与档位,让 Grok 自己决定。
1249
+ if (input.fitted && !input.fitted.omit) {
1250
+ body.aspect_ratio = input.fitted.aspect || nearestAspect(width, height);
1251
+ if (input.fitted.tier) body.resolution = String(input.fitted.tier);
1252
+ }
831
1253
  const response = await request(baseUrlOf(provider) + '/images/generations', {
832
1254
  method: 'POST', headers: headersFor(provider, false), body: JSON.stringify(body), signal
833
1255
  });
@@ -843,24 +1265,75 @@ const ADAPTERS = [
843
1265
  label: 'Recraft',
844
1266
  match: (provider) => /external\.api\.recraft\.ai/i.test(String((provider && provider.baseUrl) || '')),
845
1267
  local: false,
846
- endpoints: { generate: '/images/generations', edit: '' },
847
- transport: { generate: 'json', edit: 'json' },
848
- size: { style: 'string', field: 'size', allowed: ['1024x1024', '1365x1024', '1024x1365', '1536x1024', '1024x1536', '2048x2048'], default: '1024x1024', onUnsupported: 'nearest' },
1268
+ endpoints: { generate: '/images/generations', edit: '/images/imageToImage' },
1269
+ transport: { generate: 'json', edit: 'multipart' },
1270
+ editFields: ['image'],
1271
+ editExtras: { strength: 0.5 },
1272
+ // size 只认「该模型表内的 WxH」或任意比例;三族像素表完全不同,表外值直接 400。
1273
+ size: {
1274
+ control: 'preset', style: 'string', field: 'size', allowCustom: false, onUnsupported: 'nearest',
1275
+ allowed: [
1276
+ '1024x1024', '1536x768', '768x1536', '1280x832', '832x1280', '1216x896', '896x1216',
1277
+ '1152x896', '896x1152', '832x1344', '1280x896', '896x1280', '1344x768', '768x1344'
1278
+ ]
1279
+ },
1280
+ sizeByModel: [
1281
+ {
1282
+ match: /_pro$/i,
1283
+ size: {
1284
+ control: 'preset', style: 'string', field: 'size', allowCustom: false,
1285
+ allowed: [
1286
+ '2048x2048', '3072x1536', '1536x3072', '2560x1664', '1664x2560', '2432x1792', '1792x2432',
1287
+ '2304x1792', '1792x2304', '1664x2688', '2560x1792', '1792x2560', '2688x1536', '1536x2688'
1288
+ ]
1289
+ }
1290
+ },
1291
+ {
1292
+ match: /recraftv[23]|v[23]_/i,
1293
+ size: {
1294
+ control: 'preset', style: 'string', field: 'size', allowCustom: false,
1295
+ allowed: [
1296
+ '1024x1024', '2048x1024', '1024x2048', '1536x1024', '1024x1536', '1365x1024', '1024x1365',
1297
+ '1280x1024', '1024x1280', '1024x1707', '1434x1024', '1024x1434', '1820x1024', '1024x1820'
1298
+ ]
1299
+ }
1300
+ },
1301
+ {
1302
+ match: /_vector/i,
1303
+ size: {
1304
+ control: 'aspect', style: 'string', field: 'size',
1305
+ aspects: ['1:1', '2:1', '1:2', '3:2', '2:3', '4:3', '3:4', '5:4', '4:5', '16:9', '9:16'],
1306
+ allowCustom: false
1307
+ }
1308
+ }
1309
+ ],
849
1310
  maxN: 1,
850
1311
  async listModels() {
851
1312
  return ['recraftv4_1', 'recraftv4', 'recraftv3', 'recraftv2'];
852
1313
  },
853
1314
  async execute(kind, provider, input, signal) {
854
- if (kind === 'edit') throw new Error('Recraft 原生编辑暂未支持;请使用生成或换支持编辑的模型。');
855
1315
  let prompt = String(input.prompt || '');
856
1316
  if (input.negativePrompt) prompt += '\n\nAvoid: ' + String(input.negativePrompt);
857
- const body = {
858
- model: input.model, prompt: prompt, n: 1, response_format: 'url'
859
- };
860
- if (input.fitted && !input.fitted.omit && input.fitted.size) body.size = input.fitted.size;
861
- const response = await request(baseUrlOf(provider) + '/images/generations', {
862
- method: 'POST', headers: headersFor(provider, false), body: JSON.stringify(body), signal
863
- });
1317
+ let response;
1318
+ if (kind === 'edit') {
1319
+ const form = new FormData();
1320
+ form.append('prompt', prompt);
1321
+ form.append('strength', '0.5');
1322
+ for (const image of input.images || []) {
1323
+ form.append('image', new Blob([image.buffer], { type: image.contentType }), image.filename);
1324
+ }
1325
+ response = await request(baseUrlOf(provider) + '/images/imageToImage', {
1326
+ method: 'POST', headers: headersFor(provider, true, null, this), body: form, signal: signal
1327
+ });
1328
+ } else {
1329
+ const body = {
1330
+ model: input.model, prompt: prompt, n: 1, response_format: 'url'
1331
+ };
1332
+ if (input.fitted && !input.fitted.omit && input.fitted.size) body.size = input.fitted.size;
1333
+ response = await request(baseUrlOf(provider) + '/images/generations', {
1334
+ method: 'POST', headers: headersFor(provider, false, null, this), body: JSON.stringify(body), signal: signal
1335
+ });
1336
+ }
864
1337
  const payload = await readJsonResponse(response, 32 * 1024 * 1024);
865
1338
  const decoded = decodeImagePayload(payload, null);
866
1339
  if (decoded.bytes) return decoded;
@@ -873,9 +1346,49 @@ const ADAPTERS = [
873
1346
  label: 'Ideogram',
874
1347
  match: (provider) => /(^|\.)api\.ideogram\.ai$/i.test(String((provider && provider.baseUrl) || '').replace(/^https?:\/\//, '').split('/')[0]),
875
1348
  local: false,
876
- endpoints: { generate: '/v2/image/generate/ideogram-3', edit: '' },
1349
+ endpoints: { generate: (input) => ideogramPath(input), edit: '' },
877
1350
  transport: { generate: 'multipart', edit: 'json' },
878
- size: { style: 'aspect', field: 'aspect_ratio', aspects: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'], default: '1024x1024', onUnsupported: 'nearest' },
1351
+ // 三个模型三种协议:3 收比例(字母 x),4 只收 resolution 像素枚举,4-5 只收 size 宽高。
1352
+ size: {
1353
+ control: 'aspect', style: 'aspect', field: 'aspect_ratio', default: '1024x1024', onUnsupported: 'nearest',
1354
+ aspects: ['auto', '1x3', '3x1', '1x2', '2x1', '9x16', '16x9', '10x16', '16x10', '2x3', '3x2', '3x4', '4x3', '4x5', '5x4', '1x1']
1355
+ },
1356
+ sizeByModel: [
1357
+ {
1358
+ // 透明背景模型:比例 + 小写档位(v2 spec 是 1k/2k/4k/8k;v1 spec 写成大写,
1359
+ // 两边官方自相矛盾,这里按 v2 端点的小写来发)。
1360
+ match: /ideogram-4-transparent/i,
1361
+ size: {
1362
+ control: 'aspect', style: 'aspect', field: 'aspect_ratio',
1363
+ aspects: ['auto', '1x4', '1x3', '1x2', '9x16', '10x16', '2x3', '3x4', '4x5', '1x1', '5x4', '4x3', '3x2', '16x10', '16x9', '2x1', '3x1', '4x1'],
1364
+ tiers: [
1365
+ { value: '1k', pixels: 1048576 }, { value: '2k', pixels: 4194304 },
1366
+ { value: '4k', pixels: 16777216 }, { value: '8k', pixels: 67108864 }
1367
+ ]
1368
+ }
1369
+ },
1370
+ {
1371
+ match: /ideogram-4-5/i,
1372
+ size: {
1373
+ control: 'wh', style: 'string', field: 'size', allowCustom: true,
1374
+ multiple: 32, minSide: 256, maxPixels: 4194304
1375
+ }
1376
+ },
1377
+ {
1378
+ match: /ideogram-4/i,
1379
+ size: {
1380
+ control: 'preset', style: 'string', field: 'resolution', allowCustom: false,
1381
+ allowed: [
1382
+ '2048x2048', '1440x2880', '2880x1440', '1664x2496', '2496x1664', '1792x2240', '2240x1792',
1383
+ '1440x2560', '2560x1440', '1600x2560', '2560x1600', '1728x2304', '2304x1728', '1296x3168',
1384
+ '3168x1296', '1152x2944', '2944x1152', '1248x3328', '3328x1248', '1280x3072', '3072x1280',
1385
+ '1024x3072', '3072x1024', '1024x1024', '896x1120', '1120x896', '864x1152', '1152x864',
1386
+ '832x1248', '1248x832', '800x1280', '1280x800', '720x1280', '1280x720', '720x1440', '1440x720',
1387
+ '512x1536', '1536x512'
1388
+ ]
1389
+ }
1390
+ }
1391
+ ],
879
1392
  quality: {
880
1393
  label: '质量', default: 'default', fallback: 'default',
881
1394
  allowed: ['turbo', 'default', 'quality'],
@@ -889,25 +1402,55 @@ const ADAPTERS = [
889
1402
  },
890
1403
  maxN: 1,
891
1404
  async listModels() {
892
- return ['ideogram-3'];
1405
+ return ['ideogram-3', 'ideogram-4', 'ideogram-4-5', 'ideogram-4-transparent'];
893
1406
  },
894
1407
  async execute(kind, provider, input, signal) {
895
1408
  if (kind === 'edit') throw new Error('Ideogram 原生编辑暂未支持;请使用生成或换支持编辑的模型。');
896
- const form = new FormData();
897
- form.append('prompt', String(input.prompt || ''));
898
- if (input.negativePrompt) form.append('negative_prompt', String(input.negativePrompt));
1409
+ const model = String(input.model || 'ideogram-3');
1410
+ const fitted = input.fitted && !input.fitted.omit ? input.fitted : null;
1411
+ const prompt = String(input.prompt || '');
899
1412
  const speed = input.quality && input.quality !== 'off'
900
1413
  ? ({ turbo: 'TURBO', default: 'DEFAULT', quality: 'QUALITY' })[String(input.quality).toLowerCase()]
901
1414
  : '';
902
- if (speed) form.append('rendering_speed', speed);
903
- form.append('aspect_ratio', nearestAspect(input.fitted && input.fitted.width, input.fitted && input.fitted.height));
904
- form.append('num_images', '1');
905
- const response = await request(baseUrlOf(provider) + '/v2/image/generate/ideogram-3', {
906
- method: 'POST',
907
- headers: keyedHeaders(provider, 'Api-Key', true),
908
- body: form,
909
- signal: signal
910
- });
1415
+ let response;
1416
+ const isTransparent = /ideogram-4-transparent/i.test(model);
1417
+ const is45 = /ideogram-4-5/i.test(model);
1418
+ const is4 = !isTransparent && !is45 && /ideogram-4/i.test(model);
1419
+ if (is4) {
1420
+ // ideogram-4 是 JSON,而且只有 resolution(像素枚举),没有 aspect_ratio。
1421
+ const body = { prompt: prompt, num_images: 1 };
1422
+ if (fitted && fitted.size) body.resolution = String(fitted.size);
1423
+ if (speed) body.rendering_speed = speed;
1424
+ response = await request(baseUrlOf(provider) + ideogramPath(input), {
1425
+ method: 'POST',
1426
+ headers: keyedHeaders(provider, 'Api-Key', false),
1427
+ body: JSON.stringify(body),
1428
+ signal: signal
1429
+ });
1430
+ } else {
1431
+ const form = new FormData();
1432
+ form.append('prompt', prompt);
1433
+ if (input.negativePrompt) form.append('negative_prompt', String(input.negativePrompt));
1434
+ if (speed) form.append('rendering_speed', speed);
1435
+ if (fitted) {
1436
+ if (is45) {
1437
+ // ideogram-4-5 只收 size:auto / source / WxH(32 的倍数)。
1438
+ form.append('size', String(fitted.size));
1439
+ } else {
1440
+ // ideogram-3 与 transparent 的比例是字母 x(16x9),不是冒号。
1441
+ const aspect = fitted.aspect || nearestAspect(fitted.width, fitted.height);
1442
+ form.append('aspect_ratio', String(aspect).replace(':', 'x'));
1443
+ if (isTransparent && fitted.tier) form.append('output_resolution', String(fitted.tier));
1444
+ }
1445
+ }
1446
+ form.append('num_images', '1');
1447
+ response = await request(baseUrlOf(provider) + ideogramPath(input), {
1448
+ method: 'POST',
1449
+ headers: keyedHeaders(provider, 'Api-Key', true),
1450
+ body: form,
1451
+ signal: signal
1452
+ });
1453
+ }
911
1454
  const payload = await readJsonResponse(response, 32 * 1024 * 1024);
912
1455
  const decoded = decodeImagePayload(payload, null);
913
1456
  if (decoded.bytes) return decoded;
@@ -932,10 +1475,26 @@ const ADAPTERS = [
932
1475
  match: (provider, model) => /siliconflow/i.test(provider.baseUrl || ''),
933
1476
  endpoints: { generate: '/images/generations', edit: '/images/generations' },
934
1477
  transport: { generate: 'json', edit: 'json' },
935
- send: ['model', 'prompt', 'negative_prompt', 'image_size', 'batch_size', 'num_inference_steps', 'guidance_scale', 'seed'],
936
- size: { style: 'string', field: 'image_size', allowed: ['1024x1024', '768x1024', '1024x768', '512x512'], default: '1024x1024', onUnsupported: 'nearest' },
1478
+ send: ['model', 'prompt', 'negative_prompt', 'image_size', 'num_inference_steps', 'guidance_scale', 'seed'],
1479
+ // image_size 对 Kolors / Qwen-Image 必填;Qwen-Image-Edit 系列官方明确不收这个字段。
1480
+ size: {
1481
+ control: 'preset', custom: true, style: 'string', field: 'image_size', allowCustom: true,
1482
+ allowed: ['1024x1024', '960x1280', '768x1024', '720x1440', '720x1280']
1483
+ },
1484
+ sizeByModel: [
1485
+ { match: /qwen-image-edit/i, size: { control: 'wh', wire: [], hint: 'noSizeField' } },
1486
+ {
1487
+ match: /qwen-image/i,
1488
+ size: {
1489
+ control: 'preset', custom: true, allowCustom: true,
1490
+ allowed: ['1328x1328', '1664x928', '928x1664', '1472x1140', '1140x1472', '1584x1056', '1056x1584']
1491
+ }
1492
+ }
1493
+ ],
937
1494
  maxN: 1,
938
- editFields: ['image']
1495
+ editFields: ['image'],
1496
+ // Qwen-Image-Edit 系列不接受 image_size,传了会 400。
1497
+ editDrops: (input) => (/qwen-image-edit/i.test(String((input && input.model) || '')) ? ['image_size'] : [])
939
1498
  },
940
1499
  {
941
1500
  id: 'volcengine-ark',
@@ -943,8 +1502,44 @@ const ADAPTERS = [
943
1502
  match: (provider, model) => /volces\.com/i.test(provider.baseUrl || ''),
944
1503
  endpoints: { generate: '/images/generations', edit: '/images/generations' },
945
1504
  transport: { generate: 'json', edit: 'json' },
946
- send: ['model', 'prompt', 'size', 'response_format', 'watermark', 'n'],
947
- size: { style: 'string', field: 'size', allowed: ['1024x1024', '864x1152', '1152x864'], default: '1024x1024', onUnsupported: 'nearest' },
1505
+ send: ['model', 'prompt', 'size', 'response_format', 'watermark', 'n', 'image'],
1506
+ size: {
1507
+ control: 'preset', custom: true,
1508
+ style: 'string', field: 'size', default: '1024x1024', onUnsupported: 'nearest',
1509
+ tiers: [{ value: '2K', pixels: 2048 * 2048 }, { value: '3K', pixels: 3072 * 3072 }, { value: '4K', pixels: 4096 * 4096 }]
1510
+ },
1511
+ // 档位集合按模型分叉:5.x 是 1K/1.5K/2K(没有 4K),lite 是 2K/3K/4K,4.5 只有 2K/4K。
1512
+ // 顺序有意义:更具体的(lite)必须排在更宽的(5.x)前面。
1513
+ sizeByModel: [
1514
+ {
1515
+ match: /seedream-?5\.0-lite/i,
1516
+ size: {
1517
+ tiers: [{ value: '2K', pixels: 4194304 }, { value: '3K', pixels: 9437184 }, { value: '4K', pixels: 16777216 }],
1518
+ minPixels: 3686400, maxPixels: 16777216
1519
+ }
1520
+ },
1521
+ {
1522
+ match: /seedream-?5\.[05]/i,
1523
+ size: {
1524
+ tiers: [{ value: '1K', pixels: 1048576 }, { value: '1.5K', pixels: 2359296 }, { value: '2K', pixels: 4194304 }],
1525
+ minPixels: 921600, maxPixels: 4624220
1526
+ }
1527
+ },
1528
+ {
1529
+ match: /seedream-?4\.5/i,
1530
+ size: {
1531
+ tiers: [{ value: '2K', pixels: 4194304 }, { value: '4K', pixels: 16777216 }],
1532
+ minPixels: 3686400, maxPixels: 16777216
1533
+ }
1534
+ },
1535
+ {
1536
+ match: /seedream-?4\.0/i,
1537
+ size: {
1538
+ tiers: [{ value: '1K', pixels: 1048576 }, { value: '2K', pixels: 4194304 }, { value: '4K', pixels: 16777216 }],
1539
+ minPixels: 921600, maxPixels: 16777216
1540
+ }
1541
+ }
1542
+ ],
948
1543
  responseFormat: 'url',
949
1544
  watermark: false,
950
1545
  maxN: 1,
@@ -957,12 +1552,18 @@ const ADAPTERS = [
957
1552
  endpoints: { generate: '/v2beta/stable-image/generate/core', edit: '/v2beta/stable-image/generate/sd3' },
958
1553
  transport: { generate: 'multipart', edit: 'multipart' },
959
1554
  send: ['prompt', 'negative_prompt', 'aspect_ratio', 'output_format', 'model'],
960
- size: { style: 'aspect', field: 'aspect_ratio', aspects: ['1:1', '16:9', '3:2', '4:3', '9:16', '2:3'], default: '1024x1024', onUnsupported: 'nearest' },
1555
+ size: {
1556
+ control: 'aspect', style: 'aspect', field: 'aspect_ratio', default: '1024x1024', onUnsupported: 'nearest',
1557
+ aspects: ['21:9', '16:9', '3:2', '5:4', '1:1', '4:5', '2:3', '9:16', '9:21'],
1558
+ // 三个端点都没有像素参数:core 固定 1.5MP,sd3/ultra 固定 1MP。
1559
+ hint: 'fixedPixels'
1560
+ },
961
1561
  quality: null,
962
1562
  binary: true,
963
1563
  maxN: 1,
964
1564
  editFields: ['image']
965
1565
  },
1566
+ ...CN_ADAPTERS,
966
1567
  {
967
1568
  // 异步入队型:提交拿 task_id → 轮询到 SUCCEEDED → 下载结果。
968
1569
  // body 是嵌套结构,用 compose 把白名单字段折叠进去。
@@ -991,10 +1592,35 @@ const ADAPTERS = [
991
1592
  parameters: { size: fields.size, n: fields.n }
992
1593
  }),
993
1594
  size: {
994
- style: 'string', field: 'size', separator: '*',
995
- allowed: ['1024x1024', '1280x720', '720x1280', '1024x768', '768x1024'],
996
- default: '1024x1024', onUnsupported: 'nearest'
1595
+ control: 'preset', custom: true, style: 'string', field: 'size', separator: '*',
1596
+ // wan2.6 的总像素区间是 [1280², 1440²];官方推荐的 1104×1472 反而比它自己写的下限小,
1597
+ // 所以只按推荐表走,不按 1638400 硬拒。
1598
+ allowed: ['1280x1280', '1696x960', '960x1696', '1472x1104', '1104x1472'],
1599
+ allowCustom: true, default: '1280x1280', hint: 'modelDecides'
997
1600
  },
1601
+ // 万相里只有 wan2.7 认档位缩写;image-pro 的上限是 4096²,普通版是 2048²。
1602
+ sizeByModel: [
1603
+ {
1604
+ match: /wan2\.7.*pro/i,
1605
+ size: {
1606
+ control: 'preset', custom: true, allowCustom: true,
1607
+ tiers: [
1608
+ { value: '1K', pixels: 1048576 }, { value: '2K', pixels: 4194304 }, { value: '4K', pixels: 16777216 }
1609
+ ],
1610
+ minPixels: 589824, maxPixels: 16777216
1611
+ }
1612
+ },
1613
+ {
1614
+ match: /wan2\.7/i,
1615
+ size: {
1616
+ control: 'preset', custom: true, allowCustom: true,
1617
+ tiers: [
1618
+ { value: '1K', pixels: 1048576 }, { value: '2K', pixels: 4194304 }, { value: '4K', pixels: 16777216 }
1619
+ ],
1620
+ minPixels: 589824, maxPixels: 4194304
1621
+ }
1622
+ }
1623
+ ],
998
1624
  quality: null,
999
1625
  maxN: 4,
1000
1626
  editFields: []
@@ -1003,8 +1629,7 @@ const ADAPTERS = [
1003
1629
  id: 'a1111',
1004
1630
  label: 'AUTOMATIC1111 / Forge / SD.Next / Draw Things',
1005
1631
  match: (provider) => /a1111|forge|sdnext|sd-next|drawthings/i.test(String((provider && provider.adapter) || '')),
1006
- local: true,
1007
- endpoints: { generate: '/sdapi/v1/txt2img', edit: '/sdapi/v1/img2img' },
1632
+ local: true, endpoints: { generate: '/sdapi/v1/txt2img', edit: '/sdapi/v1/img2img' },
1008
1633
  transport: { generate: 'json', edit: 'json' },
1009
1634
  size: { style: 'string', field: 'size', multiple: 1, default: '1024x1024', onUnsupported: 'nearest' },
1010
1635
  async listModels(provider, signal) {
@@ -1018,9 +1643,10 @@ const ADAPTERS = [
1018
1643
  .filter(Boolean);
1019
1644
  },
1020
1645
  async execute(kind, provider, input, signal) {
1646
+ // 自动尺寸:请求里不带宽高,让 WebUI 用它自己的默认值。
1021
1647
  const size = input.fitted && !input.fitted.omit
1022
1648
  ? { width: input.fitted.width, height: input.fitted.height }
1023
- : { width: 1024, height: 1024 };
1649
+ : {};
1024
1650
  const body = {
1025
1651
  prompt: input.prompt,
1026
1652
  negative_prompt: input.negativePrompt || '',
@@ -1040,6 +1666,21 @@ const ADAPTERS = [
1040
1666
  body.height = dimensions.height;
1041
1667
  endpoint = '/sdapi/v1/img2img';
1042
1668
  }
1669
+ // 对话模型显式传入的采样参数:认得的覆盖,认不得的回报。
1670
+ const overrides = input.params && typeof input.params === 'object' ? input.params : null;
1671
+ let note = '';
1672
+ if (overrides) {
1673
+ const known = new Map(A1111_PARAMS.map((param) => [param.name, param]));
1674
+ const ignored = [];
1675
+ for (const [name, raw] of Object.entries(overrides)) {
1676
+ const param = known.get(name);
1677
+ if (!param || (kind !== 'edit' && A1111_EDIT_ONLY.has(name))) { ignored.push(name); continue; }
1678
+ const value = coerceA1111Param(param.type, raw);
1679
+ if (value === undefined) { ignored.push(name); continue; }
1680
+ body[name] = value;
1681
+ }
1682
+ if (ignored.length) note = '这些参数当前模型不支持或取值无效,已忽略:' + ignored.join('、');
1683
+ }
1043
1684
  const response = await request(baseUrlOf(provider) + endpoint, {
1044
1685
  method: 'POST', headers: headersFor(provider, false), body: JSON.stringify(body), signal
1045
1686
  });
@@ -1047,7 +1688,7 @@ const ADAPTERS = [
1047
1688
  const first = payload && Array.isArray(payload.images) ? payload.images[0] : null;
1048
1689
  const decoded = base64ToImage(first);
1049
1690
  if (!decoded) throw new Error('A1111 没有返回图片');
1050
- return decoded;
1691
+ return note ? Object.assign({}, decoded, { note }) : decoded;
1051
1692
  }
1052
1693
  },
1053
1694
  {
@@ -1066,26 +1707,32 @@ const ADAPTERS = [
1066
1707
  },
1067
1708
  async execute(kind, provider, input, signal) {
1068
1709
  const base = baseUrlOf(provider);
1069
- const width = input.fitted && !input.fitted.omit ? input.fitted.width : 1024;
1070
- const height = input.fitted && !input.fitted.omit ? input.fitted.height : 1024;
1710
+ // 尺寸=自动且模型没指定宽高时不注入,把分辨率留给工作流自己的节点。
1711
+ const explicit = !!(input.fitted && !input.fitted.omit);
1712
+ const width = explicit ? input.fitted.width : undefined;
1713
+ const height = explicit ? input.fitted.height : undefined;
1714
+ // 内置模板由插件拼装,必须有具体数字,自动尺寸下退回 1024。
1715
+ const builtinWidth = explicit ? width : 1024;
1716
+ const builtinHeight = explicit ? height : 1024;
1071
1717
  const seed = Math.floor(Math.random() * 2147483647);
1072
1718
  const model = input.model;
1073
1719
 
1074
1720
  const custom = comfyCustomWorkflow(provider, model);
1075
1721
  if (custom) {
1076
- const workflow = await comfyCustomGraph(base, provider, {
1722
+ const built = await comfyCustomGraph(base, provider, {
1077
1723
  kind, input, model, width, height, seed, raw: custom, signal
1078
1724
  });
1079
- return comfySubmitAndWait(base, provider, workflow, signal);
1725
+ const result = await comfySubmitAndWait(base, provider, built.graph, signal);
1726
+ return built.note ? Object.assign({}, result, { note: built.note }) : result;
1080
1727
  }
1081
1728
  const diffusionModels = await comfyNodeOptions(base, provider, 'UNETLoader', 'unet_name', signal);
1082
1729
  let workflow;
1083
1730
  if (diffusionModels.includes(model) && /moss/i.test(model)) {
1084
1731
  workflow = kind === 'edit'
1085
1732
  ? await comfyMossEditWorkflow(base, provider, { input, model, seed, signal })
1086
- : await comfyMossWorkflow(base, provider, { input, model, width, height, seed, signal });
1733
+ : await comfyMossWorkflow(base, provider, { input, model, width: builtinWidth, height: builtinHeight, seed, signal });
1087
1734
  } else if (diffusionModels.includes(model)) {
1088
- workflow = await comfyFluxWorkflow(base, provider, { kind, input, model, width, height, seed, signal });
1735
+ workflow = await comfyFluxWorkflow(base, provider, { kind, input, model, width: builtinWidth, height: builtinHeight, seed, signal });
1089
1736
  } else {
1090
1737
  let imageName = null;
1091
1738
  if (kind === 'edit') {
@@ -1093,7 +1740,7 @@ const ADAPTERS = [
1093
1740
  if (!reference || !reference.buffer) throw new Error('ComfyUI 编辑需要一张参考图');
1094
1741
  imageName = await comfyUploadImage(base, provider, reference, signal);
1095
1742
  }
1096
- workflow = comfyCheckpointWorkflow({ kind, input, model, width, height, seed, imageName });
1743
+ workflow = comfyCheckpointWorkflow({ kind, input, model, width: builtinWidth, height: builtinHeight, seed, imageName });
1097
1744
  }
1098
1745
  return comfySubmitAndWait(base, provider, workflow, signal);
1099
1746
  }
@@ -1127,14 +1774,17 @@ const ADAPTERS = [
1127
1774
  if (kind === 'edit') throw new Error('SwarmUI 原生编辑暂未支持;请改用支持 /images/edits 的 OpenAI 兼容网关');
1128
1775
  const base = baseUrlOf(provider);
1129
1776
  const session = await this.newSession(provider, signal);
1130
- const width = input.fitted && !input.fitted.omit ? input.fitted.width : 1024;
1131
- const height = input.fitted && !input.fitted.omit ? input.fitted.height : 1024;
1132
1777
  const body = {
1133
1778
  session_id: session, images: 1,
1134
1779
  prompt: input.prompt, negativeprompt: input.negativePrompt || '',
1135
- model: input.model, width: width, height: height,
1780
+ model: input.model,
1136
1781
  cfgscale: 7, steps: 20, seed: -1
1137
1782
  };
1783
+ // 自动尺寸:不带宽高,让 SwarmUI 用它自己的默认值。
1784
+ if (input.fitted && !input.fitted.omit) {
1785
+ body.width = input.fitted.width;
1786
+ body.height = input.fitted.height;
1787
+ }
1138
1788
  const generated = await readJsonResponse(await request(base + '/API/GenerateText2Image', {
1139
1789
  method: 'POST', headers: headersFor(provider, false), body: JSON.stringify(body), signal
1140
1790
  }), 5 * 1024 * 1024);
@@ -1174,12 +1824,16 @@ const ADAPTERS = [
1174
1824
  return openAiCompatibleEntries(payload);
1175
1825
  }
1176
1826
  },
1827
+ ...ASYNC_ADAPTERS,
1828
+ ...OPENAI_ADAPTERS,
1177
1829
  {
1178
1830
  id: 'openai-images',
1179
- label: 'OpenAI Images 兼容',
1831
+ label: 'OpenAI Images 兼容(自动同步/异步)',
1180
1832
  match: () => true,
1181
1833
  endpoints: { generate: '/images/generations', edit: '/images/edits' },
1182
1834
  transport: { generate: 'json', edit: 'multipart' },
1835
+ // 提交响应带任务 id / 轮询地址时自动跟着轮询;直接返回图片就照同步处理。
1836
+ autoAsync: true,
1183
1837
  send: ['model', 'prompt', 'negative_prompt', 'size', 'quality', 'n'],
1184
1838
  // 通用兼容族:尺寸原样透传(保持旧行为),被上游拒了再靠重试往上抬。
1185
1839
  size: { style: 'string', field: 'size', multiple: 1, default: '1024x1024', onUnsupported: 'nearest' },
@@ -1262,7 +1916,7 @@ export const PROVIDER_PRESETS = [
1262
1916
  id: 'gemini', name: 'Google Gemini / Nano Banana',
1263
1917
  baseUrl: 'https://generativelanguage.googleapis.com/v1beta', adapter: 'google-gemini',
1264
1918
  website: 'https://aistudio.google.com/app/apikey',
1265
- models: ['gemini-2.5-flash-image', 'gemini-3-pro-image-preview']
1919
+ models: ['gemini-nano-banana-2.1', 'gemini-3.1-flash-image', 'gemini-3-pro-image', 'gemini-2.5-flash-image']
1266
1920
  },
1267
1921
  { id: 'openai', name: 'OpenAI', baseUrl: 'https://api.openai.com/v1', adapter: '', website: 'https://platform.openai.com/api-keys', models: [] },
1268
1922
  {
@@ -1281,7 +1935,7 @@ export const PROVIDER_PRESETS = [
1281
1935
  id: 'ideogram', name: 'Ideogram',
1282
1936
  baseUrl: 'https://api.ideogram.ai', adapter: 'ideogram',
1283
1937
  website: 'https://developer.ideogram.ai/',
1284
- models: ['ideogram-3']
1938
+ models: ['ideogram-3', 'ideogram-4']
1285
1939
  },
1286
1940
  {
1287
1941
  id: 'stability', name: 'Stability AI',
@@ -1307,10 +1961,63 @@ export const PROVIDER_PRESETS = [
1307
1961
  website: 'https://novita.ai/settings/key-management',
1308
1962
  models: ['flux-1-schnell']
1309
1963
  },
1964
+ {
1965
+ id: 'openrouter', name: 'OpenRouter',
1966
+ baseUrl: 'https://openrouter.ai/api/v1', adapter: 'openrouter-images',
1967
+ website: 'https://openrouter.ai/settings/keys',
1968
+ models: ['google/gemini-3.1-flash-image', 'openai/gpt-image-2.5-flare', 'black-forest-labs/flux-2-pro']
1969
+ },
1970
+ {
1971
+ id: 'azure', name: 'Azure OpenAI',
1972
+ baseUrl: 'https://YOUR-RESOURCE.openai.azure.com/openai/v1', adapter: 'azure-openai',
1973
+ website: 'https://portal.azure.com/',
1974
+ models: []
1975
+ },
1976
+ {
1977
+ id: 'bfl', name: 'Black Forest Labs (FLUX)',
1978
+ baseUrl: 'https://api.bfl.ai/v1', adapter: 'bfl',
1979
+ website: 'https://dashboard.bfl.ai/',
1980
+ models: ['flux-2-pro', 'flux-2-max', 'flux-3-image', 'flux-kontext-pro']
1981
+ },
1982
+ {
1983
+ id: 'fal', name: 'fal.ai',
1984
+ baseUrl: 'https://queue.fal.run', adapter: 'fal',
1985
+ website: 'https://fal.ai/dashboard/keys',
1986
+ models: ['fal-ai/flux-2-pro', 'fal-ai/flux-pro/kontext']
1987
+ },
1988
+ {
1989
+ id: 'replicate', name: 'Replicate',
1990
+ baseUrl: 'https://api.replicate.com/v1', adapter: 'replicate',
1991
+ website: 'https://replicate.com/account/api-tokens',
1992
+ models: ['black-forest-labs/flux-2-pro']
1993
+ },
1310
1994
  { id: 'volcengine', name: '火山方舟', baseUrl: 'https://ark.cn-beijing.volces.com/api/v3', adapter: '', website: 'https://console.volcengine.com/ark', models: [] },
1311
- { id: 'dashscope', name: '阿里云百炼', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', adapter: '', website: 'https://bailian.console.aliyun.com/', models: [] },
1995
+ {
1996
+ id: 'volcengine-plan', name: '火山方舟 Agent Plan',
1997
+ baseUrl: 'https://ark.cn-beijing.volces.com/api/plan/v3', adapter: '',
1998
+ website: 'https://console.volcengine.com/ark',
1999
+ models: []
2000
+ },
2001
+ {
2002
+ id: 'dashscope', name: '阿里云百炼 · Qwen-Image',
2003
+ baseUrl: 'https://dashscope.aliyuncs.com/api/v1', adapter: 'dashscope-qwen-image',
2004
+ website: 'https://bailian.console.aliyun.com/',
2005
+ models: ['qwen-image-3.0-pro', 'qwen-image-3.0']
2006
+ },
2007
+ {
2008
+ id: 'dashscope-wanx', name: '阿里云百炼 · 通义万相',
2009
+ baseUrl: 'https://dashscope.aliyuncs.com/api/v1', adapter: 'dashscope-wanx',
2010
+ website: 'https://bailian.console.aliyun.com/',
2011
+ models: ['wan2.6-t2i', 'wan2.7-image-pro', 'wan2.7-image', 'wanx2.1-t2i-turbo']
2012
+ },
1312
2013
  { id: 'siliconflow', name: '硅基流动', baseUrl: 'https://api.siliconflow.cn/v1', adapter: '', website: 'https://cloud.siliconflow.cn/account/ak', models: [] },
1313
- { id: 'bigmodel', name: '智谱 BigModel', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', adapter: '', website: 'https://bigmodel.cn/usercenter/apikeys', models: [] }
2014
+ { id: 'bigmodel', name: '智谱 BigModel', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', adapter: 'zhipu', website: 'https://bigmodel.cn/usercenter/apikeys', models: [] },
2015
+ {
2016
+ id: 'modelscope', name: '魔搭 ModelScope',
2017
+ baseUrl: 'https://api-inference.modelscope.cn', adapter: 'modelscope',
2018
+ website: 'https://www.modelscope.cn/my/myaccesstoken',
2019
+ models: ['Qwen/Qwen-Image-2.1', 'Qwen/Qwen-Image-2.1-Turbo', 'Qwen/Qwen-Image-Edit']
2020
+ }
1314
2021
  ];
1315
2022
 
1316
2023
  export const LOCAL_PRESETS = [
@@ -1405,47 +2112,6 @@ export function describeAdapter(adapter) {
1405
2112
 
1406
2113
  /* -------------------------------------------------------------- requests */
1407
2114
 
1408
- function baseUrlOf(provider) {
1409
- return String((provider && provider.baseUrl) || '').replace(/\/+$/, '');
1410
- }
1411
-
1412
- function headersFor(provider, multipart, extra) {
1413
- const headers = Object.assign({}, extra || {});
1414
- const key = String((provider && provider.key) || '').trim();
1415
- if (key) headers.Authorization = 'Bearer ' + key;
1416
- if (!multipart && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
1417
- return headers;
1418
- }
1419
-
1420
- function sleep(ms) {
1421
- return new Promise((resolve) => setTimeout(resolve, ms));
1422
- }
1423
-
1424
- async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024) {
1425
- const buffer = await readResponseBytes(response, maxBytes);
1426
- const text = buffer.toString('utf8');
1427
- if (!response.ok) {
1428
- let detail = '';
1429
- try {
1430
- const parsed = JSON.parse(text);
1431
- detail = parsed && (parsed.error && (parsed.error.message || parsed.error) || parsed.message || parsed.detail) || '';
1432
- if (typeof detail !== 'string') detail = JSON.stringify(detail);
1433
- } catch (_error) {
1434
- detail = text.slice(0, 300);
1435
- }
1436
- throw localizedError(
1437
- new Error('本地生图服务返回 HTTP ' + response.status + (detail ? ':' + detail : '')),
1438
- detail ? 'upstream.http' : 'upstream.httpNoDetail',
1439
- { status: response.status, detail: detail }
1440
- );
1441
- }
1442
- try {
1443
- return JSON.parse(text);
1444
- } catch (_error) {
1445
- throw localizedError(new Error('本地生图服务返回的不是 JSON'), 'upstream.invalidJson');
1446
- }
1447
- }
1448
-
1449
2115
  /** A1111 img2img 需要原图尺寸;PNG/JPEG 足够覆盖常见参考图。 */
1450
2116
  function imageDimensions(buffer) {
1451
2117
  if (!buffer || buffer.length < 24) return null;
@@ -1482,7 +2148,7 @@ function pickFields(adapter, candidate, drops) {
1482
2148
  }
1483
2149
 
1484
2150
  function buildFields(adapter, input) {
1485
- const sizeFields = encodeSize(adapter, input.fitted);
2151
+ const sizeFields = encodeSize(adapter, input.fitted, input.model);
1486
2152
  return Object.assign({
1487
2153
  model: input.model,
1488
2154
  prompt: input.prompt,
@@ -1502,8 +2168,9 @@ function composeBody(adapter, input, drops) {
1502
2168
  return adapter.compose ? adapter.compose(fields) : fields;
1503
2169
  }
1504
2170
 
1505
- function jsonRequest(adapter, provider, requestPath, body) {
1506
- return { path: requestPath, headers: headersFor(provider, false, adapter.headers), body: JSON.stringify(body) };
2171
+ /** 端点既可以是固定字符串,也可以是按模型拼路径的函数(Ideogram、fal 这类)。 */
2172
+ function endpointOf(value, input) {
2173
+ return typeof value === 'function' ? value(input || {}) : value;
1507
2174
  }
1508
2175
 
1509
2176
  export function prepareGenerate(adapter, provider, input, drops) {
@@ -1511,13 +2178,17 @@ export function prepareGenerate(adapter, provider, input, drops) {
1511
2178
  if (adapter.transport.generate === 'multipart') {
1512
2179
  const form = new FormData();
1513
2180
  for (const key of Object.keys(body)) form.append(key, String(body[key]));
1514
- return { path: adapter.endpoints.generate, headers: headersFor(provider, true, adapter.headers), body: form };
2181
+ return { path: endpointOf(adapter.endpoints.generate, input), headers: headersFor(provider, true, adapter.headers, adapter), body: form };
1515
2182
  }
1516
- return jsonRequest(adapter, provider, adapter.endpoints.generate, body);
2183
+ return jsonRequest(adapter, provider, endpointOf(adapter.endpoints.generate, input), body);
1517
2184
  }
1518
2185
 
1519
2186
  export function prepareEdit(adapter, provider, input, drops, fieldName) {
1520
2187
  const body = composeBody(adapter, input, drops);
2188
+ // 有些编辑端点不收尺寸(如硅基流动 Qwen-Image-Edit),由适配器逐个模型声明。
2189
+ if (typeof adapter.editDrops === 'function') {
2190
+ for (const key of adapter.editDrops(input) || []) delete body[key];
2191
+ }
1521
2192
  if (adapter.transport.edit !== 'multipart') {
1522
2193
  // 非 multipart 的编辑接口(如 SiliconFlow / 火山方舟)用 image 字段承载
1523
2194
  // 参考图;统一编码成 data URL,单张发字符串,多张发数组。
@@ -1529,15 +2200,16 @@ export function prepareEdit(adapter, provider, input, drops, fieldName) {
1529
2200
  .map((image) => 'data:' + image.contentType + ';base64,' + image.buffer.toString('base64'));
1530
2201
  if (encoded.length > 0) body[field] = encoded.length === 1 ? encoded[0] : encoded;
1531
2202
  }
1532
- return jsonRequest(adapter, provider, adapter.endpoints.edit, body);
2203
+ return jsonRequest(adapter, provider, endpointOf(adapter.endpoints.edit, input), body);
1533
2204
  }
1534
2205
  const form = new FormData();
1535
2206
  for (const key of Object.keys(body)) form.append(key, String(body[key]));
2207
+ for (const [key, value] of Object.entries(adapter.editExtras || {})) form.append(key, String(value));
1536
2208
  const field = fieldName || (adapter.editFields && adapter.editFields[0]) || 'image';
1537
2209
  for (const image of input.images || []) {
1538
2210
  form.append(field, new Blob([image.buffer], { type: image.contentType }), image.filename);
1539
2211
  }
1540
- return { path: adapter.endpoints.edit, headers: headersFor(provider, true, adapter.headers), body: form };
2212
+ return { path: endpointOf(adapter.endpoints.edit, input), headers: headersFor(provider, true, adapter.headers, adapter), body: form };
1541
2213
  }
1542
2214
 
1543
2215
  /** 异步任务:先提交拿 task_id。 */
@@ -1545,6 +2217,137 @@ export function prepareAsync(adapter, provider, input, drops) {
1545
2217
  return jsonRequest(adapter, provider, adapter.submit, composeBody(adapter, input, drops));
1546
2218
  }
1547
2219
 
2220
+ /**
2221
+ * 这些字段是请求的语义核心:少了提示词、模型或参考图,请求就不再是「同一个请求」,
2222
+ * 上游就算收下也只会生成一张不相干的图。兼容性重试只允许摘掉可选参数。
2223
+ */
2224
+ const PHASE_PROTECTED_FIELDS = [
2225
+ 'prompt', 'model',
2226
+ 'input.prompt', 'input.model',
2227
+ 'images', 'image', 'image_url', 'image_urls', 'input_image',
2228
+ 'input.image', 'input.images', 'input.image_url', 'input.input_image'
2229
+ ];
2230
+
2231
+ /** BFL 的多图字段是 input_image_2/3/4,和 input_image 同类,删掉等于丢参考图。 */
2232
+ const PHASE_PROTECTED_SIBLING = /^input_image_\d+$/i;
2233
+
2234
+ /**
2235
+ * drop 是否踩到必要字段。
2236
+ *
2237
+ * 除了同名字段,还要挡两个方向:删父对象(`input`)会连带删掉 `input.prompt`;
2238
+ * 删子路径(`input.prompt.text`)等价于改必要字段。两者都按「不生效」处理。
2239
+ */
2240
+ function isProtectedPhaseDrop(path) {
2241
+ const text = String(path || '');
2242
+ if (!text) return false;
2243
+ if (PHASE_PROTECTED_SIBLING.test(text)) return true;
2244
+ for (const protectedPath of PHASE_PROTECTED_FIELDS) {
2245
+ if (text === protectedPath) return true;
2246
+ if (text.startsWith(protectedPath + '.')) return true;
2247
+ if (protectedPath.startsWith(text + '.')) return true;
2248
+ }
2249
+ return false;
2250
+ }
2251
+
2252
+ /**
2253
+ * 从请求体对象里删掉一条点分路径(`input.width` 这种),返回是否真的删掉了。
2254
+ * 只支持对象层级,不支持数组下标:适配器声明的兼容性字段都是具名字段。
2255
+ *
2256
+ * 路径来自上游错误文本,不能让它摸到原型链:`__proto__.toString` 这种
2257
+ * 会删到 Object.prototype 上,直接把整个进程的字符串化打坏。
2258
+ */
2259
+ const UNSAFE_PHASE_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);
2260
+
2261
+ function ownValue(node, key) {
2262
+ if (!node || (typeof node !== 'object' && typeof node !== 'function')) return undefined;
2263
+ return Object.prototype.hasOwnProperty.call(node, key) ? node[key] : undefined;
2264
+ }
2265
+
2266
+ function dropPhaseField(body, path) {
2267
+ const segments = String(path || '').split('.').filter(Boolean);
2268
+ if (!segments.length) return false;
2269
+ let node = body;
2270
+ for (let index = 0; index < segments.length - 1; index++) {
2271
+ const segment = segments[index];
2272
+ if (UNSAFE_PHASE_SEGMENTS.has(segment)) return false;
2273
+ const next = ownValue(node, segment);
2274
+ // 数组下标不在支持范围内:删元素会留下空洞(JSON 里变成 null),
2275
+ // 上游看到的还是一个坏数组,不如原样报回去。
2276
+ if (!next || typeof next !== 'object' || Array.isArray(next)) return false;
2277
+ node = next;
2278
+ }
2279
+ const leaf = segments[segments.length - 1];
2280
+ if (UNSAFE_PHASE_SEGMENTS.has(leaf)) return false;
2281
+ if (!node || (typeof node !== 'object' && typeof node !== 'function')) return false;
2282
+ if (!Object.prototype.hasOwnProperty.call(node, leaf)) return false;
2283
+ // 不存在的路径不算「删掉了」:调用方要按 dropped 判断请求是否真的变了,
2284
+ // 把无效路径报成 dropped 会骗它去做一次完全相同的重试。
2285
+ // 值为 undefined 的字段本来就进不了 JSON,同样不算真的删了东西。
2286
+ if (node[leaf] === undefined) return false;
2287
+ return delete node[leaf];
2288
+ }
2289
+
2290
+ /**
2291
+ * build 失败时保留原始错误对象:调用方要按 kind/status/cause 决定重试与降级,
2292
+ * 直接包装成新错误会把这些分类和栈丢掉,所以原错误一律挂到 cause 上。
2293
+ * message 保持不变,用户看到的文案不变。
2294
+ */
2295
+ function phaseBuildError(error) {
2296
+ if (!(error instanceof Error)) {
2297
+ return localizedError(new Error('构造异步请求体失败:' + String(error)), 'upstream.invalidResponse', { phase: 'prepare' });
2298
+ }
2299
+ if (error.cause && error.cause !== error) return error;
2300
+ const wrapped = new Error(error.message, { cause: error });
2301
+ wrapped.name = error.name;
2302
+ for (const key of ['status', 'code', 'kind', 'retryable', 'detail', 'localized']) {
2303
+ if (error[key] !== undefined) wrapped[key] = error[key];
2304
+ }
2305
+ return wrapped;
2306
+ }
2307
+
2308
+ /**
2309
+ * 新式异步描述符:提交体与提交路径都由适配器自己决定;build 可以是异步的。
2310
+ *
2311
+ * drops 是兼容性重试前累积的「上游不认识/不接受」的字段路径(Set 或数组,点分路径)。
2312
+ * 删在对象上再序列化,而不是先 stringify 再 parse:body 里常有 base64 data URL,
2313
+ * 往返一次会多复制一份整张图。build 每次都返回新对象,直接在上面删是安全的。
2314
+ */
2315
+ export async function preparePhaseAsync(adapter, provider, input, signal, drops) {
2316
+ const phase = adapter.async || {};
2317
+ // 有的平台提交路径依赖 baseUrl(魔搭带不带 /v1 都要能拼对),所以把 provider 也传进去。
2318
+ const path = String(phase.submitPath(input, provider) || '');
2319
+ let built;
2320
+ try {
2321
+ built = await phase.build(input, provider, signal);
2322
+ } catch (error) {
2323
+ throw phaseBuildError(error);
2324
+ }
2325
+ const body = built && built.body ? built.body : (built || {});
2326
+ const note = built && built.note ? String(built.note) : '';
2327
+ const dropped = [];
2328
+ const blockedDrops = [];
2329
+ const wanted = drops instanceof Set ? Array.from(drops) : (Array.isArray(drops) ? drops : []);
2330
+ if (body && typeof body === 'object' && !Array.isArray(body)) {
2331
+ for (const raw of wanted) {
2332
+ const fieldPath = String(raw === undefined || raw === null ? '' : raw).trim();
2333
+ if (!fieldPath) continue;
2334
+ if (isProtectedPhaseDrop(fieldPath)) {
2335
+ if (!blockedDrops.includes(fieldPath)) blockedDrops.push(fieldPath);
2336
+ continue;
2337
+ }
2338
+ if (dropPhaseField(body, fieldPath) && !dropped.includes(fieldPath)) dropped.push(fieldPath);
2339
+ }
2340
+ }
2341
+ return {
2342
+ path: path,
2343
+ headers: headersFor(provider, false, adapter.headers, adapter),
2344
+ body: JSON.stringify(body),
2345
+ note: note,
2346
+ dropped: dropped,
2347
+ blockedDrops: blockedDrops
2348
+ };
2349
+ }
2350
+
1548
2351
  export function pollUrlFor(adapter, provider, taskId) {
1549
2352
  const template = String((adapter.poll && adapter.poll.path) || '/tasks/{taskId}');
1550
2353
  return baseUrlOf(provider) + template.replace('{taskId}', encodeURIComponent(taskId));
@@ -1554,16 +2357,6 @@ export function pollHeaders(provider) {
1554
2357
  return { Authorization: 'Bearer ' + String((provider && provider.key) || '') };
1555
2358
  }
1556
2359
 
1557
- function getPath(node, path) {
1558
- if (!path) return node;
1559
- let current = node;
1560
- for (const key of String(path).split('.')) {
1561
- if (current === null || current === undefined) return null;
1562
- current = current[key];
1563
- }
1564
- return current === undefined ? null : current;
1565
- }
1566
-
1567
2360
  export function readTaskId(adapter, payload) {
1568
2361
  const value = getPath(payload, (adapter.poll && adapter.poll.idPath) || 'output.task_id');
1569
2362
  return value ? String(value) : null;
@@ -1589,219 +2382,66 @@ export function adapterBase(provider) {
1589
2382
  return baseUrlOf(provider);
1590
2383
  }
1591
2384
 
1592
- /* -------------------------------------------------------------- responses */
1593
-
1594
- export function sniffType(buffer) {
1595
- if (!buffer || buffer.length < 12) return 'image/png';
1596
- if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) return 'image/png';
1597
- if (buffer[0] === 0xff && buffer[1] === 0xd8) return 'image/jpeg';
1598
- if (buffer.slice(0, 4).toString('ascii') === 'RIFF' && buffer.slice(8, 12).toString('ascii') === 'WEBP') return 'image/webp';
1599
- if (buffer.slice(0, 3).toString('ascii') === 'GIF') return 'image/gif';
1600
- return 'image/png';
1601
- }
1602
-
1603
- export function looksLikeImage(buffer) {
1604
- if (!buffer || buffer.length < 8) return false;
1605
- const type = sniffType(buffer);
1606
- if (type === 'image/png') return buffer[0] === 0x89 && buffer[1] === 0x50;
1607
- if (type === 'image/jpeg') return buffer[0] === 0xff && buffer[1] === 0xd8;
1608
- if (type === 'image/webp') return buffer.slice(0, 4).toString('ascii') === 'RIFF' && buffer.slice(8, 12).toString('ascii') === 'WEBP';
1609
- return buffer.slice(0, 3).toString('ascii') === 'GIF';
1610
- }
1611
-
1612
- function base64ToImage(text) {
1613
- const raw = String(text || '');
1614
- if (!raw || raw.length < 64) return null;
1615
- const dataUrl = /^data:image\/([a-z+]+);base64,(.+)$/i.exec(raw);
1616
- const payload = dataUrl ? dataUrl[2] : raw;
1617
- if (!/^[A-Za-z0-9+/=\r\n]+$/.test(payload)) return null;
1618
- let buffer;
1619
- try {
1620
- buffer = Buffer.from(payload, 'base64');
1621
- } catch (_error) {
1622
- return null;
1623
- }
1624
- if (!looksLikeImage(buffer)) return null;
1625
- return { bytes: buffer, contentType: dataUrl ? 'image/' + dataUrl[1].toLowerCase() : sniffType(buffer) };
1626
- }
1627
-
1628
- function collectStrings(node, out, depth) {
1629
- if (!node || depth > 6 || out.length > 80) return;
1630
- if (typeof node === 'string') {
1631
- out.push(node);
1632
- return;
1633
- }
1634
- if (Array.isArray(node)) {
1635
- for (const item of node) collectStrings(item, out, depth + 1);
1636
- return;
1637
- }
1638
- if (typeof node === 'object') {
1639
- for (const key of Object.keys(node)) collectStrings(node[key], out, depth + 1);
1640
- }
1641
- }
1642
-
1643
- /**
1644
- * 从任意形状的回应里找出图片:二进制 / b64 / data-url / 外链,全都认。
1645
- */
1646
- export function decodeImagePayload(payload, binary) {
1647
- if (binary && looksLikeImage(binary)) return { bytes: binary, contentType: sniffType(binary) };
1648
- if (!payload) throw new Error('生图接口没有返回图片');
1649
-
1650
- const strings = [];
1651
- collectStrings(payload, strings, 0);
1652
-
1653
- for (const text of strings) {
1654
- const image = base64ToImage(text);
1655
- if (image) return image;
1656
- }
1657
- for (const text of strings) {
1658
- if (!/^https?:\/\//i.test(text)) continue;
1659
- if (/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(text)) return { url: text };
1660
- }
1661
- for (const text of strings) {
1662
- if (/^https?:\/\//i.test(text)) return { url: text };
1663
- }
1664
- throw new Error('生图接口返回格式不认识');
1665
- }
1666
-
1667
- /** 按上限读取响应体;有 Content-Length 时先拒绝明显超限的响应。 */
1668
- export async function readResponseBytes(response, maxBytes) {
1669
- const limit = Number(maxBytes) > 0 ? Number(maxBytes) : Infinity;
1670
- const declared = Number(response.headers.get('content-length'));
1671
- if (Number.isFinite(declared) && declared > limit) {
1672
- try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
1673
- throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
1674
- }
1675
- const body = response.body;
1676
- if (!body) {
1677
- const buffer = Buffer.from(await response.arrayBuffer());
1678
- if (buffer.length > limit) throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
1679
- return buffer;
1680
- }
1681
- // Content-Length 可信时直接写进预分配 buffer,避免 chunks + Buffer.concat 的 2 倍峰值。
1682
- if (Number.isFinite(declared) && declared > 0) {
1683
- const out = Buffer.allocUnsafe(Math.floor(declared));
1684
- let offset = 0;
1685
- let overflow = null;
1686
- for await (const chunk of body) {
1687
- const buffer = Buffer.from(chunk);
1688
- if (offset + buffer.length > limit) {
1689
- try { await body.cancel(); } catch (_error) { /* ignore */ }
1690
- throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
1691
- }
1692
- if (!overflow && offset + buffer.length <= out.length) {
1693
- buffer.copy(out, offset);
1694
- } else {
1695
- if (!overflow) overflow = [out.subarray(0, offset)];
1696
- overflow.push(buffer);
1697
- }
1698
- offset += buffer.length;
1699
- }
1700
- if (overflow) return Buffer.concat(overflow, offset);
1701
- return offset === out.length ? out : Buffer.from(out.subarray(0, offset));
1702
- }
1703
- const chunks = [];
1704
- let total = 0;
1705
- for await (const chunk of body) {
1706
- const buffer = Buffer.from(chunk);
1707
- total += buffer.length;
1708
- if (total > limit) {
1709
- try { await body.cancel(); } catch (_error) { /* ignore */ }
1710
- throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
1711
- }
1712
- chunks.push(buffer);
1713
- }
1714
- return Buffer.concat(chunks);
1715
- }
1716
-
1717
- export const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
1718
-
1719
- export async function fetchImageUrl(url, signal, maxBytes = MAX_IMAGE_BYTES) {
1720
- const response = await request(url, { signal: signal });
1721
- if (!response.ok) throw new Error('下载生成图失败:HTTP ' + response.status);
1722
- const bytes = await readResponseBytes(response, maxBytes);
1723
- if (!looksLikeImage(bytes)) throw new Error('下载生成图失败:返回内容不是有效图片');
1724
- return { bytes: bytes, contentType: sniffType(bytes) };
1725
- }
1726
-
1727
- /* ----------------------------------------------------------------- errors */
1728
-
1729
- export function extractMessage(text) {
1730
- const raw = String(text || '').trim();
1731
- if (!raw) return '';
1732
- try {
1733
- const parsed = JSON.parse(raw);
1734
- if (parsed && typeof parsed === 'object') {
1735
- if (parsed.error && typeof parsed.error === 'object' && parsed.error.message) return String(parsed.error.message);
1736
- if (typeof parsed.error === 'string') return parsed.error;
1737
- if (parsed.message) return String(parsed.message);
1738
- if (parsed.msg) return String(parsed.msg);
1739
- }
1740
- } catch (_error) {
1741
- /* 不是 JSON,原样返回 */
1742
- }
1743
- return raw;
1744
- }
1745
-
1746
- function detectDroppableField(message) {
1747
- const token = "['\"]?([A-Za-z_][A-Za-z0-9_.-]*)['\"]?";
1748
- const patterns = [
1749
- new RegExp('unknown parameter:\\s*' + token, 'i'),
1750
- new RegExp('unrecognized request argument supplied:\\s*' + token, 'i'),
1751
- new RegExp('unknown (?:field|parameter|property)\\s*' + token, 'i'),
1752
- new RegExp('(?:extra|unexpected|unsupported|not supported) (?:field|parameter|property)[^A-Za-z0-9_]*' + token, 'i')
1753
- ];
1754
- for (const pattern of patterns) {
1755
- const hit = pattern.exec(message);
1756
- if (hit && hit[1]) return hit[1].trim();
1757
- }
1758
- return null;
1759
- }
2385
+ /* ----------------------------------------------------------------- resize */
1760
2386
 
1761
- /** 从结构化错误里取 param 字段;不少兼容网关只在 error.param 里给字段名。 */
1762
- function extractErrorParam(text) {
1763
- try {
1764
- const parsed = JSON.parse(String(text || ''));
1765
- const param = (parsed && parsed.error && parsed.error.param) || (parsed && parsed.param);
1766
- return typeof param === 'string' && /^[A-Za-z_][A-Za-z0-9_.-]*$/.test(param) ? param.trim() : null;
1767
- } catch (_error) {
1768
- return null;
2387
+ /** 居中裁切一段 RGBA(cover 用):比例不符时裁掉多余的一边,而不是拉伸。 */
2388
+ function cropRgba(rgba, width, height, left, top, cropWidth, cropHeight) {
2389
+ const out = new Uint8Array(cropWidth * cropHeight * 4);
2390
+ for (let y = 0; y < cropHeight; y++) {
2391
+ const from = ((top + y) * width + left) * 4;
2392
+ out.set(rgba.subarray(from, from + cropWidth * 4), y * cropWidth * 4);
1769
2393
  }
1770
- }
1771
-
1772
- /**
1773
- * 把各家的错误归结成几类,调用方只按 kind 决策。
1774
- */
1775
- export function classifyFailure(status, text) {
1776
- const message = extractMessage(text) || ('HTTP ' + status);
1777
- const drop = detectDroppableField(message) || extractErrorParam(text);
1778
- if (drop) return { kind: 'param', drop: drop, message: message };
1779
- if (/size/i.test(message) && /(invalid|unsupported|below|minimum|maximum|too small|too large|budget)/i.test(message)) {
1780
- return { kind: 'size', message: message };
2394
+ return out;
2395
+ }
2396
+
2397
+ function coverCrop(image, targetWidth, targetHeight) {
2398
+ const targetRatio = targetWidth / targetHeight;
2399
+ const ratio = image.width / image.height;
2400
+ if (Math.abs(ratio - targetRatio) <= 0.01) return null;
2401
+ let cropWidth = image.width;
2402
+ let cropHeight = Math.round(image.width / targetRatio);
2403
+ if (cropHeight > image.height) {
2404
+ cropHeight = image.height;
2405
+ cropWidth = Math.round(image.height * targetRatio);
1781
2406
  }
1782
- if (status === 401 || status === 403) return { kind: 'auth', message: message };
1783
- if (status === 404) return { kind: 'endpoint', message: message };
1784
- if (status === 413) return { kind: 'payload', message: message };
1785
- if (status === 429) return { kind: 'rate', message: message, retryable: true };
1786
- if (status >= 500) return { kind: 'upstream', message: message, retryable: true };
1787
- return { kind: 'unknown', message: message };
2407
+ if (cropWidth <= 0 || cropHeight <= 0) return null;
2408
+ const left = Math.max(0, Math.floor((image.width - cropWidth) / 2));
2409
+ const top = Math.max(0, Math.floor((image.height - cropHeight) / 2));
2410
+ return {
2411
+ width: cropWidth,
2412
+ height: cropHeight,
2413
+ rgba: cropRgba(image.rgba, image.width, image.height, left, top, cropWidth, cropHeight)
2414
+ };
1788
2415
  }
1789
2416
 
1790
- /* ----------------------------------------------------------------- resize */
1791
-
1792
2417
  /**
1793
2418
  * 生成尺寸被抬大以后,把结果缩回用户要的尺寸。
1794
2419
  * PNG 走自带的纯 JS 面积平均缩放(无依赖、任何进程可用);
2420
+ * 'cover' 会先把比例裁成目标比例(平台无视比例时用),默认 'exact' 直接重采样。
1795
2421
  * 其它格式再试 Electron 的 nativeImage。
2422
+ *
2423
+ * 目标尺寸来自对话模型可填的 size:分配像素缓冲区前必须先挡住超大值,
2424
+ * 否则 `99999x99999` 会直接申请几十 GB 内存。上限与图片解码的 32MP 预算一致。
1796
2425
  */
1797
- export function resizeTo(bytes, width, height) {
2426
+ const MAX_RESIZE_SIDE = 16384;
2427
+ const MAX_RESIZE_PIXELS = 32 * 1024 * 1024;
2428
+
2429
+ export function resizeTo(bytes, width, height, mode) {
1798
2430
  if (!bytes || !width || !height) return null;
2431
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0) return null;
2432
+ if (width > MAX_RESIZE_SIDE || height > MAX_RESIZE_SIDE || width * height > MAX_RESIZE_PIXELS) return null;
2433
+ let cropped = false;
1799
2434
  try {
1800
2435
  const image = decodePng(bytes);
1801
2436
  if (image) {
1802
- if (image.width === width && image.height === height) return { bytes: bytes, contentType: 'image/png', resized: false };
1803
- const rgba = resizeRgba(image.rgba, image.width, image.height, width, height);
1804
- return { bytes: encodePng(rgba, width, height), contentType: 'image/png', resized: true };
2437
+ if (image.width === width && image.height === height) return { bytes: bytes, contentType: 'image/png', resized: false, cropped: false };
2438
+ let source = image;
2439
+ if (mode === 'cover') {
2440
+ const next = coverCrop(image, width, height);
2441
+ if (next) { source = next; cropped = true; }
2442
+ }
2443
+ const rgba = resizeRgba(source.rgba, source.width, source.height, width, height);
2444
+ return { bytes: encodePng(rgba, width, height), contentType: 'image/png', resized: true, cropped: cropped };
1805
2445
  }
1806
2446
  } catch (_error) {
1807
2447
  /* 落到下面的 Electron 通路 */
@@ -1813,11 +2453,29 @@ export function resizeTo(bytes, width, height) {
1813
2453
  const image = nativeImage.createFromBuffer(bytes);
1814
2454
  if (!image || image.isEmpty()) return null;
1815
2455
  const size = image.getSize();
1816
- if (size.width === width && size.height === height) return { bytes: bytes, contentType: 'image/png', resized: false };
1817
- const resized = image.resize({ width: width, height: height, quality: 'best' });
2456
+ if (size.width === width && size.height === height) return { bytes: bytes, contentType: 'image/png', resized: false, cropped: false };
2457
+ let source = image;
2458
+ if (mode === 'cover' && size.width && size.height) {
2459
+ const targetRatio = width / height;
2460
+ if (Math.abs(size.width / size.height - targetRatio) > 0.01) {
2461
+ let cropWidth = size.width;
2462
+ let cropHeight = Math.round(size.width / targetRatio);
2463
+ if (cropHeight > size.height) {
2464
+ cropHeight = size.height;
2465
+ cropWidth = Math.round(size.height * targetRatio);
2466
+ }
2467
+ if (cropWidth > 0 && cropHeight > 0) {
2468
+ const left = Math.max(0, Math.floor((size.width - cropWidth) / 2));
2469
+ const top = Math.max(0, Math.floor((size.height - cropHeight) / 2));
2470
+ source = image.crop({ x: left, y: top, width: cropWidth, height: cropHeight });
2471
+ cropped = true;
2472
+ }
2473
+ }
2474
+ }
2475
+ const resized = source.resize({ width: width, height: height, quality: 'best' });
1818
2476
  const png = resized.toPNG();
1819
2477
  if (!png || !png.length) return null;
1820
- return { bytes: png, contentType: 'image/png', resized: true };
2478
+ return { bytes: png, contentType: 'image/png', resized: true, cropped: cropped };
1821
2479
  } catch (_error) {
1822
2480
  return null;
1823
2481
  }