dsh-mo-image 0.5.1 → 0.6.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/index.js CHANGED
@@ -9,17 +9,18 @@ import { isIP } from 'node:net';
9
9
  import {
10
10
  resolveAdapter, describeAdapter, fitSize, escalateSize,
11
11
  qualityForAdapter, qualityOptionsFor, filterImageModels,
12
- prepareGenerate, prepareEdit, prepareAsync, pollUrlFor, pollHeaders,
12
+ prepareGenerate, prepareEdit, prepareAsync, preparePhaseAsync, pollUrlFor, pollHeaders,
13
13
  readTaskId, readTaskState, decodeImagePayload, classifyFailure,
14
14
  fetchImageUrl, resizeTo, adapterBase, readResponseBytes, looksLikeImage, sniffType,
15
15
  listProviderModelEntries, adapterManifest, localPresetManifest, providerPresetManifest, MAX_IMAGE_BYTES,
16
- adapterSupportsKind
16
+ adapterSupportsKind, analyzeComfyWorkflow
17
17
  } from './adapters.js';
18
18
  import { promptSectionText, resolvePromptProfile, settingsPayload } from './prompt-profiles.js';
19
19
  import { request, setNetworkLogger } from './net.js';
20
20
  import { configWriteReason } from './config-guard.js';
21
21
  import { localizedError, errorBody } from './localized-error.js';
22
22
  import { createUpdateService } from './update-service.js';
23
+ import { MAPPING_KEYS, DEFAULT_EXPOSED } from './comfy-workflow.js';
23
24
 
24
25
  const PLUGIN = 'dsh-mo-image';
25
26
  function dshHome() {
@@ -46,7 +47,7 @@ function pluginVersion() {
46
47
  }
47
48
  }
48
49
  const UPDATE_CHECK_TTL_MS = 12 * 60 * 60 * 1000;
49
- const MAX_BODY = 2 * 1024 * 1024;
50
+ const MAX_BODY = 8 * 1024 * 1024;
50
51
  const MAX_REF_BYTES = 15 * 1024 * 1024;
51
52
  const MAX_REF_TOTAL = 48 * 1024 * 1024;
52
53
  const MAX_JSON_EDIT_TOTAL = 10 * 1024 * 1024;
@@ -114,10 +115,9 @@ function emptyConfig() {
114
115
  };
115
116
  }
116
117
  /** 质量值由适配器的 options 决定;这里只保留旧配置里的合法字符串,具体对齐交给 adapter。 */
117
- const QUALITY_VALUES = new Set(['off', 'low', 'medium', 'high', 'max', 'auto', 'standard', 'hd', 'default', 'quality', 'turbo']);
118
+ const QUALITY_VALUES = new Set(['off', 'low', 'medium', 'high', 'xhigh', 'max', 'auto', 'standard', 'hd', 'default', 'quality', 'turbo']);
118
119
  function normalizeQuality(value) {
119
120
  const raw = String(value || '').trim().toLowerCase();
120
- if (raw === 'xhigh') return 'max';
121
121
  return QUALITY_VALUES.has(raw) ? raw : 'high';
122
122
  }
123
123
  function normalizeDefaults(raw) {
@@ -151,7 +151,75 @@ function resolveSizeArg(defaults) {
151
151
  return 'none';
152
152
  }
153
153
  /** 每个模型的可选配置(目前只有自定义工作流),只保留仍存在的模型,限制体积。 */
154
- const MODEL_WORKFLOW_MAX = 200000;
154
+ const MODEL_WORKFLOW_MAX = 2000000;
155
+ /**
156
+ * 映射要么完整,要么没有:任何一项形状不对就整体丢弃,
157
+ * 免得生成时一半注入一半不注入,产出用户看不懂的图。
158
+ */
159
+ function sanitizeMapping(raw) {
160
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
161
+ const out = {};
162
+ for (const key of MAPPING_KEYS) {
163
+ if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
164
+ const value = raw[key];
165
+ if (value === null) { out[key] = null; continue; }
166
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
167
+ const node = typeof value.node === 'string' ? value.node.trim() : '';
168
+ const input = typeof value.input === 'string' ? value.input.trim() : '';
169
+ if (!node || !input) return undefined;
170
+ out[key] = { node, input };
171
+ }
172
+ return Object.keys(out).length ? out : undefined;
173
+ }
174
+
175
+ /**
176
+ * 可调参数清单来自解析结果,形状固定:name/node/input/type/default[/options]。
177
+ * 任何一项不合法就整体丢弃——宁可不让模型看到,也不要报一个假的默认值。
178
+ */
179
+ function sanitizeParams(raw) {
180
+ if (!Array.isArray(raw)) return undefined;
181
+ const out = [];
182
+ for (const item of raw) {
183
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
184
+ const name = typeof item.name === 'string' ? item.name.trim() : '';
185
+ const node = typeof item.node === 'string' ? item.node.trim() : '';
186
+ const input = typeof item.input === 'string' ? item.input.trim() : '';
187
+ if (!name || !node || !input) return undefined;
188
+ const param = { name, node, input, type: String(item.type || 'string') };
189
+ if (Array.isArray(item.options)) param.options = item.options.map(String).slice(0, 64);
190
+ if (item.role === true) param.role = true;
191
+ if (item.expose === false) param.expose = false;
192
+ if (Array.isArray(item.candidates)) {
193
+ const seen = new Set();
194
+ param.candidates = [];
195
+ for (const candidate of item.candidates) {
196
+ if (!candidate || typeof candidate !== 'object') continue;
197
+ const node = typeof candidate.node === 'string' ? candidate.node.trim() : '';
198
+ const input = typeof candidate.input === 'string' ? candidate.input.trim() : '';
199
+ const key = node + '::' + input;
200
+ if (!node || !input || seen.has(key)) continue;
201
+ seen.add(key);
202
+ param.candidates.push({ node, input });
203
+ }
204
+ if (!param.candidates.length) delete param.candidates;
205
+ }
206
+ out.push(param);
207
+ }
208
+ return out.length ? out : undefined;
209
+ }
210
+
211
+ /** 逐项暴露开关:只存布尔值,未出现的项按角色/可调参数各自默认。 */
212
+ function sanitizeExpose(raw) {
213
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
214
+ const out = {};
215
+ for (const [key, value] of Object.entries(raw)) {
216
+ const name = String(key || '').trim();
217
+ if (!name || typeof value !== 'boolean') continue;
218
+ out[name] = value;
219
+ }
220
+ return Object.keys(out).length ? out : undefined;
221
+ }
222
+
155
223
  export function normalizeModelOptions(raw, models) {
156
224
  const out = {};
157
225
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
@@ -162,7 +230,14 @@ export function normalizeModelOptions(raw, models) {
162
230
  if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
163
231
  const workflow = typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
164
232
  if (!workflow || workflow.length > MODEL_WORKFLOW_MAX) continue;
165
- out[model] = { workflow };
233
+ const mapping = sanitizeMapping(entry.mapping);
234
+ const params = sanitizeParams(entry.params);
235
+ const expose = sanitizeExpose(entry.expose);
236
+ const next = { workflow };
237
+ if (mapping) next.mapping = mapping;
238
+ if (params) next.params = params;
239
+ if (expose) next.expose = expose;
240
+ out[model] = next;
166
241
  }
167
242
  return out;
168
243
  }
@@ -186,6 +261,11 @@ export function normalizeConfig(raw) {
186
261
  optionalKey: !!item.optionalKey,
187
262
  protocol: String(item.protocol || 'openai-images'), adapter: String(item.adapter || ''), models, names
188
263
  };
264
+ // Responses API 需要一个能调工具的主模型;只有这个适配器要留。
265
+ if (provider.adapter === 'openai-responses') {
266
+ const hostModel = String(item.hostModel || '').trim();
267
+ if (hostModel) provider.hostModel = hostModel;
268
+ }
189
269
  // 自定义工作流只有 ComfyUI 适配器会读;别的提供商留着也没用,直接丢弃。
190
270
  if (provider.adapter === 'comfyui' && Object.keys(modelOptions).length > 0) provider.modelOptions = modelOptions;
191
271
  if (key) provider.key = key;
@@ -320,9 +400,29 @@ function activeImageState(store) {
320
400
  return {
321
401
  provider, model, adapter, models: provider.models || [],
322
402
  editModel: model, editAdapter: adapter,
403
+ // 只有 ComfyUI 部署才有工作流参数;用户关掉暴露时不返回。
404
+ workflowParams: workflowParamsOf(provider, model, adapter),
323
405
  promptOptimization: config.defaults.promptOptimization !== false, defaults: config.defaults
324
406
  };
325
407
  }
408
+
409
+ /** 当前模型的工作流可调参数;非 ComfyUI 或用户逐项关闭时不返回。 */
410
+ /** 当前模型的 ComfyUI 工作流参数;角色参数默认暴露,可调参数默认不暴露。 */
411
+ export function workflowParamsOf(provider, model, adapter) {
412
+ try {
413
+ if (!adapter || adapter.id !== 'comfyui') return undefined;
414
+ const entry = provider && provider.modelOptions ? provider.modelOptions[model] : null;
415
+ if (!entry || !Array.isArray(entry.params)) return undefined;
416
+ const expose = entry.expose && typeof entry.expose === 'object' ? entry.expose : {};
417
+ const exposed = entry.params.filter((param) => {
418
+ if (!param) return false;
419
+ const explicit = expose[param.name];
420
+ if (explicit !== undefined) return explicit !== false;
421
+ return DEFAULT_EXPOSED.has(param.name);
422
+ });
423
+ return exposed.length ? exposed : undefined;
424
+ } catch (_error) { return undefined; }
425
+ }
326
426
  function canUseCredentials(store) {
327
427
  const credentials = credentialsService(store);
328
428
  return !!(credentials && typeof credentials.describe === 'function' && typeof credentials.resolve === 'function' && typeof credentials.set === 'function');
@@ -638,16 +738,25 @@ function unsupportedModelMessage(kind, failure) {
638
738
  * 提交阶段的参数错误照旧自愈(摘字段 / 抬尺寸),轮询阶段只对 429、5xx 继续等。
639
739
  */
640
740
  async function callAsyncImage(kind, adapter, provider, input, signal) {
641
- if (kind === 'edit') throw new Error('该模型(' + adapter.label + ')暂不支持参考图编辑,请到设置里换一个编辑模型。');
741
+ const phase = adapter.async && typeof adapter.async === 'object' ? adapter.async : null;
742
+ if (kind === 'edit' && !(phase && phase.edit)) {
743
+ throw new Error('该模型(' + adapter.label + ')暂不支持参考图编辑,请到设置里换一个编辑模型。');
744
+ }
642
745
  const drops = new Set();
643
746
  let fitted = input.fitted;
644
747
  let submission = null;
645
748
  let lastFailure = null;
749
+ let lastNote = '';
646
750
  let retries = 0;
647
751
 
648
752
  for (let attempt = 1; attempt <= 5; attempt++) {
649
- const built = prepareAsync(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops);
650
- const response = await request(adapterBase(provider) + built.path, {
753
+ const attemptInput = Object.assign({}, input, { fitted: fitted });
754
+ const built = phase
755
+ ? await preparePhaseAsync(adapter, provider, attemptInput, signal)
756
+ : prepareAsync(adapter, provider, attemptInput, drops);
757
+ if (built.note) lastNote = built.note;
758
+ const submitUrl = /^https?:\/\//i.test(built.path) ? built.path : adapterBase(provider) + built.path;
759
+ const response = await request(submitUrl, {
651
760
  method: 'POST', headers: built.headers, body: built.body, signal: signal
652
761
  });
653
762
  const buffer = await readResponseBytes(response, 2 * 1024 * 1024);
@@ -684,28 +793,42 @@ async function callAsyncImage(kind, adapter, provider, input, signal) {
684
793
  }
685
794
  if (!submission) throw new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '任务提交失败' }));
686
795
 
687
- const taskId = readTaskId(adapter, submission);
688
- if (!taskId) throw new Error('任务提交后没有拿到 task_id:' + JSON.stringify(submission).slice(0, 200));
689
- logHost(kind + ' async task=' + taskId + ' submitted');
796
+ const taskId = phase ? String(submission.id || '') : readTaskId(adapter, submission);
797
+ if (!phase && !taskId) throw new Error('任务提交后没有拿到 task_id:' + JSON.stringify(submission).slice(0, 200));
798
+ logHost(kind + ' async task=' + (taskId || 'unknown') + ' submitted');
690
799
 
691
800
  const poll = adapter.poll || {};
692
- const deadline = Date.now() + (Number(poll.timeoutMs) || 300000);
693
- let interval = Number(poll.intervalMs) || 2000;
801
+ const deadline = Date.now() + (phase ? (Number(phase.timeoutMs) || 300000) : (Number(poll.timeoutMs) || 300000));
802
+ let interval = phase ? (Number(phase.intervalMs) || 2000) : (Number(poll.intervalMs) || 2000);
694
803
  let state = null;
695
804
  while (Date.now() < deadline) {
696
805
  await sleep(interval);
697
- const response = await request(pollUrlFor(adapter, provider, taskId), {
698
- method: 'GET', headers: pollHeaders(provider), signal: signal
806
+ const target = phase ? String(phase.pollUrl(submission)) : pollUrlFor(adapter, provider, taskId);
807
+ const headers = phase && typeof phase.pollHeaders === 'function' ? phase.pollHeaders(provider) : pollHeaders(provider);
808
+ const response = await request(target, {
809
+ method: 'GET', headers: headers, signal: signal
699
810
  });
700
811
  const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
812
+ // fal 用 202 表示「还在跑」,不能当成错误。
813
+ if (phase && response.status === 202) {
814
+ interval = Math.min(Math.round(interval * 1.15), 5000);
815
+ continue;
816
+ }
701
817
  const payload = safeJson(buffer);
702
818
  if (!response.ok || !payload) {
703
819
  const failure = classifyFailure(response.status, buffer.toString('utf8'));
704
820
  if (failure.retryable) continue;
705
821
  throw new Error(imageErrorText(failure));
706
822
  }
707
- state = readTaskState(adapter, payload);
823
+ state = phase ? phase.statusOf(payload) : readTaskState(adapter, payload);
708
824
  if (state.state === 'success') {
825
+ if (phase) {
826
+ const resolved = await phase.resolve(payload, provider, signal, submission);
827
+ if (!resolved) throw new Error('生图任务没有返回图片');
828
+ const image = resolved.bytes ? resolved : await fetchImageUrl(resolved.url, signal);
829
+ logHost(kind + ' async task=' + (taskId || 'unknown') + ' done');
830
+ return { fitted: fitted, bytes: image.bytes, contentType: image.contentType, note: lastNote };
831
+ }
709
832
  const decoded = decodeImagePayload(state.node, null);
710
833
  const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
711
834
  logHost(kind + ' async task=' + taskId + ' done');
@@ -716,9 +839,9 @@ async function callAsyncImage(kind, adapter, provider, input, signal) {
716
839
  }
717
840
  interval = Math.min(Math.round(interval * 1.15), 5000);
718
841
  }
719
- throw new Error('生图任务超时(' + taskId + (state ? ',最后状态 ' + state.status : '') + ')');
842
+ throw new Error('生图任务超时(' + (taskId || 'job') + (state ? ',最后状态 ' + state.status : '') + ')');
720
843
  }
721
- async function callImageApi(kind, adapter, provider, input, signal) {
844
+ export async function callImageApi(kind, adapter, provider, input, signal) {
722
845
  if (!adapterSupportsKind(adapter, kind)) {
723
846
  throw new Error('该模型不支持' + (kind === 'edit' ? '图生图' : '文生图')
724
847
  + '(' + String(input.model || adapter.label) + ')。请到设置 → 生图模型换一个支持它的模型。');
@@ -726,7 +849,7 @@ async function callImageApi(kind, adapter, provider, input, signal) {
726
849
  if (adapter.async) return callAsyncImage(kind, adapter, provider, input, signal);
727
850
  if (typeof adapter.execute === 'function') {
728
851
  const out = await adapter.execute(kind, provider, input, signal);
729
- return { fitted: input.fitted, bytes: out.bytes, contentType: out.contentType };
852
+ return { fitted: input.fitted, bytes: out.bytes, contentType: out.contentType, note: out.note };
730
853
  }
731
854
  const fieldNames = (adapter.editFields && adapter.editFields.length) ? adapter.editFields : ['image'];
732
855
  const drops = new Set();
@@ -792,7 +915,7 @@ export function finalizeImage(result) {
792
915
  let bytes = result.bytes;
793
916
  let contentType = result.contentType;
794
917
  let fitted = result.fitted;
795
- let note = '';
918
+ let note = result && result.note ? String(result.note) : '';
796
919
  const wanted = fitted && fitted.requested;
797
920
  const wantedPixels = wanted ? wanted.width * wanted.height : 0;
798
921
  const fittedPixels = fitted ? (fitted.width || 0) * (fitted.height || 0) : 0;
@@ -810,7 +933,8 @@ export function finalizeImage(result) {
810
933
  logHost('resize unavailable, keep ' + fitted.size + '(用户要 ' + wanted.text + ')');
811
934
  }
812
935
  } else if (fitted && fitted.adjusted && wanted && fittedPixels < wantedPixels) {
813
- note = '该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + wanted.text + ',未放大)。';
936
+ const sizeNote = '该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + wanted.text + ',未放大)。';
937
+ note = note ? note + ';' + sizeNote : sizeNote;
814
938
  logHost('keep model max ' + fitted.size + '(用户要 ' + wanted.text + ',不放大)');
815
939
  }
816
940
  return { bytes: bytes, contentType: contentType, fitted: fitted, note: note };
@@ -825,6 +949,18 @@ async function saveImage(bytes, contentType, provider, model, size, exec) {
825
949
  await writeFile(file, bytes);
826
950
  return { file, filename, provider: provider.name || provider.id, model, size, bytes: bytes.length, contentType };
827
951
  }
952
+ /** 只保留有值的 params;别的形状一律当没传。 */
953
+ function readParamsArg(args) {
954
+ const raw = args && args.params;
955
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
956
+ const out = {};
957
+ for (const [key, value] of Object.entries(raw)) {
958
+ if (value === undefined || value === null) continue;
959
+ out[key] = value;
960
+ }
961
+ return Object.keys(out).length ? out : null;
962
+ }
963
+
828
964
  async function generate(args, exec, store) {
829
965
  const prompt = String(args.prompt || '').trim();
830
966
  if (!prompt) throw new Error('prompt 不能为空:先按当前模型的提示词公式写好完整提示词。');
@@ -836,18 +972,23 @@ async function generate(args, exec, store) {
836
972
  const adapter = resolveAdapter(provider, model);
837
973
  const profile = resolvePromptProfile(model, adapter);
838
974
  const defaults = (config && config.defaults) || {};
839
- const quality = qualityForAdapter(adapter, resolveQuality(defaults));
975
+ const quality = qualityForAdapter(adapter, resolveQuality(defaults), model);
840
976
  const fitted = fitSize(adapter, resolveSizeArg(defaults));
841
977
  if (fitted.rejected) throw new Error(fitted.reason);
842
978
  logHost('generate adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + (fitted.adjusted ? '(' + fitted.reason + ')' : ''));
843
979
  const signal = makeSignal(exec, 360000);
980
+ const extraParams = readParamsArg(args);
981
+ const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
844
982
  const result = await callImageApi('generate', adapter, provider, {
845
983
  model: model, prompt: prompt, negativePrompt: negativePrompt || undefined,
846
- fitted: fitted, quality: quality
984
+ fitted: fitted, quality: quality, params: extraParams
847
985
  }, signal);
848
986
  const final = finalizeImage(result);
849
987
  const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
850
- if (final.note) saved.note = final.note;
988
+ const notes = [];
989
+ if (final.note) notes.push(final.note);
990
+ if (unsupported.length) notes.push('当前模型不支持工作流参数,已忽略:' + unsupported.join('、'));
991
+ if (notes.length) saved.note = notes.join(';');
851
992
  return saved;
852
993
  }
853
994
  const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
@@ -989,20 +1130,25 @@ async function edit(args, exec, store) {
989
1130
  const provider = await resolveProviderCredential(store, picked.provider);
990
1131
  const adapter = resolveAdapter(provider, model);
991
1132
  const profile = resolvePromptProfile(model, adapter);
992
- const quality = qualityForAdapter(adapter, resolveQuality(defaults));
1133
+ const quality = qualityForAdapter(adapter, resolveQuality(defaults), model);
993
1134
  const fitted = fitSize(adapter, resolveSizeArg(defaults));
994
1135
  if (fitted.rejected) throw new Error(fitted.reason);
995
1136
  const signal = makeSignal(exec, 360000);
996
1137
  const totalLimit = referenceLimitFor(adapter);
997
1138
  const images = await readReferences(sources, signal, totalLimit);
998
1139
  logHost('edit adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + ' refs=' + images.length);
1140
+ const extraParams = readParamsArg(args);
1141
+ const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
999
1142
  const result = await callImageApi('edit', adapter, provider, {
1000
1143
  model: model, prompt: prompt, negativePrompt: negativePrompt || undefined,
1001
- fitted: fitted, quality: quality, images: images
1144
+ fitted: fitted, quality: quality, images: images, params: extraParams
1002
1145
  }, signal);
1003
1146
  const final = finalizeImage(result);
1004
1147
  const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
1005
- if (final.note) saved.note = final.note;
1148
+ const notes = [];
1149
+ if (final.note) notes.push(final.note);
1150
+ if (unsupported.length) notes.push('当前模型不支持工作流参数,已忽略:' + unsupported.join('、'));
1151
+ if (notes.length) saved.note = notes.join(';');
1006
1152
  return saved;
1007
1153
  }
1008
1154
 
@@ -1131,7 +1277,22 @@ async function modelsForRequest(store, body) {
1131
1277
  try { adapter = resolveAdapter(Object.assign({}, provider, { adapter: 'openai-images' }), ''); } catch (_error) { /* keep original */ }
1132
1278
  }
1133
1279
  if (!adapter || typeof adapter.listModels !== 'function') throw localizedError(new Error('该部署方式不支持获取模型列表'), 'models.unsupported');
1134
- const entries = await listProviderModelEntries(adapter, provider, AbortSignal.timeout(20000));
1280
+ let entries;
1281
+ try {
1282
+ entries = await listProviderModelEntries(adapter, provider, AbortSignal.timeout(20000));
1283
+ } catch (error) {
1284
+ // 没有 /models 的端点常见于网关和特殊版本:提醒用户手动填模型 ID,而不是只甩一个 404。
1285
+ const localized = error && error.localized;
1286
+ if (localized && localized.code === 'upstream.http' && Number(localized.params && localized.params.status) === 404) {
1287
+ const wrapped = localizedError(
1288
+ new Error('该地址没有模型列表接口(HTTP 404),请手动填写模型 ID。'),
1289
+ 'models.notFound'
1290
+ );
1291
+ wrapped.status = 404;
1292
+ throw wrapped;
1293
+ }
1294
+ throw error;
1295
+ }
1135
1296
  const seen = new Set();
1136
1297
  const allModels = [];
1137
1298
  const names = {};
@@ -1261,6 +1422,33 @@ export function apply(ctx, options = {}) {
1261
1422
  } catch (error) { logHost('models route error: ' + String(error)); return () => {}; }
1262
1423
  }, 'mo-image: models route');
1263
1424
 
1425
+ ctx.effect(() => {
1426
+ try {
1427
+ return ctx.webServer.register({
1428
+ kind: 'exact', path: '/api/mo-image/comfy/analyze',
1429
+ handler: async (req, res) => {
1430
+ try {
1431
+ assertLocalRequest(store, req, true);
1432
+ if (req.method !== 'POST') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
1433
+ const body = await readBody(req);
1434
+ const config = await readConfig(store);
1435
+ const providerId = String(body.providerId || '');
1436
+ const provider = (config.providers || []).find((item) => item && item.id === providerId) || null;
1437
+ const baseUrl = String(body.baseUrl || (provider && provider.baseUrl) || '').trim().replace(/\/+$/, '');
1438
+ if (!baseUrl) throw new Error('找不到这个提供商,或它没有填地址。');
1439
+ const workflow = String(body.workflow || '');
1440
+ if (!workflow.trim()) throw new Error('工作流是空的。');
1441
+ const merged = provider ? Object.assign({}, provider, { baseUrl }) : { baseUrl };
1442
+ const analysis = await analyzeComfyWorkflow({ base: baseUrl, provider: merged, workflow });
1443
+ return sendJson(res, 200, { ok: true, ...analysis });
1444
+ } catch (error) {
1445
+ return sendJson(res, 200, { ok: false, error: String(error && error.message ? error.message : error) });
1446
+ }
1447
+ }
1448
+ });
1449
+ } catch (error) { logHost('analyze route error: ' + String(error)); return () => {}; }
1450
+ }, 'mo-image: analyze route');
1451
+
1264
1452
  ctx.effect(() => {
1265
1453
  try {
1266
1454
  return ctx.webServer.register({
@@ -1389,7 +1577,8 @@ export function apply(ctx, options = {}) {
1389
1577
  model: { type: 'string' },
1390
1578
  promptOptimization: { type: 'boolean' },
1391
1579
  hint: { type: 'string' },
1392
- models: { type: 'array', items: { type: 'string' } }
1580
+ models: { type: 'array', items: { type: 'string' } },
1581
+ params: { type: 'array', items: { type: 'object' } }
1393
1582
  }
1394
1583
  },
1395
1584
  render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }]
@@ -1466,7 +1655,11 @@ export function apply(ctx, options = {}) {
1466
1655
  prompt: { type: 'string', description: 'Final prompt adapted to the active model when optimization is On; otherwise the user\'s original wording. Cover subject, action, environment, style, lighting, composition, and constraints; quote in-image text exactly.' },
1467
1656
  negative_prompt: { type: 'string', description: 'Optional prompt content. Only for models that support negative prompts; list artifacts and undesired elements. Omit otherwise.' },
1468
1657
  model: { type: 'string', description: 'Optional outside Auto mode: omit it and the picker\'s model is used. In Auto mode it is required — one id from the active provider list. A value other than the picked model is rejected; never use it to switch models.' },
1469
- provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' }
1658
+ provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' },
1659
+ params: {
1660
+ type: 'object', additionalProperties: true,
1661
+ description: 'Optional workflow parameters for the active model, as listed by mo_image_settings. Omit any you do not need: the workflow default applies. Keys the current model does not support are ignored and reported back in note.'
1662
+ }
1470
1663
  }
1471
1664
  },
1472
1665
  output, timeoutMs: 360000,
@@ -1491,7 +1684,11 @@ export function apply(ctx, options = {}) {
1491
1684
  images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute local paths or http(s) URLs; order matters and corresponds to 图1/图2.' },
1492
1685
  negative_prompt: { type: 'string', description: 'Optional prompt content. Only for models that support negative prompts; list artifacts and undesired elements. Omit otherwise.' },
1493
1686
  model: { type: 'string', description: 'Optional outside Auto mode: omit it and the picker\'s model is used. In Auto mode it is required — one id from the active provider list. A value other than the picked model is rejected; never use it to switch models.' },
1494
- provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' }
1687
+ provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' },
1688
+ params: {
1689
+ type: 'object', additionalProperties: true,
1690
+ description: 'Optional workflow parameters for the active model, as listed by mo_image_settings. Omit any you do not need: the workflow default applies. Keys the current model does not support are ignored and reported back in note.'
1691
+ }
1495
1692
  }
1496
1693
  },
1497
1694
  output, timeoutMs: 360000,
@@ -18,6 +18,7 @@ export const SERVER_ERROR_CODES = [
18
18
  'provider.missingKey',
19
19
  'provider.missingKeyWithRef',
20
20
  'models.unsupported',
21
+ 'models.notFound',
21
22
  'adapter.unknownProtocol',
22
23
  'adapter.notFound',
23
24
  'config.credentialsUnavailable',
@@ -237,6 +237,15 @@ export function describePromptProfile(profile) {
237
237
  * 非 Auto 模式不带模型清单——清单只在 Auto 模式需要挑模型时才出现。
238
238
  * @param {{provider?: object, model?: string, adapter?: {id?: string}|null, models?: string[], promptOptimization?: boolean}} state
239
239
  */
240
+ /** 尺寸这类参数旧配置里可能存成了 STRING,读的时候按名字纠正一次。 */
241
+ const NUMERIC_ROLES = new Set(['width', 'height', 'seed', 'steps', 'batch_size']);
242
+
243
+ function paramType(param) {
244
+ const type = String(param.type || 'STRING');
245
+ if (NUMERIC_ROLES.has(param.name) && (type === 'STRING' || type === 'string')) return 'INT';
246
+ return type;
247
+ }
248
+
240
249
  export function settingsPayload(state) {
241
250
  const provider = (state && state.provider) || null;
242
251
  const model = String((state && state.model) || '').trim();
@@ -262,6 +271,18 @@ export function settingsPayload(state) {
262
271
  payload.hint = optimized
263
272
  ? (PROFILE_HINTS[profile.id] || profile.label) + NEED_FULL_RULES
264
273
  : '直接用用户原话,不要扩写,不要补 negative prompt';
274
+ const workflowParams = Array.isArray(state && state.workflowParams)
275
+ ? state.workflowParams.filter((param) => param && param.expose !== false)
276
+ : [];
277
+ if (workflowParams.length) {
278
+ // 参数只走结构化的 params,hint 里不再重复列一遍名字。
279
+ payload.params = workflowParams.map((param) => {
280
+ const out = { name: param.name, type: paramType(param) };
281
+ if (Array.isArray(param.options)) out.options = param.options;
282
+ return out;
283
+ });
284
+ payload.hint += ';可用 params 覆盖工作流参数,不传则用工作流默认值';
285
+ }
265
286
  return payload;
266
287
  }
267
288