dsh-mo-image 1.0.2 → 1.0.4

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
@@ -47,8 +47,8 @@ export {
47
47
  capabilityManifest, normalizeConfig, normalizeDefaults, normalizeModelOptions,
48
48
  paramNoticeOf, resolveSizeRequest, workflowParamsOf
49
49
  } from './config-store.js';
50
- import { MAPPING_KEYS } from './comfy-workflow.js';
51
- import { STATUS_CONTRACT, editCapableModels, pickAutoEditModel } from './status.js';
50
+ import { MAPPING_KEYS, assertComfyReferenceCount } from './comfy-workflow.js';
51
+ import { STATUS_CONTRACT, comfyReferencePlan, editCapableModels, pickAutoEditModel } from './status.js';
52
52
  import { detectQualityRule, detectFieldRule } from './model-rules.js';
53
53
 
54
54
  const PLUGIN = 'dsh-mo-image';
@@ -175,6 +175,40 @@ function sendJson(res, status, value) {
175
175
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
176
176
  res.end(JSON.stringify(value));
177
177
  }
178
+
179
+ function routeAccessRejection(ctx, req, peer) {
180
+ // New hosts admit requests before dispatch and pass the authenticated Peer.
181
+ if (peer !== undefined) {
182
+ if (peer?.signal?.aborted) return 401;
183
+ return peer?.principal?.kind === 'owner' ? undefined : 403;
184
+ }
185
+ // On older hosts the handler itself must apply Connection's access check.
186
+ try {
187
+ const connection = ctx.get?.('connection');
188
+ if (typeof connection?.requestRejection === 'function') {
189
+ const rejection = connection.requestRejection(req);
190
+ if (rejection === undefined || rejection === 401 || rejection === 403) return rejection;
191
+ }
192
+ } catch (_error) {
193
+ // A missing or unavailable authentication service cannot grant access.
194
+ }
195
+ return 503;
196
+ }
197
+
198
+ function registerPrivateRoute(ctx, route) {
199
+ return ctx.webServer.register({
200
+ ...route,
201
+ auth: 'required',
202
+ async handler(req, res, peer) {
203
+ const rejection = routeAccessRejection(ctx, req, peer);
204
+ if (rejection === undefined) return route.handler(req, res);
205
+ const error = rejection === 401 ? 'unauthorized'
206
+ : rejection === 403 ? 'forbidden' : 'DSH authentication unavailable';
207
+ return sendJson(res, rejection, { ok: false, error });
208
+ }
209
+ });
210
+ }
211
+
178
212
  async function readBody(req) {
179
213
  const chunks = [];
180
214
  let total = 0;
@@ -647,6 +681,9 @@ async function edit(args, exec, store, snapshot, queue, journal, cwd) {
647
681
  const provider = await resolveProviderCredential(store, picked.provider);
648
682
  const adapter = resolveAdapter(provider, model);
649
683
  assertReferenceCount(adapter.operations?.edit, sources.length);
684
+ if (adapter.id === 'comfyui') {
685
+ assertComfyReferenceCount(sources.length, comfyReferencePlan(provider.modelOptions?.[model])?.count || 1);
686
+ }
650
687
  const profile = resolvePromptProfile(model, adapter);
651
688
  const quality = resolveToolQuality(provider, model, defaults, args, adapter);
652
689
  const { requested, fitted } = imageSizePlan(provider, model, defaults, args, adapter);
@@ -714,6 +751,9 @@ function settingsView(state) {
714
751
  const cached = settingsViews.get(state);
715
752
  if (cached) return cached;
716
753
  const payload = settingsPayload(state);
754
+ if (state.referenceWorkflows?.length) {
755
+ payload.referenceRevision = createHash('sha256').update(stableStringify(state.referenceWorkflows)).digest('hex').slice(0, 16);
756
+ }
717
757
  const { provider, defaults } = state;
718
758
  // Details are served on demand. Changes to those settings must still invalidate past reads.
719
759
  const models = state.model === 'auto' ? state.models : [state.model];
@@ -1124,7 +1164,6 @@ export function apply(ctx, options = {}) {
1124
1164
  log: logHost,
1125
1165
  installDelayMs: Number.isFinite(updateOptions.installDelayMs) ? updateOptions.installDelayMs : 800,
1126
1166
  registryBase: updateOptions.registryBase,
1127
- mirrorBase: updateOptions.mirrorBase,
1128
1167
  cdnSources: updateOptions.cdnSources
1129
1168
  });
1130
1169
  // 上次更新成没成,先看标记文件——这一步不能等网络,否则重启后的
@@ -1159,7 +1198,7 @@ export function apply(ctx, options = {}) {
1159
1198
 
1160
1199
  ctx.effect(() => {
1161
1200
  try {
1162
- return ctx.webServer.register({
1201
+ return registerPrivateRoute(ctx, {
1163
1202
  kind: 'exact', path: '/api/mo-image/config',
1164
1203
  handler: async (req, res) => {
1165
1204
  try {
@@ -1184,7 +1223,7 @@ export function apply(ctx, options = {}) {
1184
1223
 
1185
1224
  ctx.effect(() => {
1186
1225
  try {
1187
- return ctx.webServer.register({
1226
+ return registerPrivateRoute(ctx, {
1188
1227
  kind: 'exact', path: '/api/mo-image/models',
1189
1228
  handler: async (req, res) => {
1190
1229
  try {
@@ -1211,7 +1250,7 @@ export function apply(ctx, options = {}) {
1211
1250
 
1212
1251
  ctx.effect(() => {
1213
1252
  try {
1214
- return ctx.webServer.register({
1253
+ return registerPrivateRoute(ctx, {
1215
1254
  kind: 'exact', path: '/api/mo-image/detect-protocol',
1216
1255
  handler: async (req, res) => {
1217
1256
  try {
@@ -1271,7 +1310,7 @@ export function apply(ctx, options = {}) {
1271
1310
 
1272
1311
  ctx.effect(() => {
1273
1312
  try {
1274
- return ctx.webServer.register({
1313
+ return registerPrivateRoute(ctx, {
1275
1314
  kind: 'exact', path: '/api/mo-image/detect-model-rule',
1276
1315
  handler: async (req, res) => {
1277
1316
  try {
@@ -1328,7 +1367,7 @@ export function apply(ctx, options = {}) {
1328
1367
 
1329
1368
  ctx.effect(() => {
1330
1369
  try {
1331
- return ctx.webServer.register({
1370
+ return registerPrivateRoute(ctx, {
1332
1371
  kind: 'exact', path: '/api/mo-image/comfy/analyze',
1333
1372
  handler: async (req, res) => {
1334
1373
  try {
@@ -1356,7 +1395,7 @@ export function apply(ctx, options = {}) {
1356
1395
  */
1357
1396
  ctx.effect(() => {
1358
1397
  try {
1359
- return ctx.webServer.register({
1398
+ return registerPrivateRoute(ctx, {
1360
1399
  kind: 'exact', path: '/api/mo-image/comfy/params',
1361
1400
  handler: async (req, res) => {
1362
1401
  try {
@@ -1381,7 +1420,7 @@ export function apply(ctx, options = {}) {
1381
1420
 
1382
1421
  ctx.effect(() => {
1383
1422
  try {
1384
- return ctx.webServer.register({
1423
+ return registerPrivateRoute(ctx, {
1385
1424
  kind: 'prefix', path: '/api/mo-image/preview',
1386
1425
  handler: async (req, res) => {
1387
1426
  let handle;
@@ -1426,7 +1465,7 @@ export function apply(ctx, options = {}) {
1426
1465
 
1427
1466
  ctx.effect(() => {
1428
1467
  try {
1429
- return ctx.webServer.register({
1468
+ return registerPrivateRoute(ctx, {
1430
1469
  kind: 'exact', path: '/api/mo-image/update',
1431
1470
  handler: async (req, res) => {
1432
1471
  try {
@@ -1558,6 +1597,11 @@ export function apply(ctx, options = {}) {
1558
1597
  unchanged: { type: 'boolean' },
1559
1598
  models: { type: 'array', items: { type: 'string' } },
1560
1599
  editModels: { type: 'array', items: { type: 'string' } },
1600
+ referenceModelIndexes: { type: 'array', items: { type: 'integer' } },
1601
+ referenceRevision: { type: 'string' },
1602
+ referenceImages: {
1603
+ type: 'array', items: { type: 'object', properties: { index: { type: 'integer' }, purpose: { type: 'string' } } }
1604
+ },
1561
1605
  params: { type: 'array', items: { type: 'object' } }
1562
1606
  }
1563
1607
  },
@@ -1771,7 +1815,7 @@ export function apply(ctx, options = {}) {
1771
1815
  type: 'object', additionalProperties: false,
1772
1816
  properties: {
1773
1817
  prompt: { type: 'string', description: 'Final edit prompt: name each reference (图1/图2); state exactly what changes and that everything else stays.' },
1774
- images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute local paths or http(s) URLs, in 图1/图2 order.' },
1818
+ images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute paths or http(s) URLs. Match the order, purposes and count in referenceImages when present. For candidates in referenceModelIndexes, query mo_image_settings with the model if details are missing or referenceRevision changed. Ask if an image’s role is unclear.' },
1775
1819
  negative_prompt: { type: 'string', description: 'Optional; only for models that support it. Artifacts/elements to avoid.' },
1776
1820
  size: { type: 'string', description: 'Optional shape like "1024x1536" or an accepted aspect or tier; only honored if sizeMode is "auto".' },
1777
1821
  quality: { type: 'string', description: 'Optional level from qualityOptions. Only honored if qualityMode is "auto".' },
@@ -277,6 +277,9 @@ export function settingsPayload(state, { includeParamDetails = false } = {}) {
277
277
  payload.models = (Array.isArray(state && state.models) ? state.models : []).filter(Boolean).map(String);
278
278
  // 改图只在能图生图的模型里选;没传 model 时插件会自动取第一个。
279
279
  payload.editModels = (Array.isArray(state && state.editModels) ? state.editModels : []).filter(Boolean).map(String);
280
+ if (state?.referenceWorkflows?.length) {
281
+ payload.referenceModelIndexes = state.referenceWorkflows.map((item) => item.index);
282
+ }
280
283
  return payload;
281
284
  }
282
285
  const profile = resolvePromptProfile(model, (state && state.adapter) || null);
@@ -298,6 +301,11 @@ export function settingsPayload(state, { includeParamDetails = false } = {}) {
298
301
  if (payload.strict) {
299
302
  payload.hint += ';严格模式尝试将成品缩放到明确的像素宽高;比例或档位没有精确像素目标';
300
303
  }
304
+ if (state?.referenceImages?.length) {
305
+ payload.referenceImages = state.referenceImages.map(({ index, purpose }) => ({
306
+ index, ...(purpose ? { purpose } : {})
307
+ }));
308
+ }
301
309
  const workflowParams = Array.isArray(state && state.workflowParams)
302
310
  ? state.workflowParams.filter((param) => param && param.expose !== false)
303
311
  : [];
package/lib/status.js CHANGED
@@ -8,29 +8,52 @@
8
8
  * 纯函数,不发请求、不写配置;凭据由调用方(index.js)解析后以 key 传入。
9
9
  */
10
10
  import { adapterSupportsKind, resolveAdapter, sizeSpecFor } from './adapters.js';
11
+ import { parseWorkflow, workflowImageSlots, workflowReferenceTarget, WORKFLOW_REFERENCE_LIMIT } from './comfy-workflow.js';
11
12
 
12
13
  export const STATUS_CONTRACT = 1;
13
14
  /** mo-image 工具一次最多接受的参考图数量(与 lib/index.js 的 MAX_REF_COUNT 对齐)。 */
14
- export const MAX_REFS = 16;
15
+ export const MAX_REFS = WORKFLOW_REFERENCE_LIMIT;
15
16
 
16
17
  function adapterFor(provider, model) {
17
18
  try { return resolveAdapter(provider, model); } catch (_error) { return null; }
18
19
  }
19
20
 
21
+ const workflowEditCache = new WeakMap();
22
+ const SINGLE_REFERENCE = { count: 1, slots: [] };
23
+
24
+ export function comfyReferencePlan(entry) {
25
+ const workflow = String(entry?.workflow || '');
26
+ if (!workflow) return SINGLE_REFERENCE;
27
+ const image = entry.mapping?.image;
28
+ const cached = workflowEditCache.get(entry);
29
+ if (cached?.workflow === workflow && cached.image === image) return cached.plan;
30
+ let plan = null;
31
+ try {
32
+ const parsed = parseWorkflow(workflow);
33
+ const graph = parsed.graph || Object.fromEntries(parsed.ui.nodes.filter(Boolean).map((node) => [
34
+ String(node.id), { class_type: node.type, _meta: { title: node.title }, inputs: { widgets: node.widgets_values } }
35
+ ]));
36
+ const slots = workflow.includes('{{') ? workflowImageSlots(graph) : [];
37
+ const mapped = () => parsed.format === 'api' ? workflowReferenceTarget(graph, image)
38
+ : image && Object.hasOwn(graph, image.node);
39
+ if (slots.length) plan = { count: slots.length, slots };
40
+ else if (mapped()) plan = SINGLE_REFERENCE;
41
+ } catch (_error) {
42
+ // 无效工作流不会被列为可编辑模型。
43
+ }
44
+ workflowEditCache.set(entry, { workflow, image, plan });
45
+ return plan;
46
+ }
47
+
20
48
  /**
21
49
  * 当前模型能不能图生图。
22
- * - ComfyUI 由工作流决定:自定义工作流必须带 {{image}} 或 image 映射;内置工作流可以。
50
+ * - ComfyUI 由工作流决定:检查占位符、已保存绑定和 API 工作流的图像输入。
23
51
  * - 异步入队型看 async.edit;普通适配器看 endpoints.edit。
24
52
  */
25
53
  export function canEditModel(provider, model, adapter) {
26
54
  if (!adapter) return false;
27
55
  if (adapter.id === 'comfyui') {
28
- const entry = provider && provider.modelOptions ? provider.modelOptions[model] : null;
29
- const workflow = String(entry?.workflow || '');
30
- if (!workflow) return true;
31
- const hasSlot = /\{\{\s*image\s*\}\}/.test(workflow);
32
- const mapped = Boolean(entry.mapping && entry.mapping.image);
33
- return hasSlot || mapped;
56
+ return Boolean(comfyReferencePlan(provider?.modelOptions?.[model]));
34
57
  }
35
58
  const edit = adapter.operations?.edit;
36
59
  if (edit?.fields?.image === null || edit?.fields?.image === false
@@ -2,8 +2,7 @@
2
2
  * 更新状态服务:把「检查 npm → 有没有新版 → 装哪个版本 → 装完没有」
3
3
  * 收成一个有状态对象,路由和启动预热都只跟它打交道。
4
4
  *
5
- * 检测和安装都走 npm:检测读 registry 的版本号,安装用 npm 版本规格,
6
- * 不碰 git,免得用户还要为 GitHub 单独准备网络和凭据。
5
+ * 从镜像检测新版,安装仍使用 npm 版本规格,并指定同一个镜像。
7
6
  *
8
7
  * 自我更新有个绕不开的坑:装新版本时插件自己会被卸载,这次调用等不到结果。
9
8
  * 所以状态靠标记文件 + 当前版本号事后判定,见 hydrate()。
@@ -11,7 +10,7 @@
11
10
  import { randomUUID } from 'node:crypto';
12
11
  import {
13
12
  classifySource, clearMarker, compareVersions, fetchChangelogNotes, fetchLatestVersion,
14
- judgeMarker, readMarker, writeMarker
13
+ judgeMarker, readMarker, UPDATE_REGISTRY, writeMarker
15
14
  } from './update.js';
16
15
 
17
16
  // 宿主进程启动时刻:process.uptime 是进程年龄,模块重新 import 不会把它重置。
@@ -30,13 +29,13 @@ export const UPDATE_SPEC = (version) => `dsh-mo-image@${version}`;
30
29
  * @param {() => number} [options.now]
31
30
  * @param {(ms: number) => Promise<void>} [options.sleep]
32
31
  * @param {number} [options.installDelayMs] 先让"正在更新"气泡露个脸
33
- * @param {string} [options.apiBase]
34
- * @param {string} [options.releasesBase]
32
+ * @param {string} [options.registryBase] 检查与安装使用的 registry
35
33
  */
36
34
  export function createUpdateService(options = {}) {
37
35
  const currentVersion = String(options.currentVersion || '0.0.0');
38
36
  const markerFile = typeof options.markerFile === 'string' ? options.markerFile : '';
39
37
  const request = options.request;
38
+ const registry = options.registryBase || UPDATE_REGISTRY;
40
39
  const pluginManager = options.pluginManager;
41
40
  const log = typeof options.log === 'function' ? options.log : () => {};
42
41
  const now = typeof options.now === 'function' ? options.now : Date.now;
@@ -74,7 +73,7 @@ export function createUpdateService(options = {}) {
74
73
  return {
75
74
  source: hit && typeof hit.source === 'string' ? hit.source : '',
76
75
  // 只有以 npm 版本安装的包才能走 updateBundle(卸旧装新、失败自动装回)。
77
- updatable: !!(hit && hit.updatable)
76
+ updatable: hit?.update === 'registry' || hit?.updatable === true
78
77
  };
79
78
  } catch (_error) {
80
79
  return { source: '', updatable: false };
@@ -113,8 +112,7 @@ export function createUpdateService(options = {}) {
113
112
  updatable = bundle.updatable;
114
113
  const release = await fetchLatestVersion({
115
114
  request,
116
- registryBase: options.registryBase,
117
- mirrorBase: options.mirrorBase,
115
+ registryBase: registry,
118
116
  onError: (reason) => safeLog('update check failed: ' + String(reason || 'unknown'))
119
117
  });
120
118
  if (disposed) return;
@@ -198,8 +196,8 @@ export function createUpdateService(options = {}) {
198
196
  const rollback = async (activeManager) => {
199
197
  if (!previousSpec) return false;
200
198
  try {
201
- const restored = await activeManager.installBundle(previousSpec, { enabled: true });
202
- const application = restored && restored.result && restored.result.application;
199
+ const restored = await activeManager.installBundle(previousSpec, { enabled: true, registry });
200
+ const application = (restored?.result ?? restored)?.application;
203
201
  return application !== 'failed' && application !== 'cancelled';
204
202
  } catch (_error) {
205
203
  return false;
@@ -225,10 +223,10 @@ export function createUpdateService(options = {}) {
225
223
  let result;
226
224
  if (updatable && typeof active.updateBundle === 'function') {
227
225
  // npm 安装:走原生更新,它会在装失败时把旧版本装回来。
228
- result = await active.updateBundle('dsh-mo-image', to, { requestId });
226
+ result = await active.updateBundle('dsh-mo-image', to, { requestId, registry });
229
227
  } else {
230
228
  const spec = UPDATE_SPEC(to);
231
- const installOptions = { requestId, enabled: true };
229
+ const installOptions = { requestId, enabled: true, registry };
232
230
  try {
233
231
  result = await active.installBundle(spec, installOptions);
234
232
  } catch (caught) {
@@ -238,7 +236,7 @@ export function createUpdateService(options = {}) {
238
236
  result = await active.installBundle(spec, installOptions);
239
237
  }
240
238
  }
241
- const application = result && result.result && result.result.application;
239
+ const application = (result?.result ?? result)?.application;
242
240
  if (application === 'failed' || application === 'cancelled') {
243
241
  await fail(application);
244
242
  return;
package/lib/update.js CHANGED
@@ -7,6 +7,7 @@ import path from 'node:path';
7
7
 
8
8
  export const REPO = 'CM-Silence/dsh-mo-image';
9
9
  export const NPM_NAME = 'dsh-mo-image';
10
+ export const UPDATE_REGISTRY = 'https://registry.npmmirror.com';
10
11
 
11
12
  const SEMVER = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
12
13
 
@@ -139,9 +140,6 @@ export function isHiddenPrerelease(version) {
139
140
  return /-(?:a|b)\d+$/i.test(String(version || '').trim());
140
141
  }
141
142
 
142
- /** 读版本号时依次尝试的 registry:官方源,再退国内镜像。 */
143
- const REGISTRIES = ['https://registry.npmjs.org', 'https://registry.npmmirror.com'];
144
-
145
143
  /** 读 CHANGELOG 时依次尝试的 CDN(都按版本取包内文件)。 */
146
144
  export const DEFAULT_CDN_SOURCES = [
147
145
  (version) => `https://cdn.jsdelivr.net/npm/${NPM_NAME}@${version}/CHANGELOG.md`,
@@ -185,43 +183,28 @@ export function parseChangelogFor(markdown, version) {
185
183
  }
186
184
 
187
185
  /**
188
- * 读 npm 上的最新版本。`/latest` 只指向 latest dist-tag,所以 rc 发到 next
189
- * 时天然不会被这里看到。
190
- * @param {{registryBase?: string, mirrorBase?: string, request?: Function, timeoutMs?: number, onError?: Function}} options
186
+ * 读更新镜像上的 latest 标签,只提示已经同步到下载源的版本。
187
+ * @param {{registryBase?: string, request?: Function, timeoutMs?: number, onError?: Function}} options
191
188
  * @returns {Promise<{version: string, url: string}|null>}
192
189
  */
193
190
  export async function fetchLatestVersion(options = {}) {
194
191
  const request = typeof options.request === 'function' ? options.request : fetch;
195
192
  const timeoutMs = Number(options.timeoutMs) || 8000;
196
- const registries = [
197
- String(options.registryBase || REGISTRIES[0]).replace(/\/+$/, ''),
198
- String(options.mirrorBase || REGISTRIES[1]).replace(/\/+$/, '')
199
- ];
200
- const reasons = [];
201
- for (const base of registries) {
202
- try {
203
- const response = await request(`${base}/${NPM_NAME}/latest`, {
204
- headers: { accept: 'application/json' },
205
- signal: AbortSignal.timeout(timeoutMs)
206
- });
207
- if (response && response.ok) {
208
- const data = await response.json();
209
- const version = tagToVersion(data && data.version);
210
- if (version && !isHiddenPrerelease(version)) {
211
- return { version, url: `https://www.npmjs.com/package/${NPM_NAME}/v/${version}` };
212
- }
213
- reasons.push(`${base}: no usable version`);
214
- } else {
215
- reasons.push(`${base}: HTTP ${response ? response.status : 'nothing'}`);
216
- }
217
- } catch (error) {
218
- reasons.push(`${base}: ${String(error && error.message ? error.message : error)}`);
219
- }
220
- }
221
- if (typeof options.onError === 'function') {
222
- try { options.onError(reasons.join('; ')); } catch (_error) { /* 日志回调不该影响结果 */ }
193
+ const base = String(options.registryBase || UPDATE_REGISTRY).replace(/\/+$/, '');
194
+ try {
195
+ const response = await request(`${base}/${NPM_NAME}/latest`, {
196
+ headers: { accept: 'application/json' },
197
+ redirect: 'error',
198
+ signal: AbortSignal.timeout(timeoutMs)
199
+ });
200
+ if (!response?.ok) throw new Error(`HTTP ${response?.status ?? 'no response'}`);
201
+ const version = tagToVersion((await response.json())?.version);
202
+ if (!version || isHiddenPrerelease(version)) throw new Error('no usable version');
203
+ return { version, url: `https://www.npmjs.com/package/${NPM_NAME}/v/${version}` };
204
+ } catch (error) {
205
+ try { options.onError?.(`${base}: ${error?.message || error}`); } catch (_error) { /* 日志回调不该影响结果 */ }
206
+ return null;
223
207
  }
224
- return null;
225
208
  }
226
209
 
227
210
  /**
@@ -219,22 +219,17 @@ quality.turbo,"极速","Turbo","ターボ","Turbo","Turbo","Turbo","Турбо",
219
219
  "update.failedBroken","更新安装失败,原版本也没能装回,请在插件管理里重新安装","The update failed and the previous version was not restored — reinstall it from plugin management","更新のインストールに失敗し、元のバージョンにも戻せませんでした。プラグイン管理から再インストールしてください","La actualización falló y no se restauró la versión anterior; reinstálala desde la gestión de complementos","La mise à jour a échoué et la version précédente n'a pas été restaurée ; réinstallez le greffon depuis la gestion des plugins","Das Update ist fehlgeschlagen und die vorherige Version wurde nicht wiederhergestellt – installieren Sie das Plugin über die Plugin-Verwaltung neu","Обновление не удалось, и прежняя версия не восстановлена — переустановите плагин в управлении плагинами","A atualização falhou e a versão anterior não foi restaurada — reinstale pelo gerenciamento de plugins"
220
220
  "update.unsupported","当前环境不支持自助更新,请运行 {command}","This environment cannot self-update; run {command}","この環境では自動更新できません。{command} を実行してください","Este entorno no admite la actualización automática; ejecuta {command}","Cet environnement ne permet pas la mise à jour automatique ; exécutez {command}","Diese Umgebung kann sich nicht selbst aktualisieren; führen Sie {command} aus","Эта среда не поддерживает самообновление — выполните {command}","Este ambiente não permite atualização automática; execute {command}"
221
221
  "update.localDev","本地开发安装,请自行 git pull","Local development install — run git pull yourself","ローカル開発用のインストールです。git pull を実行してください","Instalación de desarrollo local: ejecuta git pull","Installation de développement local — lancez git pull","Lokale Entwicklungsinstallation – bitte selbst git pull ausführen","Локальная установка для разработки — выполните git pull","Instalação de desenvolvimento local — execute git pull"
222
- "update.command","dsh plugin add dsh-mo-image@{tag}","dsh plugin add dsh-mo-image@{tag}","dsh plugin add dsh-mo-image@{tag}","dsh plugin add dsh-mo-image@{tag}","dsh plugin add dsh-mo-image@{tag}","dsh plugin add dsh-mo-image@{tag}","dsh plugin add dsh-mo-image@{tag}","dsh plugin add dsh-mo-image@{tag}"
222
+ "update.command","dsh plugin --profile web add dsh-mo-image@{tag} --registry=https://registry.npmmirror.com","dsh plugin --profile web add dsh-mo-image@{tag} --registry=https://registry.npmmirror.com","dsh plugin --profile web add dsh-mo-image@{tag} --registry=https://registry.npmmirror.com","dsh plugin --profile web add dsh-mo-image@{tag} --registry=https://registry.npmmirror.com","dsh plugin --profile web add dsh-mo-image@{tag} --registry=https://registry.npmmirror.com","dsh plugin --profile web add dsh-mo-image@{tag} --registry=https://registry.npmmirror.com","dsh plugin --profile web add dsh-mo-image@{tag} --registry=https://registry.npmmirror.com","dsh plugin --profile web add dsh-mo-image@{tag} --registry=https://registry.npmmirror.com"
223
223
  "update.viewRelease","在 npm 查看","View on npm","npm で見る","Ver en npm","Voir sur npm","Auf npm ansehen","Открыть на npm","Ver no npm"
224
224
  "update.noNotes","暂无更新说明","This release has no notes.","このリリースには説明がありません。","Esta versión no tiene notas.","Cette version n'a pas de notes.","Diese Version hat keine Hinweise.","В этом выпуске нет примечаний.","Esta versão não tem notas."
225
225
  "form.modelMappingParse","解析工作流","Parse workflow","ワークフローを解析","Analizar flujo de trabajo","Analyser le workflow","Workflow analysieren","Разобрать workflow","Analisar fluxo"
226
226
  "form.modelMappingParsing","解析中…","Parsing…","解析中…","Analizando…","Analyse…","Analysiere…","Разбор…","Analisando…"
227
227
  "form.modelMappingFailed","解析失败","Parsing failed","解析に失敗しました","No se pudo analizar","Analyse impossible","Analyse fehlgeschlagen","Не удалось разобрать","Falha ao analisar"
228
- "form.modelMappingSkip","不注入","Do not inject","注入しない","No inyectar","Ne pas injecter","Nicht einsetzen","Не внедрять","Não injetar"
229
228
  "form.modelMappingFormatApi","API 格式","API format","API 形式","Formato API","Format API","API-Format","Формат API","Formato API"
230
229
  "form.modelMappingFormatUi","UI 格式","UI format","UI 形式","Formato UI","Format UI","UI-Format","Формат UI","Formato UI"
231
230
  "form.modelMappingSampler","采样器","Sampler","サンプラー","Muestreador","Sampler","Sampler","Сэмплер","Amostrador"
232
- "form.modelMappingWidth","宽度","Width","幅","Ancho","Largeur","Breite","Ширина","Largura"
233
- "form.modelMappingHeight","高度","Height","高さ","Alto","Hauteur","Höhe","Высота","Altura"
234
- "form.modelMappingImage","参考图","Reference image","参照画像","Imagen de referencia","Image de référence","Referenzbild","Референс","Imagem de referência"
235
- "form.modelMappingColName","参数名","Parameter","パラメータ","Parámetro","Paramètre","Parameter","Параметр","Parâmetro"
236
- "form.modelMappingColTarget","参数映射","Mapping","マッピング","Mapeo","Correspondance","Zuordnung","Привязка","Mapeamento"
237
- "form.modelAutoInjectHint","提示词与负面词由工具参数直接写入,不需要在这里配置。","The prompt and negative prompt come straight from the tool call, so there is nothing to configure here.","プロンプトとネガティブプロンプトはツール引数から直接書き込まれるため、ここでの設定は不要です。","El prompt y el prompt negativo llegan de la llamada de la herramienta, así que aquí no hay nada que configurar.","Les prompts positif et négatif viennent de l'appel d'outil : rien à configurer ici.","Prompt und Negativ-Prompt kommen direkt aus dem Werkzeugaufruf, hier ist nichts einzustellen.","Промпт и негативный промпт подставляются из вызова инструмента, здесь настраивать нечего.","O prompt e o prompt negativo vêm da chamada da ferramenta; não há nada para configurar aqui."
231
+ "form.modelMappingAmbiguousImage","检测到多个图像输入。用 {{image}} 标记一张参考图,或用 {{image_1}}、{{image_2}} 连续编号。","Multiple image inputs found. Use {{image}} for one reference or number them with {{image_1}}, {{image_2}}, and so on.","画像入力が複数見つかりました。参照画像が1枚なら {{image}}、複数なら {{image_1}}、{{image_2}} のように指定してください。","Hay varias entradas de imagen. Usa {{image}} para una referencia o numéralas con {{image_1}}, {{image_2}}, etc.","Plusieurs entrées d’image détectées. Utilisez {{image}} pour une référence ou numérotez-les avec {{image_1}}, {{image_2}}, etc.","Mehrere Bildeingänge gefunden. Verwende {{image}} für eine Referenz oder nummeriere sie mit {{image_1}}, {{image_2}} usw.","Найдено несколько входов для изображений. Используйте {{image}} для одного референса или нумеруйте их как {{image_1}}, {{image_2}} и т. д.","Há várias entradas de imagem. Use {{image}} para uma referência ou numere-as com {{image_1}}, {{image_2}} e assim por diante."
232
+ "form.modelAutoInjectHint","提示词自动写入工作流。尺寸和支持的质量档位在模型选择器里调整。","Prompts are inserted automatically. Adjust size and supported quality levels in the model picker.","プロンプトは自動で入力されます。サイズと対応する品質レベルはモデル選択メニューで調整できます。","Los prompts se insertan automáticamente. Ajusta el tamaño y los niveles de calidad admitidos en el selector de modelos.","Les prompts sont insérés automatiquement. Réglez la taille et les niveaux de qualité pris en charge dans le sélecteur de modèles.","Prompts werden automatisch eingefügt. Größe und verfügbare Qualitätsstufen lassen sich in der Modellauswahl einstellen.","Промпты подставляются автоматически. Размер и доступные уровни качества настраиваются в меню выбора модели.","Os prompts são inseridos automaticamente. Ajuste o tamanho e os níveis de qualidade disponíveis no seletor de modelos."
238
233
  "param.steps","步数","Steps","ステップ数","Pasos","Étapes","Schritte","Шаги","Passos"
239
234
  "param.cfg","提示词强度","CFG scale","プロンプト強度","Intensidad del prompt","Intensité du prompt","Prompt-Stärke","Сила промпта","Intensidade do prompt"
240
235
  "param.sampler_name","采样器","Sampler","サンプラー","Muestreador","Échantillonneur","Sampler","Сэмплер","Amostrador"
@@ -319,7 +314,7 @@ form.paramDescModel,请求里发送的模型名,Model name sent in the request,
319
314
  form.paramDescN,一次生成的张数,Images per request,1回に生成する枚数,Imágenes por petición,Images par requête,Bilder pro Anfrage,Изображений за запрос,Imagens por requisição
320
315
  form.paramNameHintWorkflow,工作流参数的名字只是给对话模型看的键,A workflow parameter name is only the key the chat model sees,ワークフローパラメータの名前は対話モデルが見るキーです,El nombre de un parámetro de flujo es solo la clave que ve el modelo,Le nom d'un paramètre de workflow n'est que la clé vue par le modèle,Der Name eines Workflow-Parameters ist nur der Schlüssel für das Chat-Modell,Имя параметра workflow — только ключ для чат-модели,O nome de um parâmetro de fluxo é só a chave vista pelo modelo
321
316
  form.paramNameRequired,参数名不能为空;留空的话请求里没有模型名,这个模型就发不出去,Parameter name cannot be empty; without it the request carries no model name and this model cannot be sent,パラメータ名は必須です。空欄だとリクエストにモデル名が入らず、このモデルは送信できません,El nombre del parámetro no puede estar vacío; sin él la petición no lleva nombre de modelo y este modelo no se puede enviar,Le nom du paramètre ne peut pas être vide ; sans lui la requête ne porte pas de nom de modèle et ce modèle ne peut pas être envoyé,Der Parametername darf nicht leer sein; ohne ihn enthält die Anfrage keinen Modellnamen und dieses Modell kann nicht gesendet werden,Имя параметра не может быть пустым; без него в запросе нет имени модели и эту модель нельзя отправить,O nome do parâmetro não pode ficar vazio; sem ele a requisição não leva nome de modelo e este modelo não pode ser enviado
322
- form.paramWorkflowTableHint,下面是这个模型的参数表:解析工作流与解析参数得到的行都在这里,勾上「暴露」对话模型才能用 params 调,This is the model parameter table: rows from parsing the workflow and the inputs land here; only exposed rows can be tuned through params,このモデルのパラメータ表です。ワークフロー解析とパラメータ解析の行はここに入り、「公開」した行だけ params で調整できます,Esta es la tabla de parámetros del modelo: aquí llegan las filas del flujo y de los parámetros analizados; solo las expuestas se ajustan con params,Voici la table des paramètres du modèle : les lignes issues de l'analyse du workflow et des entrées arrivent ici ; seules les lignes exposées se règlent via params,Das ist die Parametertabelle des Modells: Zeilen aus Workflow- und Parameteranalyse landen hier; nur freigegebene Zeilen lassen sich über params steuern,Это таблица параметров модели: строки из разбора workflow и входов попадают сюда; настраивать через params можно только показанные строки,Esta é a tabela de parâmetros do modelo: as linhas da análise do fluxo e das entradas ficam aqui; só as expostas podem ser ajustadas via params
317
+ form.paramWorkflowTableHint,开启「暴露」后,对话模型可以调整对应的工作流参数。,Expose a workflow parameter to let the chat model adjust it.,ワークフローのパラメータを公開するとチャットモデルが調整できます。,Expón un parámetro del flujo para que el modelo de chat pueda ajustarlo.,Exposez un paramètre du workflow pour que le modèle de chat puisse l’ajuster.,Gib einen Workflow-Parameter frei damit das Chatmodell ihn anpassen kann.,Откройте параметр рабочего процесса для изменения моделью чата.,Exponha um parâmetro do fluxo para permitir que o modelo de chat o ajuste.
323
318
  form.paramsEmptyWorkflow,"还没解析出参数。先粘贴工作流,再点「解析工作流」。","No parameters parsed yet. Paste a workflow, then click “Parse workflow”.","まだパラメータを解析していません。先にワークフローを貼り付け、「ワークフローを解析」をクリックしてください。","Aún no hay parámetros analizados. Pega un flujo de trabajo y luego pulsa «Analizar flujo de trabajo».","Aucun paramètre analysé pour l’instant. Collez un workflow, puis cliquez sur « Analyser le workflow ».","Noch keine Parameter analysiert. Fügen Sie zuerst einen Workflow ein und klicken Sie dann auf „Workflow analysieren“.","Параметры ещё не разобраны. Вставьте workflow и нажмите «Разобрать workflow».","Nenhum parâmetro analisado ainda. Cole um fluxo de trabalho e clique em «Analisar fluxo»."
324
319
  form.paramsEmpty,"这个模型还没有可调参数,点「添加参数」自己加。","This model has no tunable parameters yet. Click “Add parameter” to add one.","このモデルにはまだ調整できるパラメータがありません。「パラメータを追加」から追加してください。","Este modelo aún no tiene parámetros ajustables. Pulsa «Añadir parámetro» para crear uno.","Ce modèle n’a pas encore de paramètres réglables. Cliquez sur « Ajouter un paramètre » pour en créer un.","Dieses Modell hat noch keine einstellbaren Parameter. Klicken Sie auf „Parameter hinzufügen“, um einen anzulegen.","У этой модели пока нет настраиваемых параметров. Нажмите «Добавить параметр», чтобы создать.","Este modelo ainda não tem parâmetros ajustáveis. Clique em «Adicionar parâmetro» para criar um."
325
320
  form.a1111ParamRowsHint,默认值会随请求发送;清空某一行的默认值就沿用 WebUI 里的设置,Defaults are sent with the request; clear a default to fall back to the WebUI setting,既定値はリクエストと一緒に送信されます。空にすると WebUI の設定に従います,Los valores por defecto se envían con la petición; vacía uno para usar la configuración del WebUI,Les valeurs par défaut sont envoyées avec la requête ; videz-en une pour suivre le réglage du WebUI,Standardwerte werden mitgesendet; ein geleerter Wert folgt der WebUI-Einstellung,Значения по умолчанию отправляются с запросом; очистите — возьмётся настройка WebUI,Os padrões são enviados com a requisição; limpe um valor para seguir a configuração do WebUI
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mo-image",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "DSH plugin: generate and edit images with model-aware prompt guidance over an OpenAI-compatible image model",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -24,7 +24,6 @@
24
24
  "icon.png",
25
25
  "cordis.patch.yml",
26
26
  "CHANGELOG.md",
27
- "THIRD-PARTY-NOTICES.md",
28
27
  "README.md"
29
28
  ],
30
29
  "engines": {
@@ -11,12 +11,13 @@ whenToUse: 修改或融合参考图时,需要当前上下文中没有的编辑
11
11
  - 只负责把编辑提示词和参考图交给生图模型,不替用户判断图片好坏。
12
12
  - 本会话首次生图或改图前调用 `mo_image_settings`。之后直接调用 `mo_image_edit`,由工具通过 `needsSettings` 返回变更或校准配置。使用返回的完整设置,或在 `baseRevision` 上应用 `changes`、清除 `removed`,然后发起新调用。应用增量时找不到基线才用 `refresh:true` 读取完整配置。
13
13
  - 自动模型使用 `editModelIndexes` 从 `models` 选择,也可以省略 `model` 使用首个可改图的候选。需要具体尺寸、质量或参数时,传候选的模型 ID 查询。
14
+ - ComfyUI 若返回 `referenceImages`,按其中的编号、用途和数量传 `images`。自动模式下,若所选候选位于 `referenceModelIndexes`,在缺少该候选详情或 `referenceRevision` 改变时查询一次。图片用途有歧义时向用户确认。
14
15
  - `model` 不用传:非 Auto 时用选择器里的模型,传别的值会被拒绝;Auto 必须从当前列表里选一个。
15
16
  - 图片返回即交付:最终回复只输出工具给的图片行;不评价画质、不描述画面。除非用户明确要求看图,否则不要打开或读取图片。
16
17
  - 只用选择器里的提供商和模型:不要自行切换,也不要用本地生图、建模/Blender、脚本绘图替代。
17
18
  - 收到「生图配置不匹配(未提交)」时,用 `mo_image_settings({"refresh":true})` 重读完整配置,纠正参数后只重试一次。仍失败或遇到其他错误时原样报错。沿用用户选定的提供商和模型。
18
19
 
19
- 优化开启时,在提示词里**说清改什么、保留什么**。复用上下文已有的写法和合适的成稿。优化关闭时,prompt 只写用户原话或做最低限度整理;用户明确要求优化时才改写。两种模式都按用户指定的顺序传参考图。
20
+ 优化开启时,在提示词里**说清改什么、保留什么**。复用上下文已有的写法和合适的成稿。优化关闭时,prompt 只写用户原话或做最低限度整理;用户明确要求优化时才改写。工作流有入口编号时按编号传参考图,其余情况沿用用户指定的顺序。
20
21
 
21
22
  ## 一、编辑公式
22
23
 
@@ -1,32 +0,0 @@
1
- # Third-party notices
2
-
3
- ## dsh-codex-model-effort-selector
4
-
5
- The Codex-skin geometry (272×104 popover, 30px knob, rail padding), the
6
- per-level colour ramps (light/dark), the deterministic sparkle/bloom
7
- distribution, the ⚡ Fast toggle/`fast-mode` class contract, the peak
8
- gradient/sparkle treatment and several interaction details in `lib/client.js`
9
- are adapted from
10
- [dsh-codex-model-effort-selector](https://github.com/ABING1111/dsh-codex-model-effort-selector).
11
-
12
- MIT License
13
-
14
- Copyright (c) 2026 dsh-codex-model-effort-selector contributors
15
-
16
- Permission is hereby granted, free of charge, to any person obtaining a copy
17
- of this software and associated documentation files (the "Software"), to deal
18
- in the Software without restriction, including without limitation the rights
19
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20
- copies of the Software, and to permit persons to whom the Software is
21
- furnished to do so, subject to the following conditions:
22
-
23
- The above copyright notice and this permission notice shall be included in all
24
- copies or substantial portions of the Software.
25
-
26
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
- SOFTWARE.