dsh-mo-image 0.5.0 → 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
- import { promptSectionText, resolvePromptProfile } from './prompt-profiles.js';
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');
@@ -350,38 +450,6 @@ async function publicConfig(store, config) {
350
450
  return Object.assign({}, config, { providers: providers });
351
451
  }
352
452
  /** 选择器用的模型能力表:目前先下发每个模型可用的质量档位。 */
353
- /** 本地部署器:没有云端鉴权,走本机或局域网接口。 */
354
- const LOCAL_ADAPTERS = new Set(['a1111', 'comfyui', 'swarmui', 'localai']);
355
-
356
- /**
357
- * 给模型看的模型清单:只有 id、显示名、部署方式,绝不带 key 或凭据引用。
358
- * 模型没有别的途径读配置(配置文件被守卫拦着),所以这里要够用。
359
- */
360
- export function modelListSnapshot(config) {
361
- const providers = Array.isArray(config && config.providers) ? config.providers : [];
362
- const activeId = String((config && config.active && config.active.providerId) || '');
363
- const activeModel = String((config && config.active && config.active.model) || '');
364
- const activeProvider = providers.find((item) => item.id === activeId) || null;
365
- const nameOf = (provider, model) => String((provider && provider.names && provider.names[model]) || '');
366
- return {
367
- auto: activeModel === 'auto',
368
- active: {
369
- providerId: activeProvider ? activeProvider.id : '',
370
- providerName: activeProvider ? activeProvider.name : '',
371
- model: activeModel,
372
- modelName: activeModel === 'auto' ? '' : nameOf(activeProvider, activeModel)
373
- },
374
- providers: providers.map((provider) => ({
375
- id: provider.id,
376
- name: provider.name,
377
- adapter: provider.adapter || '',
378
- local: !!provider.optionalKey || LOCAL_ADAPTERS.has(String(provider.adapter || '')),
379
- active: !!activeProvider && activeProvider.id === provider.id,
380
- models: (provider.models || []).map((model) => ({ id: model, name: nameOf(provider, model) }))
381
- }))
382
- };
383
- }
384
-
385
453
  function capabilityManifest(config) {
386
454
  return (config.providers || []).map((provider) => ({
387
455
  providerId: provider.id,
@@ -582,26 +650,28 @@ function pickProvider(config, purpose, args) {
582
650
  if (!provider) throw new Error('当前选中的生图提供商不存在,请到设置 → 生图模型重新选择。');
583
651
  // 严格只用用户选中的模型:不做「编辑时自动换 sunburst」这类回退,
584
652
  // 模型不支持对应能力时由 callImageApi 明确报「不支持」,而不是偷偷换一个。
585
- // 唯一例外是用户把选择器设为 Auto:此时才允许工具传 model,且必须在本提供商列表内。
653
+ // 唯一例外是用户把选择器设为 Auto:此时由工具传进来的 model 决定,且必须在本提供商列表内。
586
654
  const activeModel = String(active.model || '').trim();
587
655
  if (!activeModel) throw new Error('还没有选择当前生图模型。请先到 DSH 设置 → 生图模型 选择当前模型。');
588
656
  const requestedProvider = String((args && args.provider) || '').trim();
589
657
  const requestedModel = String((args && args.model) || '').trim();
590
- // 工具调用一律要带 model(避免对话模型凭记忆漏传/错传);提供商也可以带,但只用来核对。
658
+ // 模型由用户在设置里选定,工具参数只是可选的一致性核对。不让模型复述环境状态:
659
+ // 它会把对话历史里的旧 id 再抄一遍,用户中途切换模型后必定白失败一轮。
660
+ // 传了不一致的值仍然拒绝,防止对话模型自己换提供商/模型。
591
661
  if (requestedProvider && requestedProvider !== provider.id && requestedProvider !== provider.name) {
592
662
  throw new Error('提供商由用户在设置里固定(当前:' + (provider.name || provider.id) + '),请求的是 ' + requestedProvider + '。要换提供商请让用户在设置里切换。');
593
663
  }
594
- if (!requestedModel) {
595
- throw new Error('调用生图工具时必须传 model:当前选中的是 ' + (activeModel === 'auto' ? 'Auto(可从列表选择)' : activeModel) + '。');
596
- }
597
664
  let model;
598
665
  if (activeModel === 'auto') {
666
+ if (!requestedModel) {
667
+ throw new Error('Auto 模式下要由你选一个模型:' + ((provider.models || []).join(' / ') || '(列表为空,请让用户先在设置里添加模型)') + ',通过 model 传入。');
668
+ }
599
669
  if (!(provider.models || []).includes(requestedModel)) {
600
670
  throw new Error('Auto 模式只能选当前提供商列表里的模型:' + requestedModel + '。可选:' + ((provider.models || []).join(' / ') || '(列表为空)'));
601
671
  }
602
672
  model = requestedModel;
603
673
  } else {
604
- if (requestedModel !== activeModel) {
674
+ if (requestedModel && requestedModel !== activeModel) {
605
675
  throw new Error('当前选中的模型是 ' + activeModel + '(提供商 ' + (provider.name || provider.id) + '),请求的是 ' + requestedModel + '。模型只能由用户在设置里切换。');
606
676
  }
607
677
  model = activeModel;
@@ -668,16 +738,25 @@ function unsupportedModelMessage(kind, failure) {
668
738
  * 提交阶段的参数错误照旧自愈(摘字段 / 抬尺寸),轮询阶段只对 429、5xx 继续等。
669
739
  */
670
740
  async function callAsyncImage(kind, adapter, provider, input, signal) {
671
- 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
+ }
672
745
  const drops = new Set();
673
746
  let fitted = input.fitted;
674
747
  let submission = null;
675
748
  let lastFailure = null;
749
+ let lastNote = '';
676
750
  let retries = 0;
677
751
 
678
752
  for (let attempt = 1; attempt <= 5; attempt++) {
679
- const built = prepareAsync(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops);
680
- 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, {
681
760
  method: 'POST', headers: built.headers, body: built.body, signal: signal
682
761
  });
683
762
  const buffer = await readResponseBytes(response, 2 * 1024 * 1024);
@@ -714,28 +793,42 @@ async function callAsyncImage(kind, adapter, provider, input, signal) {
714
793
  }
715
794
  if (!submission) throw new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '任务提交失败' }));
716
795
 
717
- const taskId = readTaskId(adapter, submission);
718
- if (!taskId) throw new Error('任务提交后没有拿到 task_id:' + JSON.stringify(submission).slice(0, 200));
719
- 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');
720
799
 
721
800
  const poll = adapter.poll || {};
722
- const deadline = Date.now() + (Number(poll.timeoutMs) || 300000);
723
- 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);
724
803
  let state = null;
725
804
  while (Date.now() < deadline) {
726
805
  await sleep(interval);
727
- const response = await request(pollUrlFor(adapter, provider, taskId), {
728
- 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
729
810
  });
730
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
+ }
731
817
  const payload = safeJson(buffer);
732
818
  if (!response.ok || !payload) {
733
819
  const failure = classifyFailure(response.status, buffer.toString('utf8'));
734
820
  if (failure.retryable) continue;
735
821
  throw new Error(imageErrorText(failure));
736
822
  }
737
- state = readTaskState(adapter, payload);
823
+ state = phase ? phase.statusOf(payload) : readTaskState(adapter, payload);
738
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
+ }
739
832
  const decoded = decodeImagePayload(state.node, null);
740
833
  const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
741
834
  logHost(kind + ' async task=' + taskId + ' done');
@@ -746,9 +839,9 @@ async function callAsyncImage(kind, adapter, provider, input, signal) {
746
839
  }
747
840
  interval = Math.min(Math.round(interval * 1.15), 5000);
748
841
  }
749
- throw new Error('生图任务超时(' + taskId + (state ? ',最后状态 ' + state.status : '') + ')');
842
+ throw new Error('生图任务超时(' + (taskId || 'job') + (state ? ',最后状态 ' + state.status : '') + ')');
750
843
  }
751
- async function callImageApi(kind, adapter, provider, input, signal) {
844
+ export async function callImageApi(kind, adapter, provider, input, signal) {
752
845
  if (!adapterSupportsKind(adapter, kind)) {
753
846
  throw new Error('该模型不支持' + (kind === 'edit' ? '图生图' : '文生图')
754
847
  + '(' + String(input.model || adapter.label) + ')。请到设置 → 生图模型换一个支持它的模型。');
@@ -756,7 +849,7 @@ async function callImageApi(kind, adapter, provider, input, signal) {
756
849
  if (adapter.async) return callAsyncImage(kind, adapter, provider, input, signal);
757
850
  if (typeof adapter.execute === 'function') {
758
851
  const out = await adapter.execute(kind, provider, input, signal);
759
- return { fitted: input.fitted, bytes: out.bytes, contentType: out.contentType };
852
+ return { fitted: input.fitted, bytes: out.bytes, contentType: out.contentType, note: out.note };
760
853
  }
761
854
  const fieldNames = (adapter.editFields && adapter.editFields.length) ? adapter.editFields : ['image'];
762
855
  const drops = new Set();
@@ -822,7 +915,7 @@ export function finalizeImage(result) {
822
915
  let bytes = result.bytes;
823
916
  let contentType = result.contentType;
824
917
  let fitted = result.fitted;
825
- let note = '';
918
+ let note = result && result.note ? String(result.note) : '';
826
919
  const wanted = fitted && fitted.requested;
827
920
  const wantedPixels = wanted ? wanted.width * wanted.height : 0;
828
921
  const fittedPixels = fitted ? (fitted.width || 0) * (fitted.height || 0) : 0;
@@ -840,7 +933,8 @@ export function finalizeImage(result) {
840
933
  logHost('resize unavailable, keep ' + fitted.size + '(用户要 ' + wanted.text + ')');
841
934
  }
842
935
  } else if (fitted && fitted.adjusted && wanted && fittedPixels < wantedPixels) {
843
- note = '该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + wanted.text + ',未放大)。';
936
+ const sizeNote = '该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + wanted.text + ',未放大)。';
937
+ note = note ? note + ';' + sizeNote : sizeNote;
844
938
  logHost('keep model max ' + fitted.size + '(用户要 ' + wanted.text + ',不放大)');
845
939
  }
846
940
  return { bytes: bytes, contentType: contentType, fitted: fitted, note: note };
@@ -855,6 +949,18 @@ async function saveImage(bytes, contentType, provider, model, size, exec) {
855
949
  await writeFile(file, bytes);
856
950
  return { file, filename, provider: provider.name || provider.id, model, size, bytes: bytes.length, contentType };
857
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
+
858
964
  async function generate(args, exec, store) {
859
965
  const prompt = String(args.prompt || '').trim();
860
966
  if (!prompt) throw new Error('prompt 不能为空:先按当前模型的提示词公式写好完整提示词。');
@@ -866,18 +972,23 @@ async function generate(args, exec, store) {
866
972
  const adapter = resolveAdapter(provider, model);
867
973
  const profile = resolvePromptProfile(model, adapter);
868
974
  const defaults = (config && config.defaults) || {};
869
- const quality = qualityForAdapter(adapter, resolveQuality(defaults));
975
+ const quality = qualityForAdapter(adapter, resolveQuality(defaults), model);
870
976
  const fitted = fitSize(adapter, resolveSizeArg(defaults));
871
977
  if (fitted.rejected) throw new Error(fitted.reason);
872
978
  logHost('generate adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + (fitted.adjusted ? '(' + fitted.reason + ')' : ''));
873
979
  const signal = makeSignal(exec, 360000);
980
+ const extraParams = readParamsArg(args);
981
+ const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
874
982
  const result = await callImageApi('generate', adapter, provider, {
875
983
  model: model, prompt: prompt, negativePrompt: negativePrompt || undefined,
876
- fitted: fitted, quality: quality
984
+ fitted: fitted, quality: quality, params: extraParams
877
985
  }, signal);
878
986
  const final = finalizeImage(result);
879
987
  const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
880
- 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(';');
881
992
  return saved;
882
993
  }
883
994
  const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
@@ -1019,20 +1130,25 @@ async function edit(args, exec, store) {
1019
1130
  const provider = await resolveProviderCredential(store, picked.provider);
1020
1131
  const adapter = resolveAdapter(provider, model);
1021
1132
  const profile = resolvePromptProfile(model, adapter);
1022
- const quality = qualityForAdapter(adapter, resolveQuality(defaults));
1133
+ const quality = qualityForAdapter(adapter, resolveQuality(defaults), model);
1023
1134
  const fitted = fitSize(adapter, resolveSizeArg(defaults));
1024
1135
  if (fitted.rejected) throw new Error(fitted.reason);
1025
1136
  const signal = makeSignal(exec, 360000);
1026
1137
  const totalLimit = referenceLimitFor(adapter);
1027
1138
  const images = await readReferences(sources, signal, totalLimit);
1028
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) : [];
1029
1142
  const result = await callImageApi('edit', adapter, provider, {
1030
1143
  model: model, prompt: prompt, negativePrompt: negativePrompt || undefined,
1031
- fitted: fitted, quality: quality, images: images
1144
+ fitted: fitted, quality: quality, images: images, params: extraParams
1032
1145
  }, signal);
1033
1146
  const final = finalizeImage(result);
1034
1147
  const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
1035
- 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(';');
1036
1152
  return saved;
1037
1153
  }
1038
1154
 
@@ -1161,7 +1277,22 @@ async function modelsForRequest(store, body) {
1161
1277
  try { adapter = resolveAdapter(Object.assign({}, provider, { adapter: 'openai-images' }), ''); } catch (_error) { /* keep original */ }
1162
1278
  }
1163
1279
  if (!adapter || typeof adapter.listModels !== 'function') throw localizedError(new Error('该部署方式不支持获取模型列表'), 'models.unsupported');
1164
- 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
+ }
1165
1296
  const seen = new Set();
1166
1297
  const allModels = [];
1167
1298
  const names = {};
@@ -1291,6 +1422,33 @@ export function apply(ctx, options = {}) {
1291
1422
  } catch (error) { logHost('models route error: ' + String(error)); return () => {}; }
1292
1423
  }, 'mo-image: models route');
1293
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
+
1294
1452
  ctx.effect(() => {
1295
1453
  try {
1296
1454
  return ctx.webServer.register({
@@ -1408,32 +1566,107 @@ export function apply(ctx, options = {}) {
1408
1566
  },
1409
1567
  render: renderImage
1410
1568
  };
1569
+ // DSH 的工具契约要求每个工具声明 output { schema, render? };settings
1570
+ // 返回值就是给模型看的全部内容:一个最小 JSON(提供商/模型唯一 id + 优化开关 + 一句写法提示)。
1571
+ const modelsOutput = {
1572
+ schema: {
1573
+ type: 'object', additionalProperties: false,
1574
+ required: ['provider', 'model', 'promptOptimization', 'hint'],
1575
+ properties: {
1576
+ provider: { type: 'string' },
1577
+ model: { type: 'string' },
1578
+ promptOptimization: { type: 'boolean' },
1579
+ hint: { type: 'string' },
1580
+ models: { type: 'array', items: { type: 'string' } },
1581
+ params: { type: 'array', items: { type: 'object' } }
1582
+ }
1583
+ },
1584
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }]
1585
+ };
1411
1586
 
1587
+ // 生图前必须先读配置。只靠系统提示词时,多轮之后模型会按上一条提示词的习惯继续写,
1588
+ // 换了模型、关了提示词优化都不看;把当前配置放进工具结果,能让它每次写之前重读一遍。
1589
+ // 一次读取在当前回合内有效,配置一变(换模型、切优化开关)就作废。
1590
+ const marks = new WeakMap();
1591
+ const signatureOf = (state) => {
1592
+ if (!state) return '';
1593
+ const defaults = state.defaults || {};
1594
+ return [
1595
+ (state.provider && state.provider.id) || '', state.model,
1596
+ state.promptOptimization === false ? 'off' : 'on',
1597
+ defaults.quality || '', defaults.width || '', defaults.height || ''
1598
+ ].join('|');
1599
+ };
1600
+ const sessionOf = (exec) => (exec && exec.agent && exec.agent.session) || null;
1601
+ const currentTurn = (session) => {
1602
+ try {
1603
+ const projections = ctx.get && ctx.get('sessionProjections');
1604
+ if (!projections || typeof projections.stateOf !== 'function') return null;
1605
+ const boundary = projections.stateOf(session, 'turnBoundary');
1606
+ const seq = boundary && boundary.openTurnStartSeq;
1607
+ return typeof seq === 'number' ? seq : null;
1608
+ } catch (error) { logHost('turn lookup error: ' + String(error && error.message ? error.message : error)); return null; }
1609
+ };
1610
+ const rememberSettings = (exec) => {
1611
+ const session = sessionOf(exec);
1612
+ if (!session) return;
1613
+ marks.set(session, { signature: signatureOf(activeImageState(store)), turn: currentTurn(session) });
1614
+ };
1615
+ const requireSettings = (exec) => {
1616
+ const session = sessionOf(exec);
1617
+ if (!session) return; // 没有会话上下文(脚本调用)时无从比对,不拦。
1618
+ const mark = marks.get(session);
1619
+ const turn = currentTurn(session);
1620
+ const fresh = !!mark
1621
+ && mark.signature === signatureOf(activeImageState(store))
1622
+ && (turn === null || mark.turn === turn);
1623
+ if (!fresh) {
1624
+ throw new Error('生成前先读当前配置:调用 mo_image_settings,按它返回的模型写法和提示词优化状态写提示词,再调用本工具。');
1625
+ }
1626
+ };
1627
+ // 拿不到回合号时退回一次一读:生成成功后作废这次读取,失败不消耗。
1628
+ const consumeSettings = (exec) => {
1629
+ const session = sessionOf(exec);
1630
+ if (session && currentTurn(session) === null) marks.delete(session);
1631
+ };
1632
+
1633
+ // 每个工具单独兜底:一个工具的契约不满足时,不会连带其它工具一起注册失败。
1412
1634
  try {
1413
1635
  ctx.tools.register({
1414
- name: 'mo_image_list_models',
1415
- description: 'List the image models configured in this plugin: every provider, its models with display names, the model the user currently picked, and whether Auto mode is on. Call this first whenever you need to know which image models exist, for example to choose the model argument or to answer which models are available. Reading the plugin config file also works, but this returns the same picture without parsing it.',
1636
+ name: 'mo_image_settings',
1637
+ description: 'Read the current image settings before every generation or edit: the picked provider and model, whether prompt optimization is on, and a one-line hint for how to write the prompt for that model. Calling mo_image_generate or mo_image_edit without reading this first in the current turn is rejected, so read it again after the user switches models or toggles a setting.',
1416
1638
  parameters: { type: 'object', additionalProperties: false, properties: {} },
1639
+ output: modelsOutput,
1417
1640
  timeoutMs: 15000,
1418
- async execute() {
1419
- return modelListSnapshot(await readConfig(store));
1641
+ async execute(_args, exec) {
1642
+ rememberSettings(exec);
1643
+ return settingsPayload(activeImageState(store));
1420
1644
  }
1421
1645
  });
1646
+ } catch (error) { logHost('settings tool register error: ' + String(error)); }
1647
+
1648
+ try {
1422
1649
  ctx.tools.register({
1423
1650
  name: 'mo_image_generate',
1424
- description: 'Generate a new image with the active image model. Follow the active mo-image prompt section: when prompt optimization is On, write the final prompt in the active model\'s dialect; when Off, pass the user\'s original wording unchanged. Model, size, and quality come from the picker, not this tool; the only exception is Auto mode, where the model argument selects one entry from the active provider list. Load the mo-image-generation skill whenever you generate or redo an image; when optimization is Off, use only its invocation and output guidance, not its prompt formulas. The tool returns a Markdown image line and a file card; reply with that Markdown line and nothing else. Output is final: never judge or describe the image, never switch provider, model or tool (local image models, Blender, scripting) on your own, and do not open or read the image unless the user explicitly asks to look at it. On failure report the error verbatim and at most ask the user whether to switch.',
1651
+ description: 'Generate a new image with the active image model. Call mo_image_settings first in this turn: it returns the current model, the prompt-optimization state and the writing rules for that model, and this tool rejects a call that did not read it. Then follow what it returned: when optimization is On, write the final prompt in the active model\'s dialect; when Off, pass the user\'s original wording unchanged. Model, size, and quality come from the picker, so leave the model argument out; only in Auto mode must you pass one id from the active provider list. Load the mo-image-generation skill only when you have not already read this model\'s writing rules in this conversation; when optimization is Off, use only its invocation and output guidance, not its prompt formulas. The tool returns a Markdown image line and a file card; reply with that Markdown line and nothing else. Output is final: never judge or describe the image, never switch provider, model or tool (local image models, Blender, scripting) on your own, and do not open or read the image unless the user explicitly asks to look at it. On failure report the error verbatim and at most ask the user whether to switch.',
1425
1652
  parameters: {
1426
- type: 'object', additionalProperties: false, required: ['prompt', 'model'],
1653
+ type: 'object', additionalProperties: false, required: ['prompt'],
1427
1654
  properties: {
1428
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.' },
1429
1656
  negative_prompt: { type: 'string', description: 'Optional prompt content. Only for models that support negative prompts; list artifacts and undesired elements. Omit otherwise.' },
1430
- model: { type: 'string', description: 'Always required. Outside Auto mode pass the model the user selected in the picker (the prompt section names it); in Auto mode pick one id from the active provider list.' },
1431
- provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' }
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.' },
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
+ }
1432
1663
  }
1433
1664
  },
1434
1665
  output, timeoutMs: 360000,
1435
1666
  async execute(args, exec) {
1667
+ requireSettings(exec);
1436
1668
  const result = await generate(args, exec, store);
1669
+ consumeSettings(exec);
1437
1670
  presentImage(exec, result);
1438
1671
  return result.note ? { path: result.file, note: result.note } : { path: result.file };
1439
1672
  }
@@ -1443,20 +1676,26 @@ export function apply(ctx, options = {}) {
1443
1676
  try {
1444
1677
  ctx.tools.register({
1445
1678
  name: 'mo_image_edit',
1446
- description: 'Edit or refine an existing image with one or more reference images. Follow the active mo-image prompt section: when prompt optimization is Off, use the user\'s original edit wording and do not expand it. Model, size, and quality come from the picker, not this tool; the only exception is Auto mode, where the model argument selects one entry from the active provider list. Name each reference as 图1/图2 in the prompt. For a full redo that must not copy the current image, use mo_image_generate instead. Load the mo-image-editing skill whenever you edit an image; when optimization is Off, use only its invocation and output guidance, not its edit formula. Output is final: never judge or describe the image, never switch provider, model or tool (local image models, Blender, scripting) on your own, and do not open or read the image unless the user explicitly asks to look at it. On failure report the error verbatim and at most ask the user whether to switch.',
1679
+ description: 'Edit or refine an existing image with one or more reference images. Call mo_image_settings first in this turn: it returns the current model, the prompt-optimization state and the writing rules for that model, and this tool rejects a call that did not read it. Follow what it returned: when optimization is Off, use the user\'s original edit wording and do not expand it. Model, size, and quality come from the picker, so leave the model argument out; only in Auto mode must you pass one id from the active provider list. Name each reference as 图1/图2 in the prompt. For a full redo that must not copy the current image, use mo_image_generate instead. Load the mo-image-editing skill only when you have not already read this model\'s editing rules in this conversation; when optimization is Off, use only its invocation and output guidance, not its edit formula. Output is final: never judge or describe the image, never switch provider, model or tool (local image models, Blender, scripting) on your own, and do not open or read the image unless the user explicitly asks to look at it. On failure report the error verbatim and at most ask the user whether to switch.',
1447
1680
  parameters: {
1448
- type: 'object', additionalProperties: false, required: ['prompt', 'images', 'model'],
1681
+ type: 'object', additionalProperties: false, required: ['prompt', 'images'],
1449
1682
  properties: {
1450
1683
  prompt: { type: 'string', description: 'Final edit prompt. Name each reference image (图1/图2), state exactly what to change, and state that everything else must stay unchanged.' },
1451
1684
  images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute local paths or http(s) URLs; order matters and corresponds to 图1/图2.' },
1452
1685
  negative_prompt: { type: 'string', description: 'Optional prompt content. Only for models that support negative prompts; list artifacts and undesired elements. Omit otherwise.' },
1453
- model: { type: 'string', description: 'Always required. Outside Auto mode pass the model the user selected in the picker (the prompt section names it); in Auto mode pick one id from the active provider list.' },
1454
- provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' }
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.' },
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
+ }
1455
1692
  }
1456
1693
  },
1457
1694
  output, timeoutMs: 360000,
1458
1695
  async execute(args, exec) {
1696
+ requireSettings(exec);
1459
1697
  const result = await edit(args, exec, store);
1698
+ consumeSettings(exec);
1460
1699
  presentImage(exec, result);
1461
1700
  return result.note ? { path: result.file, note: result.note } : { path: result.file };
1462
1701
  }