dsh-mo-image 0.7.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,25 +1,28 @@
1
- import { mkdirSync, existsSync, appendFileSync, readFileSync, writeFileSync, statSync } from 'node:fs';
2
- import { readFile, writeFile, stat, rename, unlink } from 'node:fs/promises';
1
+ import { constants, mkdirSync, existsSync, appendFileSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { writeFile, open, stat, rename, unlink } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
- import { randomUUID, randomBytes, createHmac, timingSafeEqual } from 'node:crypto';
5
+ import { randomUUID, randomBytes, createHash, createHmac, timingSafeEqual } from 'node:crypto';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { lookup } from 'node:dns/promises';
8
8
  import { isIP } from 'node:net';
9
+ import { pipeline } from 'node:stream/promises';
9
10
  import {
10
- resolveAdapter, describeAdapter, fitSize, sizePolicyFor, sizeSpecFor,
11
+ resolveAdapter, describeAdapter, selectedProtocolOf, fitSize, sizePolicyFor, sizeRuleFor, sizeSpecFor,
11
12
  parseSize, nearestAspect, nearestTier, sizeForAspect,
12
- qualityForAdapter, qualityOptionsFor, filterImageModels,
13
+ qualityOptionsFor, isLikelyImageModel,
13
14
  readResponseBytes, looksLikeImage, sniffType,
14
15
  listProviderModelEntries, adapterManifest, localPresetManifest, providerPresetManifest,
15
- analyzeComfyWorkflow, A1111_PARAMS
16
+ adapterCanListModels, listsOpenAiCompatibleModels, fieldsFor,
17
+ analyzeComfyWorkflow, listComfyParams, paramDefaultsManifest, detectProtocolStart, probeProtocolPath, operationFieldsFor,
18
+ AUTH_MODES
16
19
  } from './adapters.js';
17
20
  import {
18
- applySizeStitch, finalizeImage, finalizeImageAsync, saveImage, saveSidecar, sizeLabel, stitchSizePrompt
21
+ applySizeStitch, checkImageOutput, finalizeImage, finalizeImageAsync, saveImage, saveSidecar, sizeLabel, stitchSizePrompt
19
22
  } from './image-service.js';
20
23
  export { finalizeImage, finalizeImageAsync, stitchSizePrompt };
21
- import { CONFIG_STATE_MARKER, CONFIG_STATE_VARIABLE, configStateText, promptSectionText, resolvePromptProfile, settingsPayload } from './prompt-profiles.js';
22
- import { rememberSettings, settingsSignature, settingsState } from './settings-memory.js';
24
+ import { CONFIG_STATE_MARKER, CONFIG_STATE_VARIABLE, configStateText, promptSectionText, resolvePromptProfile, settingsForModel, settingsPayload } from './prompt-profiles.js';
25
+ import { createSettingsMemory, settingsSnapshot } from './settings-memory.js';
23
26
  import { request, setNetworkLogger } from './net.js';
24
27
  import { configWriteReason } from './config-guard.js';
25
28
  import { localizedError, errorBody } from './localized-error.js';
@@ -27,22 +30,26 @@ import { createUpdateService } from './update-service.js';
27
30
  import { createImageQueue } from './image-queue.js';
28
31
  import { createCallRegistry, createJobJournal } from './image-jobs.js';
29
32
  import {
30
- attachFailure, callAsyncImage, callImageApi, followTask,
33
+ attachFailure, callImageApi, followTask,
31
34
  setImageExecutionLogger, stableStringify, TOTAL_BUDGET_MS
32
35
  } from './image-execution.js';
36
+ import { taskPollTargets, taskSpecOf } from './output-profiles.js';
37
+ import { assertReferenceCount, outputPresetManifest } from './provider-operations.js';
38
+ import { joinEndpoint, resolveHttpUrl } from './adapter-kit.js';
33
39
  export { callImageApi };
34
40
  import {
35
- activeImageState, assertLocalRequest, canUseCredentials, capabilityManifest, createConfigStore,
41
+ activeImageState, assertLocalRequest, canUseCredentials, capabilityManifest, createConfigStore, modelImageState,
36
42
  describeImageStatus as describeImageStatusBase, normalizeConfig, normalizeDefaults,
37
- normalizeModelOptions, publicConfig, readConfig, readConfigSync, resolveProviderCredential,
38
- resolveQuality, resolveSizeRequest, saveConfigWithCredentials
43
+ normalizeModelOptions, paramNoticeOf, publicConfig, readConfig, readConfigSync, resolveProviderCredential,
44
+ imageSettingsMismatch, resolveQuality, resolveSizeRequest, resolveToolQuality, saveConfigWithCredentials, validateProviderDraft
39
45
  } from './config-store.js';
40
46
  export {
41
47
  capabilityManifest, normalizeConfig, normalizeDefaults, normalizeModelOptions,
42
- resolveSizeRequest, workflowParamsOf
48
+ paramNoticeOf, resolveSizeRequest, workflowParamsOf
43
49
  } from './config-store.js';
44
- import { MAPPING_KEYS, DEFAULT_EXPOSED } from './comfy-workflow.js';
50
+ import { MAPPING_KEYS } from './comfy-workflow.js';
45
51
  import { STATUS_CONTRACT, editCapableModels, pickAutoEditModel } from './status.js';
52
+ import { detectQualityRule, detectFieldRule } from './model-rules.js';
46
53
 
47
54
  const PLUGIN = 'dsh-mo-image';
48
55
  function dshHome() {
@@ -85,17 +92,47 @@ function ensureDirs() { mkdirSync(outputDir(), { recursive: true }); }
85
92
  function logHost(message) {
86
93
  try { appendFileSync(hostLogFile(), new Date().toISOString() + ' ' + message + '\n'); } catch (_error) { /* diagnostics */ }
87
94
  }
88
- function sessionCwd(exec) {
95
+ function sessionCwd(ctx, exec) {
96
+ const session = exec?.agent?.session;
97
+ if (!session) return '';
89
98
  try {
90
- const cwd = exec && exec.agent && exec.agent.session && exec.agent.session.header && exec.agent.session.header.cwd;
91
- return typeof cwd === 'string' && path.isAbsolute(cwd) ? cwd : '';
92
- } catch (_error) { return ''; }
99
+ const current = ctx.get?.('sessionProjections')?.stateOf(session, 'workingDirectory');
100
+ if (typeof current === 'string' && path.isAbsolute(current)) return current;
101
+ } catch (_error) { /* Older hosts can still supply the session's starting directory. */ }
102
+ const start = session.header?.cwd;
103
+ return typeof start === 'string' && path.isAbsolute(start) ? start : '';
93
104
  }
94
- /** 新图优先写进当前项目目录;没有 session cwd 时退回 DSH 状态目录。 */
95
- function generatedImageDir(exec) {
96
- const cwd = sessionCwd(exec);
105
+ function generatedImageDir(cwd) {
97
106
  return cwd ? path.join(cwd, 'generated-images') : outputDir();
98
107
  }
108
+
109
+ async function verifyImageOutput(cwd) {
110
+ const dir = generatedImageDir(cwd);
111
+ try {
112
+ await checkImageOutput(dir);
113
+ } catch (cause) {
114
+ throw attachFailure(new Error('无法写入生图目录 ' + dir + '。请检查目录和写入权限。', { cause }), {
115
+ code: 'output_unavailable', phase: 'prepare', submissionState: 'rejected'
116
+ });
117
+ }
118
+ }
119
+
120
+ /** 本地 Markdown 图片用绝对路径,宿主才能保留右键菜单所需的文件路径。 */
121
+ function markdownFilePath(file) {
122
+ if (typeof file !== 'string' || !path.isAbsolute(file) || /^[\\/]{2}/u.test(file) || /[\u0000-\u001f\u007f]/u.test(file)) return '';
123
+ const normalized = path.sep === '\\' ? file.replace(/\\/g, '/') : file;
124
+ return normalized.split('/').map((segment, index) => (
125
+ index === 0 && /^[a-z]:$/i.test(segment)
126
+ ? segment
127
+ : encodeURIComponent(segment).replace(/[()]/g, (char) => char === '(' ? '%28' : '%29')
128
+ )).join('/');
129
+ }
130
+
131
+ function belongsToWorkspace(cwd, file) {
132
+ if (!cwd || !path.isAbsolute(file)) return false;
133
+ const relative = path.relative(cwd, file);
134
+ return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
135
+ }
99
136
  let previewKeyCache = null;
100
137
  /** 预览 URL 用 HMAC 签名,图片本体留在项目目录,宿主只保存一把很小的 key。 */
101
138
  function previewKey() {
@@ -173,35 +210,33 @@ function pickProvider(config, purpose, args) {
173
210
  // 它会把对话历史里的旧 id 再抄一遍,用户中途切换模型后必定白失败一轮。
174
211
  // 传了不一致的值仍然拒绝,防止对话模型自己换提供商/模型。
175
212
  if (requestedProvider && requestedProvider !== provider.id && requestedProvider !== provider.name) {
176
- throw new Error('提供商由用户在设置里固定(当前:' + (provider.name || provider.id) + '),请求的是 ' + requestedProvider + '。要换提供商请让用户在设置里切换。');
213
+ throw imageSettingsMismatch('提供商由用户在设置里固定(当前:' + (provider.name || provider.id) + '),请求的是 ' + requestedProvider + '。沿用当前提供商');
177
214
  }
178
215
  let model;
179
216
  if (activeModel === 'auto') {
217
+ const models = provider.models || [];
218
+ if (requestedModel && models.length && !models.includes(requestedModel)) {
219
+ throw imageSettingsMismatch('Auto 模式只能选当前提供商列表里的模型 ID');
220
+ }
180
221
  if (purpose === 'edit') {
181
222
  // Auto 改图:只在能图生图的模型里选。没传 model 时自动取第一个,
182
223
  // 传了但不能图生图就报清楚可选项,不要把问题拖到适配器层。
183
- if (requestedModel && !(provider.models || []).includes(requestedModel)) {
184
- throw new Error('Auto 模式只能选当前提供商列表里的模型:' + requestedModel + '。可选:' + ((provider.models || []).join(' / ') || '(列表为空)'));
185
- }
186
- const picked = pickAutoEditModel(provider, provider.models || [], requestedModel);
224
+ const picked = pickAutoEditModel(provider, models, requestedModel);
187
225
  if (!picked.model) {
188
- throw new Error(picked.capable.length
189
- ? 'Auto 模式下该模型不支持图生图:' + requestedModel + '。可改图的模型:' + picked.capable.join(' / ')
190
- : 'Auto 模式下当前提供商没有支持图生图的模型,请到设置 → 生图模型换一个支持编辑的模型。');
226
+ if (picked.capable.length) {
227
+ throw imageSettingsMismatch('Auto 模式下该模型不支持图生图:' + requestedModel + '。请核对 editModelIndexes');
228
+ }
229
+ throw new Error('Auto 模式下当前提供商没有支持图生图的模型,请到设置 → 生图模型换一个支持编辑的模型。');
191
230
  }
192
231
  model = picked.model;
193
232
  } else {
194
- if (!requestedModel) {
195
- throw new Error('Auto 模式下要由你选一个模型:' + ((provider.models || []).join(' / ') || '(列表为空,请让用户先在设置里添加模型)') + ',通过 model 传入。');
196
- }
197
- if (!(provider.models || []).includes(requestedModel)) {
198
- throw new Error('Auto 模式只能选当前提供商列表里的模型:' + requestedModel + '。可选:' + ((provider.models || []).join(' / ') || '(列表为空)'));
199
- }
233
+ if (!models.length) throw new Error('模型列表为空,请让用户先在设置里添加模型。');
234
+ if (!requestedModel) throw imageSettingsMismatch('Auto 模式下要由你选一个模型:从 models 选择并通过 model 传入');
200
235
  model = requestedModel;
201
236
  }
202
237
  } else {
203
238
  if (requestedModel && requestedModel !== activeModel) {
204
- throw new Error('当前选中的模型是 ' + activeModel + '(提供商 ' + (provider.name || provider.id) + '),请求的是 ' + requestedModel + '。模型只能由用户在设置里切换。');
239
+ throw imageSettingsMismatch('当前选中的模型是 ' + activeModel + '(提供商 ' + (provider.name || provider.id) + '),请求的是 ' + requestedModel + '。模型只能由用户切换,固定时省略 model');
205
240
  }
206
241
  model = activeModel;
207
242
  }
@@ -216,6 +251,15 @@ function pickProvider(config, purpose, args) {
216
251
  // 协议/适配器解析交给 resolveAdapter():不同模型族的请求形状由适配器描述符定义。
217
252
  // API Key 由 resolveProviderCredential() 在请求前从 DSH 凭据库解析,不在这里检查。
218
253
  if (!provider.baseUrl) throw new Error('生图提供商缺少 API 地址,请到设置 → 生图模型补全。');
254
+ // 「未选择协议」不发请求:路径、字段名和响应解析全由协议决定,猜一个只会把请求发错
255
+ // (以前是拿协议表的最后一条 openai-images 当默认值,而界面上写着「自动」)。
256
+ if (!selectedProtocolOf(provider)) {
257
+ throw localizedError(
258
+ new Error('提供商 ' + (provider.name || provider.id) + ' 还没有选择 API 协议:请到设置 → 生图模型里选一条(或点「识别协议」)再试。'),
259
+ 'adapter.noProtocol',
260
+ { provider: String(provider.name || provider.id || '') }
261
+ );
262
+ }
219
263
  return { provider, model };
220
264
  }
221
265
  function makeSignal(exec, timeoutMs) {
@@ -226,10 +270,9 @@ function makeSignal(exec, timeoutMs) {
226
270
  return signals.length > 1 && AbortSignal.any ? AbortSignal.any(signals) : signals[0];
227
271
  }
228
272
  /**
229
- * 上游生图任务的全局并发槽。
273
+ * 生图任务的全局并发槽。
230
274
  *
231
- * 排队等待也算在工具总超时里(signal 已经带 timeout):用户不能看到工具卡在队列里
232
- * 却一直没有截止时间。槽位只包住真正发往上游的那一段,本地参考图读取不占位。
275
+ * 排队和参考图读取共用工具的取消预算。只在持有槽位时保留输入和输出图片。
233
276
  */
234
277
  async function withUpstreamSlot(queue, signal, task) {
235
278
  if (!queue) return task();
@@ -240,13 +283,43 @@ async function withUpstreamSlot(queue, signal, task) {
240
283
  release();
241
284
  }
242
285
  }
286
+
287
+ async function saveResult(result, provider, model, cwd, defaults, journal, notes = []) {
288
+ try {
289
+ const final = await finalizeImageAsync(result, { strict: defaults.strict === true }, logHost);
290
+ const saved = await saveImage(final.bytes, sniffType(final.bytes), provider, model, sizeLabel(final.fitted), generatedImageDir(cwd));
291
+ if (final.generated) saved.generated = final.generated;
292
+ if (final.original) {
293
+ const kept = await saveSidecar(final.original, sniffType(final.original), saved.file, logHost);
294
+ if (kept) saved.original = kept;
295
+ }
296
+ const combinedNotes = [final.note, ...notes].filter(Boolean);
297
+ if (combinedNotes.length) saved.note = combinedNotes.join(';');
298
+ if (result.jobId) {
299
+ saved.jobId = result.jobId;
300
+ await journal?.update(result.jobId, {
301
+ status: 'saved', file: saved.file, size: saved.size, generated: saved.generated || '',
302
+ original: saved.original || '', note: saved.note || ''
303
+ }).catch((error) => logHost('job journal save update failed: ' + error.message));
304
+ }
305
+ return saved;
306
+ } catch (error) {
307
+ if (result.resumable && result.jobId) {
308
+ error.message += '。可用 resume_job_id=' + result.jobId + ' 继续同一个任务。';
309
+ }
310
+ throw attachFailure(error, {
311
+ code: 'save_failed', phase: 'save', submissionState: 'accepted',
312
+ jobId: result.jobId, resumable: result.resumable === true
313
+ });
314
+ }
315
+ }
243
316
  /**
244
317
  * 恢复一个已经提交过的异步任务:不重新提交,只沿任务日志里的
245
318
  * submission / taskId / pollTarget 继续轮询并下载。
246
319
  *
247
320
  * 只支持异步任务;同步任务没有可查询的远端状态,任务日志也不会为它们落盘。
248
321
  */
249
- async function resumeImageJob(args, exec, store, snapshot, queue, journal) {
322
+ async function resumeImageJob(args, exec, store, snapshot, queue, journal, cwd) {
250
323
  const jobId = String((args && args.resume_job_id) || '').trim();
251
324
  if (!jobId) throw new Error('resume_job_id 不能为空');
252
325
  const job = await journal.get(jobId);
@@ -259,76 +332,76 @@ async function resumeImageJob(args, exec, store, snapshot, queue, journal) {
259
332
  const defaults = (config && config.defaults) || {};
260
333
 
261
334
  // 已经保存过、文件还在:直接返回原结果,不再打上游。
262
- if (job.status === 'saved' && job.file && existsSync(job.file)) {
335
+ const savedFile = job.status === 'saved' && job.file ? await stat(job.file).catch(() => null) : null;
336
+ if (savedFile?.isFile()) {
263
337
  return {
264
338
  file: job.file, filename: path.basename(job.file), provider: job.providerName || job.providerId,
265
- model: job.model, size: job.size, bytes: 0, contentType: '',
339
+ model: job.model, size: job.size, bytes: savedFile.size, contentType: '',
266
340
  generated: job.generated || '', original: job.original || '', note: job.note || '', jobId: job.id
267
341
  };
268
342
  }
269
343
  if (job.status === 'submitting') {
270
- throw attachFailure(new Error('这个任务在提交途中中断,无法确认上游是否已经受理;请先按原提示词重新提交,避免重复计费。'), {
271
- code: 'submission_unknown', phase: 'resume', submissionState: 'unknown', jobId: job.id
344
+ throw attachFailure(new Error('任务提交途中中断,受理状态未知。请先在供应商侧核实任务或账单。'), {
345
+ code: 'submission_unknown', phase: 'resume', submissionState: 'unknown', jobId
272
346
  });
273
347
  }
274
- if (!job.submission || (!job.pollTarget && !job.submitUrl)) {
275
- throw attachFailure(new Error('任务日志缺少恢复所需的任务信息(submission / pollTarget / submitUrl),无法继续查询。'), {
276
- code: 'job_not_resumable', phase: 'resume', jobId: job.id
348
+ if (job.status === 'failed' || job.status === 'rejected') {
349
+ throw attachFailure(new Error(job.failure || '上游已结束任务,无法继续查询。'), {
350
+ code: 'job_not_resumable', phase: 'resume', jobId
277
351
  });
278
352
  }
279
353
 
280
- const provider = (config.providers || []).find((item) => item && item.id === job.providerId);
354
+ const provider = config.providers.find((item) => item.id === job.providerId);
281
355
  if (!provider) {
282
356
  throw attachFailure(new Error('恢复任务所属的提供商已不存在:' + job.providerId + '。请恢复提供商配置后再试。'), {
283
- code: 'job_provider_missing', phase: 'resume', jobId: job.id
357
+ code: 'job_provider_missing', phase: 'resume', jobId
284
358
  });
285
359
  }
286
- const resolved = await resolveProviderCredential(store, provider);
287
- const adapter = resolveAdapter(resolved, job.model);
288
-
289
- const signal = makeSignal(exec, 360000);
290
- const deadline = Date.now() + TOTAL_BUDGET_MS;
291
- let result;
292
- if (adapter.autoAsync && job.submitUrl) {
293
- // 通用网关:提交响应就是任务包络;恢复时从同一个 submitUrl 推导轮询候选。
294
- result = await withUpstreamSlot(queue, signal, () => followTask(
295
- job.kind === 'edit' ? 'edit' : 'generate',
296
- adapter, resolved, job.submission, job.submitUrl, null, job.fitted, job.model,
297
- signal, deadline, { resume: { jobId: job.id } }
298
- ));
299
- } else if (adapter.async) {
300
- result = await withUpstreamSlot(queue, signal, () => callAsyncImage(
301
- job.kind === 'edit' ? 'edit' : 'generate',
302
- adapter, resolved,
303
- { model: job.model, fitted: job.fitted },
304
- signal,
305
- {
306
- journal: null,
307
- resume: {
308
- jobId: job.id, submission: job.submission, taskId: job.taskId,
309
- pollTarget: job.pollTarget, fitted: job.fitted, note: job.note || ''
310
- }
311
- }
312
- ));
313
- } else {
314
- throw attachFailure(new Error('该任务不是异步队列任务,无法从任务日志恢复。'), {
315
- code: 'job_not_resumable', phase: 'resume', jobId: job.id
360
+ const adapter = resolveAdapter(provider, job.model);
361
+ const kind = job.kind === 'edit' ? 'edit' : 'generate';
362
+ const originOf = (value) => {
363
+ const url = resolveHttpUrl(value);
364
+ return url ? new URL(url).origin : '';
365
+ };
366
+ const route = adapter.routes?.[kind];
367
+ const currentTarget = route ? joinEndpoint(provider.baseUrl, route) : provider.baseUrl;
368
+ if (adapter.id !== job.adapterId || (job.providerOrigin && job.providerOrigin !== originOf(currentTarget))
369
+ || (job.baseOrigin && job.baseOrigin !== originOf(provider.baseUrl))) {
370
+ throw attachFailure(new Error('任务的提供商协议或目标地址已改变。请恢复原配置后继续该任务。'), {
371
+ code: 'job_provider_changed', phase: 'resume', jobId
316
372
  });
317
373
  }
318
- const final = await finalizeImageAsync(result, { strict: defaults.strict === true }, logHost);
319
- const saved = await saveImage(final.bytes, final.contentType, resolved, job.model, sizeLabel(final.fitted), generatedImageDir(exec));
320
- if (final.generated) saved.generated = final.generated;
321
- if (final.original) {
322
- const kept = await saveSidecar(final.original, final.contentType, saved.file, logHost);
323
- if (kept) saved.original = kept;
374
+ const spec = job.taskSpec || taskSpecOf(adapter);
375
+ const submitUrl = job.submitUrl || provider.baseUrl;
376
+ const targets = job.pollTargets?.length ? job.pollTargets : job.pollTarget ? [job.pollTarget]
377
+ : spec ? taskPollTargets(spec, provider, job.submission, job.taskId, submitUrl) : [];
378
+ if (!spec || !targets.length) {
379
+ throw attachFailure(new Error('任务日志缺少可继续查询的状态地址。'), {
380
+ code: 'job_not_resumable', phase: 'resume', jobId
381
+ });
382
+ }
383
+ let resolved;
384
+ try {
385
+ resolved = await resolveProviderCredential(store, provider);
386
+ } catch (error) {
387
+ error.message += '。更新鉴权后可用 resume_job_id=' + jobId + ' 继续该任务。';
388
+ throw attachFailure(error, { phase: 'resume', jobId, resumable: true, submissionState: 'accepted' });
324
389
  }
325
- if (final.note) saved.note = final.note;
326
- saved.jobId = job.id;
327
- await journal.update(job.id, {
328
- status: 'saved', file: saved.file, size: saved.size, generated: saved.generated || '',
329
- original: saved.original || '', note: saved.note || ''
330
- }).catch((error) => logHost('job journal resume update failed: ' + String(error && error.message ? error.message : error)));
331
- return saved;
390
+ const signal = makeSignal(exec, 360000);
391
+ return withUpstreamSlot(queue, signal, async () => {
392
+ const result = await followTask(kind, {
393
+ ...adapter, operationOrigin: originOf(job.submitUrl || currentTarget),
394
+ pollNotFoundPending: job.pollNotFoundPending ?? adapter.pollNotFoundPending,
395
+ waitForTaskSuccess: job.waitForTaskSuccess ?? adapter.waitForTaskSuccess,
396
+ pollOrigins: job.pollOrigins ?? adapter.pollOrigins,
397
+ resultAuthOrigins: job.resultAuthOrigins ?? adapter.resultAuthOrigins,
398
+ pollHeaders: job.pollHeaders ?? adapter.pollHeaders
399
+ },
400
+ resolved, job.submission || {}, submitUrl, { spec, taskId: job.taskId, pollTargets: targets },
401
+ job.fitted, job.model, signal, Date.now() + TOTAL_BUDGET_MS, { journal, resume: { id: jobId }, note: job.note }
402
+ );
403
+ return saveResult(result, resolved, job.model, cwd, { strict: job.strict ?? defaults.strict }, journal);
404
+ });
332
405
  }
333
406
  /** 只保留有值的 params;别的形状一律当没传。 */
334
407
  function readParamsArg(args) {
@@ -342,7 +415,25 @@ function readParamsArg(args) {
342
415
  return Object.keys(out).length ? out : null;
343
416
  }
344
417
 
345
- async function generate(args, exec, store, snapshot, queue, journal) {
418
+ function imageSizePlan(provider, model, defaults, args, adapter) {
419
+ const requested = resolveSizeRequest(provider, model, defaults, args, adapter);
420
+ const fitted = fitSize(provider, { kind: requested.control, text: requested.arg }, model, adapter);
421
+ fitted.aspect = requested.aspect || fitted.aspect;
422
+ fitted.stitch = requested.stitch === true;
423
+ if (requested.tier && !fitted.tier) fitted.tier = requested.tier;
424
+ if (fitted.rejected) {
425
+ if (defaults.auto !== false && args?.size) throw imageSettingsMismatch(fitted.reason);
426
+ throw new Error(fitted.reason);
427
+ }
428
+ // A ratio or tier needs nominal dimensions for encoding, but it has no exact pixel target.
429
+ const explicit = defaults.auto === false
430
+ ? (requested.control === 'aspect' ? '' : requested.arg)
431
+ : args?.size;
432
+ fitted.requested = parseSize(explicit);
433
+ return { requested, fitted };
434
+ }
435
+
436
+ async function generate(args, exec, store, snapshot, queue, journal, cwd) {
346
437
  const prompt = String(args.prompt || '').trim();
347
438
  if (!prompt) throw new Error('prompt 不能为空:先按当前模型的提示词公式写好完整提示词。');
348
439
  const negativePrompt = String(args.negative_prompt || '').trim();
@@ -355,46 +446,24 @@ async function generate(args, exec, store, snapshot, queue, journal) {
355
446
  const adapter = resolveAdapter(provider, model);
356
447
  const profile = resolvePromptProfile(model, adapter);
357
448
  const defaults = (config && config.defaults) || {};
358
- const quality = qualityForAdapter(adapter, resolveQuality(defaults), model);
359
- const requested = resolveSizeRequest(adapter, model, defaults, args);
360
- const fitted = fitSize(adapter, { kind: requested.control, text: requested.arg }, model);
361
- fitted.aspect = requested.aspect || fitted.aspect;
362
- fitted.stitch = requested.stitch === true;
363
- if (requested.tier && !fitted.tier) fitted.tier = requested.tier;
364
- if (fitted.rejected) throw new Error(fitted.reason);
449
+ const quality = resolveToolQuality(provider, model, defaults, args, adapter);
450
+ const { requested, fitted } = imageSizePlan(provider, model, defaults, args, adapter);
365
451
  logHost('generate adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + (fitted.adjusted ? '(' + fitted.reason + ')' : ''));
366
452
  const signal = makeSignal(exec, 360000);
367
453
  const extraParams = readParamsArg(args);
368
- const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
454
+ // 只在真的用不上时才提:有暴露行的模型(A1111 / 通用路径的参数表)不该被说成「不支持」。
455
+ const paramNotice = paramNoticeOf(provider, model, adapter, extraParams ? Object.keys(extraParams) : []);
369
456
  const stitched = applySizeStitch(prompt, fitted, adapter, provider, model);
370
- const result = await withUpstreamSlot(queue, signal, () => callImageApi('generate', adapter, provider, {
371
- model: model, prompt: stitched.prompt, negativePrompt: negativePrompt || undefined,
372
- fitted: fitted, quality: quality, params: extraParams
373
- }, signal, journal ? { journal: journal, kind: 'generate', providerId: provider.id } : undefined));
374
- const final = await finalizeImageAsync(result, { strict: defaults.strict === true }, logHost);
375
- const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), generatedImageDir(exec));
376
- if (final.generated) saved.generated = final.generated;
377
- if (final.original) {
378
- const kept = await saveSidecar(final.original, final.contentType, saved.file, logHost);
379
- if (kept) saved.original = kept;
380
- }
381
- const notes = [];
382
- if (stitched.note) notes.push(stitched.note);
383
- if (final.note) notes.push(final.note);
384
- if (requested.note) notes.push(requested.note);
385
- if (fitted.reason) notes.push('尺寸 ' + fitted.reason);
386
- if (unsupported.length) notes.push('当前模型不支持工作流参数,已忽略:' + unsupported.join('、'));
387
- if (notes.length) saved.note = notes.join(';');
388
- if (result.jobId) {
389
- saved.jobId = result.jobId;
390
- if (journal) {
391
- await journal.update(result.jobId, {
392
- status: 'saved', file: saved.file, size: saved.size, generated: saved.generated || '',
393
- original: saved.original || '', note: saved.note || ''
394
- }).catch((error) => logHost('job journal save update failed: ' + String(error && error.message ? error.message : error)));
395
- }
396
- }
397
- return saved;
457
+ return withUpstreamSlot(queue, signal, async () => {
458
+ await verifyImageOutput(cwd);
459
+ const result = await callImageApi('generate', adapter, provider, {
460
+ model, prompt: stitched.prompt, negativePrompt: negativePrompt || undefined,
461
+ fitted, quality, params: extraParams
462
+ }, signal, { journal, strict: defaults.strict === true });
463
+ return saveResult(result, provider, model, cwd, defaults, journal, [
464
+ stitched.note, requested.note, fitted.reason && '尺寸 ' + fitted.reason, paramNotice
465
+ ]);
466
+ });
398
467
  }
399
468
  const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
400
469
  function isPrivateIpv4(address) {
@@ -463,12 +532,34 @@ async function fetchReferenceResponse(raw, signal) {
463
532
  }
464
533
  throw new Error('参考图重定向次数过多');
465
534
  }
466
- async function readReference(src, signal, index) {
535
+
536
+ function localReferenceFile(raw) {
537
+ const literal = path.resolve(raw);
538
+ if (existsSync(literal)) return literal;
539
+ if (path.isAbsolute(raw) && raw.includes('%')) {
540
+ try {
541
+ const decoded = path.normalize(decodeURIComponent(raw));
542
+ if (markdownFilePath(decoded) === raw && existsSync(decoded)) return decoded;
543
+ } catch (_error) { /* Keep the usual missing-file error for invalid escapes. */ }
544
+ }
545
+ throw new Error('找不到参考图:' + raw);
546
+ }
547
+
548
+ async function readReference(src, signal, index, remoteOnly) {
467
549
  const raw = String(src || '').trim();
468
550
  if (!raw) throw new Error('第 ' + (index + 1) + ' 张参考图为空');
469
551
  if (/^https?:\/\//i.test(raw)) {
552
+ if (remoteOnly) {
553
+ await assertReferenceUrl(raw);
554
+ const url = resolveHttpUrl(raw);
555
+ if (url) return { url, filename: 'ref-' + (index + 1) };
556
+ throw new Error('参考图 URL 无效');
557
+ }
470
558
  const response = await fetchReferenceResponse(raw, signal);
471
- if (!response.ok) throw new Error('下载参考图失败(第 ' + (index + 1) + ' 张):HTTP ' + response.status);
559
+ if (!response.ok) {
560
+ try { await response.body?.cancel(); } catch (_error) { /* already closed */ }
561
+ throw new Error('下载参考图失败(第 ' + (index + 1) + ' 张):HTTP ' + response.status);
562
+ }
472
563
  let buffer;
473
564
  try {
474
565
  buffer = await readResponseBytes(response, MAX_REF_BYTES);
@@ -478,14 +569,30 @@ async function readReference(src, signal, index) {
478
569
  if (!looksLikeImage(buffer)) throw new Error('参考图不是有效图片(第 ' + (index + 1) + ' 张):' + raw);
479
570
  return { buffer, contentType: sniffType(buffer), filename: 'ref-' + (index + 1) + (/\.(png|jpe?g|webp|gif)$/i.exec(raw) || ['.png'])[0] };
480
571
  }
481
- const file = path.resolve(raw);
482
- if (!existsSync(file)) throw new Error('找不到参考图:' + raw);
572
+ if (remoteOnly) throw new Error('该模型要求参考图使用可访问的 HTTP(S) URL');
573
+ const file = localReferenceFile(raw);
574
+ const ext = path.extname(file).toLowerCase();
483
575
  const info = await stat(file);
484
576
  if (!info.isFile()) throw new Error('参考图不是文件:' + raw);
485
- if (info.size > MAX_REF_BYTES) throw new Error('参考图超过 15MB:' + raw);
486
- const ext = path.extname(file).toLowerCase();
487
577
  if (!IMAGE_MIME[ext]) throw new Error('参考图只支持 png / jpg / jpeg / webp / gif:' + raw);
488
- const buffer = await readFile(file);
578
+ const local = await open(file, 'r');
579
+ let buffer;
580
+ try {
581
+ const { size } = await local.stat();
582
+ if (size > MAX_REF_BYTES) throw new Error('参考图超过 15MB:' + raw);
583
+ buffer = Buffer.allocUnsafe(size + 1);
584
+ let offset = 0;
585
+ while (offset < buffer.length) {
586
+ signal?.throwIfAborted();
587
+ const { bytesRead } = await local.read(buffer, offset, buffer.length - offset, offset);
588
+ if (!bytesRead) break;
589
+ offset += bytesRead;
590
+ }
591
+ if (offset !== size) throw new Error('参考图读取期间发生变化:' + raw);
592
+ buffer = buffer.subarray(0, size);
593
+ } finally {
594
+ await local.close();
595
+ }
489
596
  if (!looksLikeImage(buffer)) throw new Error('参考图不是有效图片:' + raw);
490
597
  return { buffer, contentType: sniffType(buffer), filename: path.basename(file) };
491
598
  }
@@ -494,24 +601,29 @@ export function referenceLimitFor(adapter) {
494
601
  }
495
602
 
496
603
  /** 有界并发读取参考图;结果按输入顺序返回。 */
497
- export async function readReferences(sources, signal, totalLimit = MAX_REF_TOTAL, concurrency = MAX_REF_CONCURRENCY) {
604
+ export async function readReferences(sources, signal, totalLimit = MAX_REF_TOTAL, concurrency = MAX_REF_CONCURRENCY, remoteOnly = false) {
498
605
  const list = Array.isArray(sources) ? sources : [];
499
606
  const images = new Array(list.length);
500
607
  let totalBytes = 0;
501
608
  let failure = null;
502
609
  let nextIndex = 0;
610
+ const controller = new AbortController();
611
+ const activeSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
503
612
  const worker = async () => {
504
613
  while (!failure) {
505
614
  const index = nextIndex++;
506
615
  if (index >= list.length) return;
507
616
  try {
508
- const image = await readReference(list[index], signal, index);
617
+ const image = await readReference(list[index], activeSignal, index, remoteOnly);
509
618
  if (failure) return;
510
- totalBytes += image.buffer.length;
619
+ totalBytes += image.buffer?.length || 0;
511
620
  if (totalBytes > totalLimit) throw new Error('参考图总大小超过 ' + Math.round(totalLimit / 1024 / 1024) + 'MB,请减少图片数量或压缩后再试。');
512
621
  images[index] = image;
513
622
  } catch (error) {
514
- failure = failure || error;
623
+ if (!failure) {
624
+ failure = error;
625
+ controller.abort(error);
626
+ }
515
627
  }
516
628
  }
517
629
  };
@@ -521,7 +633,7 @@ export async function readReferences(sources, signal, totalLimit = MAX_REF_TOTAL
521
633
  return images;
522
634
  }
523
635
 
524
- async function edit(args, exec, store, snapshot, queue, journal) {
636
+ async function edit(args, exec, store, snapshot, queue, journal, cwd) {
525
637
  const prompt = String(args.prompt || '').trim();
526
638
  if (!prompt) throw new Error('prompt 不能为空:图片编辑需要写清保留什么、只改什么。');
527
639
  const negativePrompt = String(args.negative_prompt || '').trim();
@@ -534,49 +646,34 @@ async function edit(args, exec, store, snapshot, queue, journal) {
534
646
  const model = picked.model;
535
647
  const provider = await resolveProviderCredential(store, picked.provider);
536
648
  const adapter = resolveAdapter(provider, model);
649
+ assertReferenceCount(adapter.operations?.edit, sources.length);
537
650
  const profile = resolvePromptProfile(model, adapter);
538
- const quality = qualityForAdapter(adapter, resolveQuality(defaults), model);
539
- const requested = resolveSizeRequest(adapter, model, defaults, args);
540
- const fitted = fitSize(adapter, { kind: requested.control, text: requested.arg }, model);
541
- fitted.aspect = requested.aspect || fitted.aspect;
542
- fitted.stitch = requested.stitch === true;
543
- if (requested.tier && !fitted.tier) fitted.tier = requested.tier;
544
- if (fitted.rejected) throw new Error(fitted.reason);
651
+ const quality = resolveToolQuality(provider, model, defaults, args, adapter);
652
+ const { requested, fitted } = imageSizePlan(provider, model, defaults, args, adapter);
545
653
  const signal = makeSignal(exec, 360000);
546
654
  const totalLimit = referenceLimitFor(adapter);
547
- const images = await readReferences(sources, signal, totalLimit);
548
- logHost('edit adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + ' refs=' + images.length);
655
+ logHost('edit adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + ' refs=' + sources.length);
549
656
  const extraParams = readParamsArg(args);
550
- const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
657
+ const paramNotice = paramNoticeOf(provider, model, adapter, extraParams ? Object.keys(extraParams) : []);
551
658
  const stitched = applySizeStitch(prompt, fitted, adapter, provider, model);
552
- const result = await withUpstreamSlot(queue, signal, () => callImageApi('edit', adapter, provider, {
553
- model: model, prompt: stitched.prompt, negativePrompt: negativePrompt || undefined,
554
- fitted: fitted, quality: quality, images: images, params: extraParams
555
- }, signal, journal ? { journal: journal, kind: 'edit', providerId: provider.id } : undefined));
556
- const final = await finalizeImageAsync(result, { strict: defaults.strict === true }, logHost);
557
- const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), generatedImageDir(exec));
558
- if (final.generated) saved.generated = final.generated;
559
- if (final.original) {
560
- const kept = await saveSidecar(final.original, final.contentType, saved.file, logHost);
561
- if (kept) saved.original = kept;
562
- }
563
- const notes = [];
564
- if (stitched.note) notes.push(stitched.note);
565
- if (final.note) notes.push(final.note);
566
- if (requested.note) notes.push(requested.note);
567
- if (fitted.reason) notes.push('尺寸 ' + fitted.reason);
568
- if (unsupported.length) notes.push('当前模型不支持工作流参数,已忽略:' + unsupported.join('、'));
569
- if (notes.length) saved.note = notes.join(';');
570
- if (result.jobId) {
571
- saved.jobId = result.jobId;
572
- if (journal) {
573
- await journal.update(result.jobId, {
574
- status: 'saved', file: saved.file, size: saved.size, generated: saved.generated || '',
575
- original: saved.original || '', note: saved.note || ''
576
- }).catch((error) => logHost('job journal save update failed: ' + String(error && error.message ? error.message : error)));
577
- }
578
- }
579
- return saved;
659
+ return withUpstreamSlot(queue, signal, async () => {
660
+ await verifyImageOutput(cwd);
661
+ const reference = operationFieldsFor(adapter, provider, model, 'edit').image;
662
+ const usesUrl = adapterTakesReferenceUrl(adapter, reference);
663
+ const images = await readReferences(sources, signal, totalLimit, MAX_REF_CONCURRENCY, usesUrl);
664
+ const result = await callImageApi('edit', adapter, provider, {
665
+ model: model, prompt: stitched.prompt, negativePrompt: negativePrompt || undefined,
666
+ fitted: fitted, quality: quality, images: images, params: extraParams
667
+ }, signal, { journal, strict: defaults.strict === true });
668
+ return saveResult(result, provider, model, cwd, defaults, journal, [
669
+ stitched.note, requested.note, fitted.reason && '尺寸 ' + fitted.reason, paramNotice
670
+ ]);
671
+ });
672
+ }
673
+
674
+ function adapterTakesReferenceUrl(adapter, reference) {
675
+ return reference?.as === 'url' && !adapter.async && typeof adapter.execute !== 'function'
676
+ && adapter.transport?.edit !== 'multipart';
580
677
  }
581
678
 
582
679
 
@@ -609,8 +706,32 @@ function parseSkillMarkdown(raw) {
609
706
  return { meta, body: text.slice(match[0].length) };
610
707
  }
611
708
 
709
+ const settingsViews = new WeakMap();
710
+ const emptySettingsView = settingsSnapshot(settingsPayload(null), '');
711
+
712
+ function settingsView(state) {
713
+ if (!state) return emptySettingsView;
714
+ const cached = settingsViews.get(state);
715
+ if (cached) return cached;
716
+ const payload = settingsPayload(state);
717
+ const { provider, defaults } = state;
718
+ // Details are served on demand. Changes to those settings must still invalidate past reads.
719
+ const models = state.model === 'auto' ? state.models : [state.model];
720
+ const modelSettings = models.map((id) => {
721
+ const model = provider.modelOptions?.[id];
722
+ return model ? [model.size, model.quality, model.params, model.expose, model.fields, model.operations] : null;
723
+ });
724
+ const signature = createHash('sha256').update(stableStringify([
725
+ payload, defaults, provider.baseUrl, provider.adapter, provider.protocolOptions, provider.operations,
726
+ state.workflowParams, modelSettings
727
+ ])).digest('hex');
728
+ const view = settingsSnapshot(payload, signature);
729
+ settingsViews.set(state, view);
730
+ return view;
731
+ }
732
+
612
733
  /** 把当前模型对应的提示词方言注入系统提示词;模型切换后下一次组装自动更新。 */
613
- function installPromptRecipe(ctx, store) {
734
+ function installPromptRecipe(ctx, store, settingsMemory) {
614
735
  const register = (target) => {
615
736
  if (!target.systemPrompt || typeof target.systemPrompt.section !== 'function') return;
616
737
  // 配置状态按会话算:本会话读过、之后配置没变,模型就直接生图,不必再读一遍。
@@ -621,8 +742,8 @@ function installPromptRecipe(ctx, store) {
621
742
  target.effect(() => target.systemPrompt.variable(CONFIG_STATE_VARIABLE, (context) => {
622
743
  try {
623
744
  const session = context && context.agent ? context.agent.session : null;
624
- const signature = settingsSignature(settingsPayload(activeImageState(store)));
625
- return configStateText(settingsState(session, signature));
745
+ const { signature } = settingsView(activeImageState(store));
746
+ return configStateText(settingsMemory.state(session, signature));
626
747
  } catch (error) {
627
748
  logHost('config state marker error: ' + String(error && error.message ? error.message : error));
628
749
  return configStateText('unread');
@@ -635,7 +756,7 @@ function installPromptRecipe(ctx, store) {
635
756
  const sectionText = (session) => {
636
757
  const state = activeImageState(store);
637
758
  if (!state) return '';
638
- const value = marker || configStateText(settingsState(session, settingsSignature(settingsPayload(state))));
759
+ const value = marker || configStateText(settingsMemory.state(session, settingsView(state).signature));
639
760
  return promptSectionText(state, value);
640
761
  };
641
762
  target.effect(() => target.systemPrompt.section({
@@ -686,48 +807,195 @@ function installBundledSkills(ctx) {
686
807
  export const name = PLUGIN;
687
808
  export const inject = ['webServer', 'tools'];
688
809
 
689
- async function modelsForRequest(store, body) {
810
+ /* ------------------------------------------------- 模型规则下发(尺寸 / 质量) */
811
+
812
+ /*
813
+ * 规则表(lib/model-rules.js)只有宿主能读到,浏览器 bundle 拿不到;这两个函数把
814
+ * 命中的规则压成 `modelOptions[model].size` / `.quality` 的形状,客户端能直接塞进
815
+ * 表单(「自动检测」按钮),也能原样存回配置当覆盖。
816
+ */
817
+
818
+ /** 尺寸规则 → `{ mode, field, separator, second, domain }`(规则点名时多带 control)。 */
819
+ function publicSizeRule(rule) {
820
+ const size = (rule && rule.size) || {};
821
+ const mode = typeof size.mode === 'string' ? size.mode.trim() : '';
822
+ const field = typeof size.field === 'string' ? size.field.trim() : '';
823
+ const declared = typeof size.separator === 'string' ? size.separator.trim() : '';
824
+ // 尺寸串线上默认用 x 分隔(encodeSize 也是这么兜的);宽高/比例/档位形态没有分隔符可言。
825
+ const separator = declared || (mode === 'wh-string' ? 'x' : '');
826
+ const value = {
827
+ mode: mode,
828
+ field: field,
829
+ separator: separator,
830
+ second: size.second && typeof size.second === 'object' ? size.second : null,
831
+ domain: rule && rule.domain && typeof rule.domain === 'object' ? rule.domain : {}
832
+ };
833
+ // 面板给哪种控件默认由 mode + domain 推导;规则显式点名的才带出来(向量模型是"面板给比例、线上发像素")。
834
+ if (typeof size.control === 'string' && size.control) value.control = size.control;
835
+ return value;
836
+ }
837
+
838
+ /** 质量规则 → `{ field, options, default, map }`;没命中就是 null(= 不发质量字段)。 */
839
+ function publicQualityRule(rule) {
840
+ const quality = (rule && rule.quality) || {};
841
+ const field = typeof quality.field === 'string' ? quality.field.trim() : '';
842
+ const options = Array.isArray(quality.options) ? quality.options.map((item) => String(item)) : [];
843
+ const fallback = typeof quality.default === 'string' ? quality.default : (options[0] || '');
844
+ return {
845
+ field: field,
846
+ options: options,
847
+ default: fallback,
848
+ map: quality.map && typeof quality.map === 'object' ? quality.map : null
849
+ };
850
+ }
851
+
852
+ /**
853
+ * 字段模板的「会怎么发」快照:三层合并后的结果(用户覆盖 > 模型规则 > 预设)。
854
+ * 面板拿它做只读摘要、一键配置拿它做写入来源;`null` 表示这个逻辑字段不发。
855
+ *
856
+ * 为什么在这里合而不是在客户端:规则表与预设都在宿主里,客户端只拿到结果。
857
+ * 认不出模板就当没有(形状不对的模板在保存时也会被丢一次,不必在这里炸路由)。
858
+ */
859
+ function publicFieldsOf(provider, model, adapter) {
860
+ let fields = null;
861
+ try { fields = fieldsFor(adapter, provider, model); } catch (_error) { fields = null; }
862
+ if (!fields || typeof fields !== 'object') return null;
863
+ const out = {};
864
+ for (const [name, spec] of Object.entries(fields)) {
865
+ if (spec === null || spec === false) { out[name] = null; continue; }
866
+ if (spec && typeof spec === 'object' && !Array.isArray(spec)) out[name] = spec;
867
+ }
868
+ return out;
869
+ }
870
+
871
+ /**
872
+ * 一条模型的规则快照:{ rule: { size, quality }, fields, matched }。
873
+ *
874
+ * 尺寸、质量和字段独立匹配。只有默认兜底时,保留协议默认值并允许手动设置。
875
+ */
876
+ function ruleSnapshot(provider, model) {
877
+ const baseUrl = provider && provider.baseUrl;
878
+ const unmatched = { rule: { size: null, quality: null }, fields: null, matched: false };
879
+ let adapter;
880
+ try { adapter = resolveAdapter(provider, model); } catch (_error) { return unmatched; }
881
+ const directionUsesProtocol = ['generate', 'edit'].some((kind) => (
882
+ adapter.endpoints?.[kind] && adapter.operations?.[kind]?.input !== 'explicit'
883
+ ));
884
+ if (!provider.presetId && adapter.id === 'custom' && !directionUsesProtocol) return unmatched;
885
+ const sizeRule = sizeRuleFor(provider, model, adapter);
886
+ const qualityRule = detectQualityRule(model, baseUrl, adapter.id);
887
+ const sizeSpecific = Boolean(sizeRule) && sizeRule.generic !== true;
888
+ return {
889
+ rule: {
890
+ size: sizeRule ? publicSizeRule(sizeRule) : null,
891
+ quality: qualityRule ? publicQualityRule(qualityRule) : null
892
+ },
893
+ fields: publicFieldsOf(provider, model, adapter),
894
+ matched: sizeSpecific || Boolean(qualityRule) || Boolean(detectFieldRule(model, baseUrl, adapter.id))
895
+ };
896
+ }
897
+
898
+ /** 复用草稿的协议上下文,规则匹配无需凭据。 */
899
+ function detectProviderOf(body) {
900
+ const provider = {
901
+ baseUrl: String((body && body.baseUrl) || '').trim(),
902
+ adapter: String((body && body.adapter) || '').trim(),
903
+ protocol: String((body && body.protocol) || 'openai-images').trim() || 'openai-images'
904
+ };
905
+ for (const name of ['presetId', 'protocolOptions', 'customEndpoints', 'operations']) {
906
+ if (body && Object.hasOwn(body, name)) provider[name] = body[name];
907
+ }
908
+ return provider;
909
+ }
910
+
911
+
912
+ /** 批量检测的模型清单:去空白、去重、限量,重复的模型只算一次。 */
913
+ function detectModelsOf(raw) {
914
+ const models = [];
915
+ const seen = new Set();
916
+ for (const item of Array.isArray(raw) ? raw : []) {
917
+ const id = String(item || '').trim();
918
+ if (!id || seen.has(id)) continue;
919
+ seen.add(id);
920
+ models.push(id);
921
+ if (models.length >= 200) break;
922
+ }
923
+ return models;
924
+ }
925
+
926
+ /**
927
+ * 本次拉取里哪些模型算"新增"——规则只对新模型跑,已存在的可能被用户手改过,不能用规则覆盖。
928
+ * 来源优先级:
929
+ * 1. 请求体的 `known`:表单里当前已勾选的模型 id 列表(客户端最清楚,优先);
930
+ * 2. 已保存的 `provider.models`:按 providerId 找回来的那个提供商原来有哪些模型;
931
+ * 3. 都没有(新建提供商)→ 整批都算新增。
932
+ */
933
+ function knownModelsForRequest(provider, providerId, body) {
934
+ if (Array.isArray(body && body.known)) {
935
+ return { source: 'request', models: body.known.map((id) => String(id || '').trim()).filter(Boolean) };
936
+ }
937
+ if (providerId && provider && Array.isArray(provider.models)) {
938
+ return { source: 'provider', models: provider.models.map((id) => String(id || '').trim()).filter(Boolean) };
939
+ }
940
+ return { source: 'none', models: [] };
941
+ }
942
+
943
+ /** 凭据解析失败里,只有「就是没配 Key」这两种算可区分的状态;别的失败不吞。 */
944
+ function isMissingCredentialError(error) {
945
+ const code = error && error.localized && error.localized.code;
946
+ return code === 'provider.missingKey' || code === 'provider.missingKeyWithRef';
947
+ }
948
+
949
+ /** Derive a provider the same way for settings probes, model discovery, and saved calls. */
950
+ async function draftProviderOf(store, body = {}, { requireBaseUrl = true } = {}) {
690
951
  const providerId = String(body.providerId || '').trim();
691
- let provider;
952
+ let saved;
692
953
  if (providerId) {
693
954
  const config = await readConfig(store);
694
- provider = (config.providers || []).find((item) => item.id === providerId);
695
- if (!provider) throw localizedError(new Error('找不到指定的生图提供商'), 'provider.notFound');
696
- provider = Object.assign({}, provider);
697
- if (body.baseUrl) provider.baseUrl = String(body.baseUrl).trim().replace(/\/+$/, '');
698
- if (body.adapter) provider.adapter = String(body.adapter).trim();
699
- if (body.protocol) provider.protocol = String(body.protocol).trim();
700
- if (body.optionalKey !== undefined) provider.optionalKey = !!body.optionalKey;
701
- const supplied = String(body.key || '').trim();
702
- if (supplied) {
703
- provider.key = supplied;
704
- delete provider.apiKeyEnv;
705
- }
706
- } else {
707
- const supplied = String(body.key || '').trim();
708
- provider = normalizeConfig({
709
- providers: [{
710
- id: 'model-list',
711
- baseUrl: String(body.baseUrl || '').trim(),
712
- adapter: String(body.adapter || '').trim(),
713
- protocol: String(body.protocol || 'openai-images').trim(),
714
- optionalKey: !!body.optionalKey,
715
- key: supplied
716
- }]
717
- }).providers[0];
955
+ saved = config.providers.find((item) => item.id === providerId);
956
+ if (!saved) throw localizedError(new Error('找不到指定的生图提供商'), 'provider.notFound');
957
+ }
958
+ const draft = { id: 'draft', ...saved };
959
+ for (const name of ['baseUrl', 'adapter', 'protocol', 'presetId', 'optionalKey', 'auth', 'protocolOptions', 'customEndpoints', 'operations']) {
960
+ if (Object.hasOwn(body, name)) draft[name] = body[name];
961
+ }
962
+ const supplied = String(body.key || '').trim();
963
+ if (supplied) {
964
+ draft.key = supplied;
965
+ delete draft.apiKeyEnv;
966
+ }
967
+ validateProviderDraft(draft, { resolve: false });
968
+ const provider = normalizeConfig({ providers: [draft] }).providers[0];
969
+ if (!provider.baseUrl) {
970
+ if (!requireBaseUrl) return { provider, credential: 'unchecked' };
971
+ const error = localizedError(new Error('请先填写 API 地址'), 'provider.missingBaseUrl');
972
+ error.status = 400;
973
+ throw error;
718
974
  }
719
- if (!provider || !provider.baseUrl) throw localizedError(new Error('请先填写 API 地址'), 'provider.missingBaseUrl');
720
975
  try {
721
- provider = await resolveProviderCredential(store, provider);
722
- } catch (_error) {
723
- // 模型列表接口本身可能不需要鉴权;没 key 也让它试一次,真 401 会由上游报出来。
976
+ return { provider: await resolveProviderCredential(store, provider), credential: 'ok' };
977
+ } catch (error) {
978
+ if (!isMissingCredentialError(error)) throw error;
979
+ return { provider, credential: 'missing' };
980
+ }
981
+ }
982
+
983
+ async function modelsForRequest(store, body) {
984
+ const { provider } = await draftProviderOf(store, body);
985
+ // 没选协议就没有可探测的列表端点(以前这里会退回 OpenAI 兼容的 /models 猜一把)。
986
+ if (!selectedProtocolOf(provider)) {
987
+ throw localizedError(
988
+ new Error('还没有选择 API 协议:先选一条再获取模型列表。'),
989
+ 'adapter.noProtocol',
990
+ { provider: String(provider.name || provider.id || '') }
991
+ );
724
992
  }
725
993
  let adapter = resolveAdapter(provider, '');
726
- if ((!adapter || typeof adapter.listModels !== 'function') && !String(provider.adapter || '').trim()) {
994
+ if (!adapterCanListModels(adapter) && !String(provider.adapter || '').trim()) {
727
995
  // 没有显式适配器的第三方/兼容网关,退回 OpenAI 兼容的 /models 探测。
728
996
  try { adapter = resolveAdapter(Object.assign({}, provider, { adapter: 'openai-images' }), ''); } catch (_error) { /* keep original */ }
729
997
  }
730
- if (!adapter || typeof adapter.listModels !== 'function') throw localizedError(new Error('该部署方式不支持获取模型列表'), 'models.unsupported');
998
+ if (!adapterCanListModels(adapter)) throw localizedError(new Error('该部署方式不支持获取模型列表'), 'models.unsupported');
731
999
  let entries;
732
1000
  try {
733
1001
  entries = await listProviderModelEntries(adapter, provider, AbortSignal.timeout(20000));
@@ -744,20 +1012,52 @@ async function modelsForRequest(store, body) {
744
1012
  }
745
1013
  throw error;
746
1014
  }
747
- const seen = new Set();
748
- const allModels = [];
749
- const names = {};
1015
+ const limit = 500;
1016
+ const mixed = listsOpenAiCompatibleModels(adapter);
1017
+ const first = new Map();
1018
+ const images = new Map();
750
1019
  for (const entry of Array.isArray(entries) ? entries : []) {
751
1020
  const id = String((entry && entry.id) || '').trim();
752
- if (!id || seen.has(id)) continue;
753
- seen.add(id);
754
- allModels.push(id);
1021
+ if (!id || first.has(id) || images.has(id)) continue;
755
1022
  const name = String((entry && entry.name) || '').trim();
1023
+ if (first.size < limit) first.set(id, name);
1024
+ if (mixed && isLikelyImageModel(id)) images.set(id, name);
1025
+ if (mixed ? images.size === limit : first.size === limit) break;
1026
+ }
1027
+ // 大型兼容目录可能先列数百个文本模型。图片优先保留,显示全部时再用其他模型补足上限。
1028
+ const names = Object.create(null);
1029
+ const allModels = [];
1030
+ let otherBudget = limit - images.size;
1031
+ for (const [id, name] of first) {
1032
+ if (!images.has(id) && otherBudget-- <= 0) continue;
1033
+ allModels.push(id);
1034
+ if (name && name !== id) names[id] = name;
1035
+ }
1036
+ for (const [id, name] of images) {
1037
+ if (first.has(id)) continue;
1038
+ allModels.push(id);
756
1039
  if (name && name !== id) names[id] = name;
757
- if (allModels.length >= 500) break;
758
1040
  }
759
- const models = adapter.id === 'openai-images' ? filterImageModels(allModels) : allModels;
760
- return { models: models, allModels: allModels, filteredCount: allModels.length - models.length, names: names };
1041
+ const models = mixed ? Array.from(images.keys()) : allModels;
1042
+ // 新模型的判定在 provider 还在手里的时候做(providerId 场景下 provider.models 就是已保存的列表)。
1043
+ const known = knownModelsForRequest(provider, String(body.providerId || '').trim(), body);
1044
+ const knownSet = new Set(known.models);
1045
+ const detected = Object.create(null);
1046
+ const detectedSnapshots = Object.create(null);
1047
+ const detectedModels = [];
1048
+ // 只对本次新增的模型算:决定面板"要不要自动填"的是宿主,客户端只管有没有手改过。
1049
+ for (const id of models) {
1050
+ if (knownSet.has(id)) continue;
1051
+ detectedModels.push(id);
1052
+ const snapshot = ruleSnapshot(provider, id);
1053
+ detected[id] = snapshot.rule;
1054
+ detectedSnapshots[id] = snapshot;
1055
+ }
1056
+ return {
1057
+ models: models, allModels: allModels, filteredCount: allModels.length - models.length, names: names,
1058
+ // detectedModels 就是 detected 的键(自解释:detected 里只有"本次新增"的模型)。
1059
+ detected, detectedModels, detectedSnapshots, knownSource: known.source
1060
+ };
761
1061
  }
762
1062
 
763
1063
  export function apply(ctx, options = {}) {
@@ -782,8 +1082,15 @@ export function apply(ctx, options = {}) {
782
1082
  const imageQueue = createImageQueue(options.queue && typeof options.queue === 'object' ? options.queue : {});
783
1083
  // 同一个 callId 的重放复用结果;只在内存里,进程重启后的恢复另由任务日志负责。
784
1084
  const callRegistry = createCallRegistry();
1085
+ const resumeInflight = new Map();
785
1086
  // 异步任务日志:提交后先落盘,进程重启时还能凭 jobId 找回远端任务。
786
1087
  const jobJournal = createJobJournal({ dir: path.join(stateDir(), 'jobs') });
1088
+ const configResponse = async (config) => ({
1089
+ ok: true, config: await publicConfig(store, config),
1090
+ adapters: adapterManifest(), authModes: AUTH_MODES.slice(), outputPresets: outputPresetManifest(),
1091
+ providerPresets: providerPresetManifest(), localPresets: localPresetManifest(),
1092
+ paramDefaults: paramDefaultsManifest(), capabilities: capabilityManifest(config)
1093
+ });
787
1094
  Promise.resolve(jobJournal.prune(7 * 24 * 60 * 60 * 1000))
788
1095
  .catch((error) => logHost('job journal prune failed: ' + String(error && error.message ? error.message : error)));
789
1096
  try { store.webOriginHost = new URL(ctx.webServer.getOrigin()).hostname; } catch (_error) { store.webOriginHost = ''; }
@@ -802,7 +1109,8 @@ export function apply(ctx, options = {}) {
802
1109
  if (canUseCredentials(store)) {
803
1110
  readConfig(store).catch((error) => logHost('config key migration failed: ' + String(error && error.message ? error.message : error)));
804
1111
  }
805
- installPromptRecipe(ctx, store);
1112
+ const settingsMemory = createSettingsMemory(ctx);
1113
+ installPromptRecipe(ctx, store, settingsMemory);
806
1114
  installBundledSkills(ctx);
807
1115
 
808
1116
  // 更新检查:宿主启动后预热一次,路由再按 12 小时的新鲜度补查。
@@ -858,12 +1166,12 @@ export function apply(ctx, options = {}) {
858
1166
  assertLocalRequest(store, req, req.method === 'POST');
859
1167
  if (req.method === 'GET') {
860
1168
  const config = await readConfig(store);
861
- return sendJson(res, 200, { ok: true, config: await publicConfig(store, config), adapters: adapterManifest(), providerPresets: providerPresetManifest(), localPresets: localPresetManifest(), capabilities: capabilityManifest(config) });
1169
+ return sendJson(res, 200, await configResponse(config));
862
1170
  }
863
1171
  if (req.method === 'POST') {
864
1172
  const body = await readBody(req);
865
1173
  const saved = await saveConfigWithCredentials(store, body.config || body);
866
- return sendJson(res, 200, { ok: true, config: await publicConfig(store, saved), adapters: adapterManifest(), providerPresets: providerPresetManifest(), localPresets: localPresetManifest(), capabilities: capabilityManifest(saved) });
1174
+ return sendJson(res, 200, await configResponse(saved));
867
1175
  }
868
1176
  return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
869
1177
  } catch (error) {
@@ -884,7 +1192,15 @@ export function apply(ctx, options = {}) {
884
1192
  if (req.method !== 'POST') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
885
1193
  const body = await readBody(req);
886
1194
  const result = await modelsForRequest(store, body || {});
887
- return sendJson(res, 200, { ok: true, models: result.models, allModels: result.allModels, filteredCount: result.filteredCount, names: result.names || {} });
1195
+ return sendJson(res, 200, {
1196
+ ok: true, models: result.models, allModels: result.allModels,
1197
+ filteredCount: result.filteredCount, names: result.names || {},
1198
+ // 只对本次新增的模型附规则:detectedModels 是 detected 的键,knownSource 说明
1199
+ // "新增"是按请求里的 known(request)、已保存的 provider.models(provider)判的,
1200
+ // 还是压根没有已知列表、整批都算新增(none)。
1201
+ detected: result.detected, detectedModels: result.detectedModels, detectedSnapshots: result.detectedSnapshots,
1202
+ knownSource: result.knownSource || 'none'
1203
+ });
888
1204
  } catch (error) {
889
1205
  return sendJson(res, Number(error && error.status) || 502, errorBody(error));
890
1206
  }
@@ -893,6 +1209,123 @@ export function apply(ctx, options = {}) {
893
1209
  } catch (error) { logHost('models route error: ' + String(error)); return () => {}; }
894
1210
  }, 'mo-image: models route');
895
1211
 
1212
+ ctx.effect(() => {
1213
+ try {
1214
+ return ctx.webServer.register({
1215
+ kind: 'exact', path: '/api/mo-image/detect-protocol',
1216
+ handler: async (req, res) => {
1217
+ try {
1218
+ assertLocalRequest(store, req, true);
1219
+ if (req.method !== 'POST') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
1220
+ const body = await readBody(req);
1221
+ const draft = await draftProviderOf(store, body);
1222
+ const provider = draft.provider;
1223
+ // 「识别协议」现在是**一次问一条**:客户端拿到探测顺序后逐条调用,每发一条就把
1224
+ // 「正在尝试访问 xxx」写出来——进度是真的,不是假轮播。
1225
+ // - 不带 probe:静态能认就给答案(零请求),否则只返回探测顺序;
1226
+ // - 带 probe:只探这一条路径,返回形状与它能证明的协议;命中即停由客户端做。
1227
+ // 失败也把 `status` / `reason` 带回去:401 / 404 / 超时在界面上必须是三句不同的话。
1228
+ const probe = String((body && body.probe) || '').trim();
1229
+ const options = { expected: body && body.expectedProtocol };
1230
+ if (probe) {
1231
+ const step = await probeProtocolPath(provider, probe, options);
1232
+ // 计划外的路径一个请求都不发:这条路由不是任意路径的 GET 代理。
1233
+ if (!step) {
1234
+ return sendJson(res, 400, errorBody(localizedError(new Error('unknown probe path'), 'provider.invalidProbe')));
1235
+ }
1236
+ const answer = {
1237
+ ok: true, done: false, probe: step.probe, hit: step.protocols.length > 0,
1238
+ shape: step.shape, protocols: step.protocols, status: step.status
1239
+ };
1240
+ if (step.reason) answer.reason = step.reason;
1241
+ return sendJson(res, 200, answer);
1242
+ }
1243
+ const start = detectProtocolStart(provider, String((body && body.model) || '').trim(), options);
1244
+ if (!start.done) {
1245
+ const plan = { ok: true, done: false, probes: start.probes };
1246
+ // 「缺 Key」是独立状态:客户端据此把失败提示写成「没有可用的 API Key」,
1247
+ // 而不是跟「地址不对」一起落进笼统的「没认出协议」。
1248
+ if (draft.credential === 'missing') plan.credential = 'missing';
1249
+ return sendJson(res, 200, plan);
1250
+ }
1251
+ const result = start.answer || {};
1252
+ const answer = { ok: true, done: true, protocol: result.protocol, matched: result.matched, probed: result.probed };
1253
+ // 校验结论与探针命中的路径 / 形状:设置页据此写清提示。
1254
+ for (const key of ['probe', 'shape', 'verified', 'suggested', 'suggestedProbe']) {
1255
+ if (result[key] !== undefined) answer[key] = result[key];
1256
+ }
1257
+ // 已知主机带回来的协议级选项(例如方舟的 edit='same'):客户端一次性写对协议 + 选项。
1258
+ if (result.protocolOptions && Object.keys(result.protocolOptions).length) {
1259
+ answer.protocolOptions = result.protocolOptions;
1260
+ }
1261
+ // 鉴权是提供商字段(provider.auth):Azure 这类主机识别出来时一并给出默认形态。
1262
+ if (result.auth) answer.auth = result.auth;
1263
+ return sendJson(res, 200, answer);
1264
+ } catch (error) {
1265
+ return sendJson(res, Number(error && error.status) || 500, errorBody(error));
1266
+ }
1267
+ }
1268
+ });
1269
+ } catch (error) { logHost('detect protocol route error: ' + String(error)); return () => {}; }
1270
+ }, 'mo-image: detect protocol route');
1271
+
1272
+ ctx.effect(() => {
1273
+ try {
1274
+ return ctx.webServer.register({
1275
+ kind: 'exact', path: '/api/mo-image/detect-model-rule',
1276
+ handler: async (req, res) => {
1277
+ try {
1278
+ assertLocalRequest(store, req, true);
1279
+ if (req.method !== 'POST') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
1280
+ const body = await readBody(req);
1281
+ const provider = detectProviderOf(body);
1282
+ const baseUrl = provider.baseUrl;
1283
+ // 地址是必填:没有它,主机指纹无从谈起;没有模型名,整张规则表都无意义。
1284
+ if (!baseUrl) {
1285
+ const error = localizedError(new Error('请先填写 API 地址'), 'provider.missingBaseUrl');
1286
+ error.status = 400;
1287
+ throw error;
1288
+ }
1289
+ // 批量:一键配置一次问完所有模型(客户端没有规则表,也不想为每个模型发一次请求)。
1290
+ // 单模型的老形状保持不动:{ ok, model, size, quality }。
1291
+ const models = detectModelsOf(body && body.models);
1292
+ if (Array.isArray(body && body.models)) {
1293
+ if (!models.length) {
1294
+ // 客户端没有对应的 i18n code,保留原文;返回体仍是 errorBody 那一套形状。
1295
+ const error = new Error('请先填写模型 ID');
1296
+ error.status = 400;
1297
+ throw error;
1298
+ }
1299
+ const rules = Object.create(null);
1300
+ const fields = Object.create(null);
1301
+ const matched = Object.create(null);
1302
+ for (const id of models) {
1303
+ const snapshot = ruleSnapshot(provider, id);
1304
+ rules[id] = snapshot.rule;
1305
+ fields[id] = snapshot.fields;
1306
+ matched[id] = snapshot.matched;
1307
+ }
1308
+ return sendJson(res, 200, { ok: true, models: models, rules: rules, fields: fields, matched: matched });
1309
+ }
1310
+ const model = String((body && body.model) || '').trim();
1311
+ if (!model) {
1312
+ const error = new Error('请先填写模型 ID');
1313
+ error.status = 400;
1314
+ throw error;
1315
+ }
1316
+ const snapshot = ruleSnapshot(provider, model);
1317
+ return sendJson(res, 200, {
1318
+ ok: true, model: model, size: snapshot.rule.size, quality: snapshot.rule.quality,
1319
+ fields: snapshot.fields, matched: snapshot.matched
1320
+ });
1321
+ } catch (error) {
1322
+ return sendJson(res, Number(error && error.status) || 500, errorBody(error));
1323
+ }
1324
+ }
1325
+ });
1326
+ } catch (error) { logHost('detect rule route error: ' + String(error)); return () => {}; }
1327
+ }, 'mo-image: detect rule route');
1328
+
896
1329
  ctx.effect(() => {
897
1330
  try {
898
1331
  return ctx.webServer.register({
@@ -902,15 +1335,12 @@ export function apply(ctx, options = {}) {
902
1335
  assertLocalRequest(store, req, true);
903
1336
  if (req.method !== 'POST') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
904
1337
  const body = await readBody(req);
905
- const config = await readConfig(store);
906
- const providerId = String(body.providerId || '');
907
- const provider = (config.providers || []).find((item) => item && item.id === providerId) || null;
908
- const baseUrl = String(body.baseUrl || (provider && provider.baseUrl) || '').trim().replace(/\/+$/, '');
909
- if (!baseUrl) throw new Error('找不到这个提供商,或它没有填地址。');
910
1338
  const workflow = String(body.workflow || '');
911
1339
  if (!workflow.trim()) throw new Error('工作流是空的。');
912
- const merged = provider ? Object.assign({}, provider, { baseUrl }) : { baseUrl };
913
- const analysis = await analyzeComfyWorkflow({ base: baseUrl, provider: merged, workflow });
1340
+ const { provider } = await draftProviderOf(store, body);
1341
+ const analysis = await analyzeComfyWorkflow({
1342
+ base: provider.baseUrl, provider, workflow, signal: AbortSignal.timeout(20000)
1343
+ });
914
1344
  return sendJson(res, 200, { ok: true, ...analysis });
915
1345
  } catch (error) {
916
1346
  return sendJson(res, 200, { ok: false, error: String(error && error.message ? error.message : error) });
@@ -920,11 +1350,41 @@ export function apply(ctx, options = {}) {
920
1350
  } catch (error) { logHost('analyze route error: ' + String(error)); return () => {}; }
921
1351
  }, 'mo-image: analyze route');
922
1352
 
1353
+ /**
1354
+ * 「解析参数」:把工作流里所有原始值输入摊成候选,给设置页勾选成离散参数表的行。
1355
+ * 和 /comfy/analyze 分开:那个找落点(映射),这个找可挂参数的输入。
1356
+ */
1357
+ ctx.effect(() => {
1358
+ try {
1359
+ return ctx.webServer.register({
1360
+ kind: 'exact', path: '/api/mo-image/comfy/params',
1361
+ handler: async (req, res) => {
1362
+ try {
1363
+ assertLocalRequest(store, req, true);
1364
+ if (req.method !== 'POST') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
1365
+ const body = await readBody(req);
1366
+ const workflow = String(body.workflow || '');
1367
+ if (!workflow.trim()) throw new Error('工作流是空的。');
1368
+ const { provider } = await draftProviderOf(store, body, { requireBaseUrl: false });
1369
+ const listed = await listComfyParams({
1370
+ base: provider.baseUrl, provider, workflow, signal: AbortSignal.timeout(20000)
1371
+ });
1372
+ return sendJson(res, 200, { ok: true, ...listed });
1373
+ } catch (error) {
1374
+ // 解析失败必须是可读的一句话,前端直接显示(和 analyze 同一套约定)。
1375
+ return sendJson(res, 200, { ok: false, error: String(error && error.message ? error.message : error) });
1376
+ }
1377
+ }
1378
+ });
1379
+ } catch (error) { logHost('params route error: ' + String(error)); return () => {}; }
1380
+ }, 'mo-image: comfy params route');
1381
+
923
1382
  ctx.effect(() => {
924
1383
  try {
925
1384
  return ctx.webServer.register({
926
1385
  kind: 'prefix', path: '/api/mo-image/preview',
927
1386
  handler: async (req, res) => {
1387
+ let handle;
928
1388
  try {
929
1389
  const url = new URL(req.url, 'http://127.0.0.1');
930
1390
  if (req.method !== 'GET') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
@@ -936,15 +1396,28 @@ export function apply(ctx, options = {}) {
936
1396
  if (!/^[a-zA-Z0-9._-]+$/.test(name)) return sendJson(res, 400, { ok: false, error: 'bad filename' });
937
1397
  file = path.join(outputDir(), name);
938
1398
  }
939
- if (!existsSync(file)) return sendJson(res, 404, { ok: false, error: 'not found' });
940
- const info = await stat(file);
1399
+ // Where supported, opening a pipe must not wait for a writer before stat can reject it.
1400
+ handle = await open(file, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
1401
+ const info = await handle.stat();
941
1402
  if (!info.isFile()) return sendJson(res, 404, { ok: false, error: 'not found' });
942
1403
  const ext = path.extname(file).toLowerCase();
943
1404
  const type = ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : ext === '.webp' ? 'image/webp' : ext === '.gif' ? 'image/gif' : 'image/png';
944
1405
  res.writeHead(200, { 'Content-Type': type, 'Content-Length': info.size, 'Cache-Control': 'private, max-age=3600' });
945
- res.end(await readFile(file));
1406
+ if (!info.size) return res.end();
1407
+ const stream = handle.createReadStream({ end: info.size - 1 });
1408
+ handle = undefined; // The stream owns the file handle, including on client disconnect.
1409
+ await pipeline(stream, res);
946
1410
  } catch (error) {
947
- return sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) });
1411
+ if (res.destroyed || res.headersSent) {
1412
+ if (!res.destroyed) res.destroy();
1413
+ return;
1414
+ }
1415
+ if (['ENOENT', 'ENOTDIR', 'EISDIR', 'ENXIO'].includes(error?.code)) {
1416
+ return sendJson(res, 404, { ok: false, error: 'not found' });
1417
+ }
1418
+ return sendJson(res, 500, { ok: false, error: 'could not open preview' });
1419
+ } finally {
1420
+ await handle?.close().catch(() => {});
948
1421
  }
949
1422
  }
950
1423
  });
@@ -992,17 +1465,23 @@ export function apply(ctx, options = {}) {
992
1465
 
993
1466
  const renderImage = (_args, value) => {
994
1467
  // 配置交接:这次没有生成图片,整个返回值按 JSON 交给模型(含 settings),不渲染图片行。
995
- if (value && value.needsSettings) return [{ type: 'text', text: JSON.stringify(value) }];
996
- let ref = '';
997
- try { ref = value && value.path ? signPreview(value.path) : ''; } catch (error) { logHost('preview sign error: ' + String(error && error.message ? error.message : error)); }
998
- if (!ref) ref = path.basename((value && value.path) || '');
1468
+ if (value && value.needsSettings) {
1469
+ return [{ type: 'text', text: JSON.stringify({ ...value, settings: settingsForModel(value.settings) }) }];
1470
+ }
1471
+ let destination = value?.workspaceFile ? markdownFilePath(value.path) : '';
1472
+ if (!destination) {
1473
+ let ref = '';
1474
+ try { ref = value?.path ? signPreview(value.path) : ''; } catch (error) { logHost('preview sign error: ' + String(error && error.message ? error.message : error)); }
1475
+ if (!ref) ref = path.basename(value?.path || '');
1476
+ destination = publicOrigin() + '/api/mo-image/preview/' + encodeURIComponent(ref);
1477
+ }
999
1478
  const blocks = [{
1000
1479
  type: 'text',
1001
- text: '![生成图片](' + publicOrigin() + '/api/mo-image/preview/' + encodeURIComponent(ref) + ')'
1480
+ text: '![生成图片](' + destination + ')'
1002
1481
  }];
1003
1482
  if (value && value.note) blocks.push({ type: 'text', text: value.note });
1004
1483
  // 异步任务 id 必须让模型看得见:任务中断时,下一轮才有 resume_job_id 可传。
1005
- if (value && value.jobId) blocks.push({ type: 'text', text: '任务 ID:' + value.jobId + '(中断后可用 resume_job_id 继续)' });
1484
+ if (value && value.jobId) blocks.push({ type: 'text', text: '任务 ID ' + value.jobId });
1006
1485
  return blocks;
1007
1486
  };
1008
1487
  const pendingPresentations = new Map();
@@ -1036,6 +1515,7 @@ export function apply(ctx, options = {}) {
1036
1515
  type: 'object', additionalProperties: false, required: ['path'],
1037
1516
  properties: {
1038
1517
  path: { type: 'string' },
1518
+ workspaceFile: { type: 'boolean' },
1039
1519
  model: { type: 'string' },
1040
1520
  // 成品尺寸与上游原始尺寸:严格模式靠这两个值解释"我缩过 / 上游没按你说的出"。
1041
1521
  size: { type: 'string' },
@@ -1052,7 +1532,7 @@ export function apply(ctx, options = {}) {
1052
1532
  };
1053
1533
  // DSH 的工具契约要求每个工具声明 output { schema, render? };settings
1054
1534
  // 返回值就是给模型看的全部内容:一个最小 JSON(提供商/模型唯一 id + 优化开关 + 一句写法提示)。
1055
- // 配置没变时只回 { unchanged, hint },所以 schema 只把 hint 标成必填。
1535
+ // 全量、增量和未变结果共用同一个 schema。
1056
1536
  const modelsOutput = {
1057
1537
  schema: {
1058
1538
  type: 'object', additionalProperties: false,
@@ -1063,18 +1543,25 @@ export function apply(ctx, options = {}) {
1063
1543
  promptOptimization: { type: 'boolean' },
1064
1544
  canEdit: { type: 'boolean' },
1065
1545
  sizeMode: { type: 'string', enum: ['auto', 'fixed'] },
1546
+ qualityMode: { type: 'string', enum: ['auto', 'fixed', 'unsupported'] },
1547
+ quality: { type: 'string' },
1548
+ qualityOptions: { type: 'array', items: { type: 'string' } },
1066
1549
  strict: { type: 'boolean' },
1067
1550
  size: { type: 'string' },
1068
1551
  control: { type: 'string' },
1069
1552
  sizeOptions: { type: 'array', items: { type: 'string' } },
1070
1553
  hint: { type: 'string' },
1554
+ revision: { type: 'integer' },
1555
+ baseRevision: { type: 'integer' },
1556
+ changes: { type: 'object' },
1557
+ removed: { type: 'array', items: { type: 'string' } },
1071
1558
  unchanged: { type: 'boolean' },
1072
1559
  models: { type: 'array', items: { type: 'string' } },
1073
1560
  editModels: { type: 'array', items: { type: 'string' } },
1074
1561
  params: { type: 'array', items: { type: 'object' } }
1075
1562
  }
1076
1563
  },
1077
- render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }]
1564
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(settingsForModel(value)) }]
1078
1565
  };
1079
1566
 
1080
1567
  // 生图前要读过当前配置,但只在「这个会话还没读过」或「配置真的变了」时才需要重读。
@@ -1085,13 +1572,20 @@ export function apply(ctx, options = {}) {
1085
1572
  // 之后用户再改,签名就变了,下一次调用会重新判断;所以这次锁定不会因为后续修改而失真,
1086
1573
  // 进行中的请求也不受后续修改影响。
1087
1574
  //
1088
- // 没读完就调用生图工具时不报错:把当前配置直接交回去,让模型按它重写提示词再调一次。
1089
- // 一次失败的工具调用对用户就是一条红字,而模型本来就能从结果里把配置读懂。
1575
+ // 未读或配置过期时把当前配置交回去,让模型按需调整后再调用。
1090
1576
  const sessionOf = (exec) => (exec && exec.agent && exec.agent.session) || null;
1577
+ // DSH 为同一步的工具调用传同一个 toolSet。兄弟调用还看不到这一步刚返回的配置。
1578
+ const settingsByStep = new WeakMap();
1579
+ const recordStepRead = (exec, signature) => {
1580
+ if (exec?.toolSet && typeof exec.toolSet === 'object') {
1581
+ settingsByStep.set(exec.toolSet, signature);
1582
+ }
1583
+ };
1091
1584
  const settingsHandoff = (exec, mode, snapshot) => {
1092
1585
  const session = sessionOf(exec);
1093
1586
  if (!session) return null; // 没有会话上下文(脚本调用)时无从比对,不拦。
1094
- const payload = settingsPayload(activeImageState(store, snapshot));
1587
+ const current = settingsView(activeImageState(store, snapshot));
1588
+ const { payload, signature } = current;
1095
1589
  // 没有选模型不是「配置过期」问题:不记成已读,也别让模型重试到 generate() 里去撞红字。
1096
1590
  if (!payload.model) {
1097
1591
  return {
@@ -1104,18 +1598,22 @@ export function apply(ctx, options = {}) {
1104
1598
  // 模型不支持改图时不要用交接盖住它:让 edit() 抛那条带模型名、能被本地化的能力错误。
1105
1599
  // 用交接会变成“重写提示词再调用”,重试还是同一个错误,只是多绕一轮。
1106
1600
  if (mode === 'edit' && payload.canEdit === false) return null;
1107
- const signature = settingsSignature(payload);
1108
- const state = settingsState(session, signature);
1109
- if (state === 'fresh') return null;
1110
- rememberSettings(session, signature);
1601
+ if (settingsByStep.get(exec.toolSet) === signature) {
1602
+ return { path: '', needsSettings: true, note: '这次没有生成。使用同一步返回的配置结果,在下一步重新调用。' };
1603
+ }
1604
+ const { state, reply } = settingsMemory.read(session, current, { step: exec.toolSet, onlyIfNeeded: true });
1605
+ if (!reply) return null;
1606
+ recordStepRead(exec, signature);
1111
1607
  return {
1112
1608
  path: '',
1113
1609
  needsSettings: true,
1114
- settings: payload,
1610
+ settings: reply,
1115
1611
  note: (state === 'stale'
1116
1612
  ? '配置在你上次读取后改过了,这次没有生成。'
1117
- : '本会话还没读过生图配置,这次没有生成。')
1118
- + '按 settings 里的模型写法和提示词优化状态重写提示词,再调用一次本工具。'
1613
+ : state === 'refresh' ? '已重新返回完整配置,这次没有生成。' : '本会话还没读过生图配置,这次没有生成。')
1614
+ + (reply.changes ? '按变更更新已有配置;找不到对应的基线时用 refresh:true 重读。' : '使用这份 settings。')
1615
+ + (payload.promptOptimization ? '沿用上下文里仍适用的写法和成稿,只调整受影响的部分。' : '提示词沿用用户原话。')
1616
+ + '有当前配置后,用新的工具调用提交。'
1119
1617
  };
1120
1618
  };
1121
1619
 
@@ -1134,30 +1632,48 @@ export function apply(ctx, options = {}) {
1134
1632
  if (!callId) return '';
1135
1633
  return tool + ':' + sessionIdOf(sessionOf(exec)) + ':' + callId;
1136
1634
  };
1137
- /** 有效请求摘要:参数 + 配置快照 + 提供商地址。键顺序必须稳定。 */
1635
+ const configDigests = new WeakMap();
1636
+ /** 有效请求摘要:参数 + 配置快照。配置对象换代时重新计算。 */
1138
1637
  const invocationFingerprint = (tool, args, snapshot) => {
1139
- const state = activeImageState(store, snapshot);
1140
1638
  const input = {
1141
1639
  prompt: String((args && args.prompt) || ''),
1142
1640
  negative_prompt: String((args && args.negative_prompt) || ''),
1143
1641
  images: Array.isArray(args && args.images) ? args.images.map((item) => String(item || '')) : [],
1144
1642
  size: String((args && args.size) || ''),
1643
+ quality: resolveQuality(snapshot.defaults) === 'auto' ? String(args?.quality || '').trim().toLowerCase() : '',
1145
1644
  model: String((args && args.model) || ''),
1146
1645
  provider: String((args && args.provider) || ''),
1147
1646
  params: args && args.params && typeof args.params === 'object' ? args.params : null
1148
1647
  };
1149
- const providerPrint = state
1150
- ? [state.provider.id, state.provider.baseUrl, state.provider.apiKeyEnv || '']
1151
- : null;
1152
- return stableStringify([
1153
- tool,
1154
- state ? settingsSignature(settingsPayload(state)) : '',
1155
- providerPrint,
1156
- input
1157
- ]);
1648
+ let configDigest = configDigests.get(snapshot);
1649
+ if (!configDigest) {
1650
+ const provider = snapshot.providers.find((item) => item.id === snapshot.active.providerId);
1651
+ configDigest = createHash('sha256')
1652
+ .update(stableStringify([snapshot.active, snapshot.defaults, provider || null]))
1653
+ .digest('hex');
1654
+ configDigests.set(snapshot, configDigest);
1655
+ }
1656
+ return createHash('sha256').update(stableStringify([tool, configDigest, input])).digest('hex');
1657
+ };
1658
+ const resume = async (args, exec, config) => {
1659
+ const id = String(args.resume_job_id).trim();
1660
+ const cwd = sessionCwd(ctx, exec);
1661
+ let pending = resumeInflight.get(id);
1662
+ if (!pending) {
1663
+ pending = resumeImageJob(args, exec, store, config, imageQueue, jobJournal, cwd).finally(() => resumeInflight.delete(id));
1664
+ resumeInflight.set(id, pending);
1665
+ }
1666
+ const result = await pending;
1667
+ presentImage(exec, result);
1668
+ return imagePayload(result, cwd);
1158
1669
  };
1159
- const imagePayload = (result) => {
1670
+ const imagePayload = (result, cwd) => {
1160
1671
  const payload = { path: result.file, model: String(result.model || '') };
1672
+ let limit;
1673
+ try { limit = ctx.get?.('attachments')?.imageLimits?.maxImageBytes; } catch (_error) { /* Optional host service. */ }
1674
+ if (belongsToWorkspace(cwd, result.file) && (!Number.isFinite(limit) || result.bytes <= limit)) {
1675
+ payload.workspaceFile = true;
1676
+ }
1161
1677
  if (result.size) payload.size = String(result.size);
1162
1678
  if (result.generated) payload.generated = String(result.generated);
1163
1679
  if (result.original) payload.original = String(result.original);
@@ -1166,30 +1682,58 @@ export function apply(ctx, options = {}) {
1166
1682
  if (result.jobId) payload.jobId = String(result.jobId);
1167
1683
  return payload;
1168
1684
  };
1685
+ const executeImageTool = async (kind, handler, args, exec) => {
1686
+ // 交接和请求使用同一份快照。恢复任务独立于当前选择器配置。
1687
+ const config = await readConfig(store);
1688
+ if (String(args?.resume_job_id || '').trim()) return resume(args, exec, config);
1689
+ const run = async () => {
1690
+ const handoff = settingsHandoff(exec, kind, config);
1691
+ if (handoff) return handoff;
1692
+ const cwd = sessionCwd(ctx, exec);
1693
+ const result = await handler(args, exec, store, config, imageQueue, jobJournal, cwd);
1694
+ presentImage(exec, result);
1695
+ return imagePayload(result, cwd);
1696
+ };
1697
+ // 交接结果也要按 callId 去重,否则重放同一次交接可能直接提交生图。
1698
+ const key = invocationKey(exec, kind);
1699
+ if (!key) return run();
1700
+ const outcome = await callRegistry.run(key, invocationFingerprint(kind, args, config), run);
1701
+ return outcome.value;
1702
+ };
1703
+ const deliveryDescription = ' On 生图配置不匹配(未提交), call mo_image_settings with refresh:true and correct the arguments for one new call within the user’s choices. If it still fails, report the error. Report other failures verbatim. Never switch the user’s model, provider, or tool. Reply with the returned Markdown image line. Never judge or describe the image, and open it only when asked.';
1169
1704
 
1170
1705
  // 每个工具单独兜底:一个工具的契约不满足时,不会连带其它工具一起注册失败。
1171
1706
  try {
1172
1707
  ctx.tools.register({
1173
1708
  name: 'mo_image_settings',
1174
- description: 'Read the current image settings: provider, model, optimization state, per-model dialect. The <mo-image-prompt> 配置状态 line decides: 还没读过/刚改过 → call this before mo_image_generate/mo_image_edit (they hand back settings, not images); 一致 → skip. An unchanged read answers {"unchanged":true}; refresh:true re-reads after compaction.',
1709
+ description: 'Read image settings before first generation or editing (配置状态). After that, let the image tool return updates via needsSettings, including periodic and post-compaction full snapshots. Apply changes to baseRevision, delete keys in removed, and keep other values. Arrays replace whole fields. Use refresh:true when a required baseline is missing or after a local settings mismatch. unchanged:true reuses the prior result. In Model Auto, editModelIndexes gives editable indexes in models (zero-based), or "all". Pass model for that candidate’s size, quality, edit support and exposed parameters.',
1175
1710
  parameters: {
1176
1711
  type: 'object', additionalProperties: false,
1177
1712
  properties: {
1178
- refresh: { type: 'boolean', description: 'Re-read the full payload after compaction, or when the earlier read is no longer in context.' }
1713
+ refresh: { type: 'boolean', description: 'Return the full catalog or candidate if the earlier configuration is unavailable.' },
1714
+ model: { type: 'string', description: 'Exact ID from models, or the current selected model. Omit to read the current settings/catalog.' }
1179
1715
  }
1180
1716
  },
1181
1717
  output: modelsOutput,
1182
1718
  timeoutMs: 15000,
1183
1719
  async execute(args, exec) {
1184
- const payload = settingsPayload(activeImageState(store));
1185
- const signature = settingsSignature(payload);
1720
+ const current = activeImageState(store);
1186
1721
  const session = sessionOf(exec);
1187
- const state = settingsState(session, signature);
1188
- rememberSettings(session, signature);
1189
- if (state === 'fresh' && !(args && args.refresh === true)) {
1190
- return { unchanged: true, hint: '配置没变:沿用上次读到的模型和写法,直接生图/改图;这份配置已经不在上下文里时传 refresh:true 重读。' };
1722
+ const requested = String(args?.model || '').trim();
1723
+ const readOptions = { step: exec?.toolSet, refresh: args?.refresh === true };
1724
+ if (requested) {
1725
+ const allowed = current && (current.model === 'auto'
1726
+ ? current.models.includes(requested)
1727
+ : current.model === requested);
1728
+ if (!allowed) return { hint: '该模型不在当前可选范围内。请从当前设置的模型目录里选择。' };
1729
+ const detail = modelImageState(current.provider, requested, current.defaults, current.editModels.includes(requested));
1730
+ const candidate = settingsSnapshot(settingsPayload(detail, { includeParamDetails: true }));
1731
+ return settingsMemory.read(session, candidate, { ...readOptions, candidate: true }).reply;
1191
1732
  }
1192
- return payload;
1733
+ const view = settingsView(current);
1734
+ const { reply } = settingsMemory.read(session, view, readOptions);
1735
+ if (!reply.unchanged) recordStepRead(exec, view.signature);
1736
+ return reply;
1193
1737
  }
1194
1738
  });
1195
1739
  } catch (error) { logHost('settings tool register error: ' + String(error)); }
@@ -1197,13 +1741,14 @@ export function apply(ctx, options = {}) {
1197
1741
  try {
1198
1742
  ctx.tools.register({
1199
1743
  name: 'mo_image_generate',
1200
- description: 'Generate a new image with the active model. If 配置状态 says the settings read is missing or stale, call mo_image_settings first: this tool then returns {"path":"","needsSettings":true,"settings":…} and generates nothing. With current settings: On → write the prompt in the model\'s dialect and pick fitting params; Off → pass the user\'s wording unchanged. Model and quality come from the picker, so leave model out; pass size only when settings report sizeMode "auto" and the user asked for it; in Auto mode pass one id from the list. Load the mo-image-generation skill once; when optimization is Off use its invocation guidance only. Reply with the returned Markdown image line. Output is final: never judge/describe the image, never switch provider/model/tool, and do not open it unless asked. On failure report the error verbatim and at most ask whether to switch.',
1744
+ description: 'Generate with the active model. A needsSettings result makes no image; apply its settings as described by mo_image_settings before making a new call. On: complete rough prompts in the model\'s dialect, reusing suitable drafts and preserving exact wording when requested. Off: use the user\'s wording. Load the mo-image-generation skill only for needed guidance missing from context. Pass model only in Model Auto. In Size Auto, choose size if useful; in Quality Auto, use qualityOptions. Fixed selections take precedence.' + deliveryDescription,
1201
1745
  parameters: {
1202
1746
  type: 'object', additionalProperties: false,
1203
1747
  properties: {
1204
- prompt: { type: 'string', description: 'Final prompt in the model\'s dialect (On) or the user\'s wording (Off). Cover subject, action, environment, style, lighting, composition, constraints; quote in-image text exactly.' },
1748
+ prompt: { type: 'string', description: 'Final prompt. When optimizing, add relevant subject, action, environment, style, lighting or composition detail. Preserve constraints and quote in-image text exactly.' },
1205
1749
  negative_prompt: { type: 'string', description: 'Optional; only for models that support it. Artifacts/elements to avoid.' },
1206
- size: { type: 'string', description: 'Optional shape like "1024x1536"; only when settings report sizeMode "auto" and the user asked; ignored when the picker pins the size.' },
1750
+ size: { type: 'string', description: 'Optional shape like "1024x1536" or an accepted aspect or tier; only honored if sizeMode is "auto".' },
1751
+ quality: { type: 'string', description: 'Optional level from qualityOptions. Only honored if qualityMode is "auto".' },
1207
1752
  model: { type: 'string', description: 'Optional outside Auto mode: the picker\'s model is used. In Auto mode pass one id from the active list; other values are rejected — never switch models.' },
1208
1753
  provider: { type: 'string', description: 'Optional. The user-selected provider; validated against the picker, never switched.' },
1209
1754
  params: {
@@ -1214,43 +1759,23 @@ export function apply(ctx, options = {}) {
1214
1759
  }
1215
1760
  },
1216
1761
  output, timeoutMs: 360000,
1217
- async execute(args, exec) {
1218
- // 一次工具调用只读一次配置:交接判断和真正的请求共用同一份快照。
1219
- const config = await readConfig(store);
1220
- // 恢复入口不重新提交,也不要求先读 settings。
1221
- if (String((args && args.resume_job_id) || '').trim()) {
1222
- const result = await resumeImageJob(args, exec, store, config, imageQueue, jobJournal);
1223
- presentImage(exec, result);
1224
- return imagePayload(result);
1225
- }
1226
- const handoff = settingsHandoff(exec, undefined, config);
1227
- if (handoff) return handoff;
1228
- const run = async () => {
1229
- const result = await generate(args, exec, store, config, imageQueue, jobJournal);
1230
- presentImage(exec, result);
1231
- return imagePayload(result);
1232
- };
1233
- const key = invocationKey(exec, 'generate');
1234
- // 脚本入口没有稳定 callId:不去重,比猜一个身份更安全。
1235
- if (!key) return run();
1236
- const outcome = await callRegistry.run(key, invocationFingerprint('generate', args, config), run);
1237
- return outcome.value;
1238
- }
1762
+ execute: (args, exec) => executeImageTool('generate', generate, args, exec)
1239
1763
  });
1240
1764
  } catch (error) { logHost('generate tool register error: ' + String(error)); }
1241
1765
 
1242
1766
  try {
1243
1767
  ctx.tools.register({
1244
1768
  name: 'mo_image_edit',
1245
- description: 'Edit or refine existing images. If 配置状态 says the settings read is missing or stale, call mo_image_settings first: this tool then returns needsSettings and edits nothing. With current settings: optimization is Off → use the user\'s original edit wording unchanged; On → pick fitting params and say what changed. Model and quality come from the picker; pass size only when settings report sizeMode "auto"; in Auto mode omit model or pass one id from editModels. Name references 图1/图2. For a full redo that must not copy the current image, use mo_image_generate. Load mo-image-editing skill once; when optimization is Off use its invocation guidance only. Reply with the returned Markdown image line. Output is final: never judge/describe the image, never switch provider/model/tool, and do not open it unless asked. On failure report the error verbatim and at most ask whether to switch.',
1769
+ description: 'Edit existing images. A needsSettings result edits nothing; apply its settings as described by mo_image_settings before making a new call. On: state the requested changes and what to preserve in the prompt, reusing suitable wording. Off: use the user\'s wording. Load the mo-image-editing skill only for needed guidance missing from context. Respect fixed model, size and quality. Choose size or quality only in its Auto mode. In Model Auto omit model or choose using editModelIndexes. Name references 图1/图2 in order. For a redo without a reference use mo_image_generate.' + deliveryDescription,
1246
1770
  parameters: {
1247
1771
  type: 'object', additionalProperties: false,
1248
1772
  properties: {
1249
1773
  prompt: { type: 'string', description: 'Final edit prompt: name each reference (图1/图2); state exactly what changes and that everything else stays.' },
1250
1774
  images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute local paths or http(s) URLs, in 图1/图2 order.' },
1251
1775
  negative_prompt: { type: 'string', description: 'Optional; only for models that support it. Artifacts/elements to avoid.' },
1252
- size: { type: 'string', description: 'Optional shape like "1024x1536"; only when settings report sizeMode "auto" and the user asked; ignored when the picker pins the size.' },
1253
- model: { type: 'string', description: 'Optional outside Auto mode. In Auto mode omit it (first edit-capable model) or pass one id from editModels; non-editing models are rejected.' },
1776
+ size: { type: 'string', description: 'Optional shape like "1024x1536" or an accepted aspect or tier; only honored if sizeMode is "auto".' },
1777
+ quality: { type: 'string', description: 'Optional level from qualityOptions. Only honored if qualityMode is "auto".' },
1778
+ model: { type: 'string', description: 'Optional outside Auto mode. In Auto mode omit it (first edit-capable model) or choose an editable ID using editModelIndexes.' },
1254
1779
  provider: { type: 'string', description: 'Optional. The user-selected provider; validated against the picker, never switched.' },
1255
1780
  params: {
1256
1781
  type: 'object', additionalProperties: true,
@@ -1260,26 +1785,7 @@ export function apply(ctx, options = {}) {
1260
1785
  }
1261
1786
  },
1262
1787
  output, timeoutMs: 360000,
1263
- async execute(args, exec) {
1264
- // 同 generate:交接判断与请求共用一份配置快照。
1265
- const config = await readConfig(store);
1266
- if (String((args && args.resume_job_id) || '').trim()) {
1267
- const result = await resumeImageJob(args, exec, store, config, imageQueue, jobJournal);
1268
- presentImage(exec, result);
1269
- return imagePayload(result);
1270
- }
1271
- const handoff = settingsHandoff(exec, 'edit', config);
1272
- if (handoff) return handoff;
1273
- const run = async () => {
1274
- const result = await edit(args, exec, store, config, imageQueue, jobJournal);
1275
- presentImage(exec, result);
1276
- return imagePayload(result);
1277
- };
1278
- const key = invocationKey(exec, 'edit');
1279
- if (!key) return run();
1280
- const outcome = await callRegistry.run(key, invocationFingerprint('edit', args, config), run);
1281
- return outcome.value;
1282
- }
1788
+ execute: (args, exec) => executeImageTool('edit', edit, args, exec)
1283
1789
  });
1284
1790
  } catch (error) { logHost('edit tool register error: ' + String(error)); }
1285
1791
  }