dsh-mo-image 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -7,19 +7,42 @@ import { fileURLToPath } from 'node:url';
7
7
  import { lookup } from 'node:dns/promises';
8
8
  import { isIP } from 'node:net';
9
9
  import {
10
- resolveAdapter, describeAdapter, fitSize, escalateSize,
10
+ resolveAdapter, describeAdapter, fitSize, sizePolicyFor, sizeSpecFor,
11
+ parseSize, nearestAspect, nearestTier, sizeForAspect,
11
12
  qualityForAdapter, qualityOptionsFor, filterImageModels,
12
- prepareGenerate, prepareEdit, prepareAsync, pollUrlFor, pollHeaders,
13
- readTaskId, readTaskState, decodeImagePayload, classifyFailure,
14
- fetchImageUrl, resizeTo, adapterBase, readResponseBytes, looksLikeImage, sniffType,
15
- listProviderModelEntries, adapterManifest, localPresetManifest, providerPresetManifest, MAX_IMAGE_BYTES,
16
- adapterSupportsKind
13
+ readResponseBytes, looksLikeImage, sniffType,
14
+ listProviderModelEntries, adapterManifest, localPresetManifest, providerPresetManifest,
15
+ analyzeComfyWorkflow, A1111_PARAMS
17
16
  } from './adapters.js';
18
- import { promptSectionText, resolvePromptProfile, settingsPayload } from './prompt-profiles.js';
17
+ import {
18
+ applySizeStitch, finalizeImage, finalizeImageAsync, saveImage, saveSidecar, sizeLabel, stitchSizePrompt
19
+ } from './image-service.js';
20
+ 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';
19
23
  import { request, setNetworkLogger } from './net.js';
20
24
  import { configWriteReason } from './config-guard.js';
21
25
  import { localizedError, errorBody } from './localized-error.js';
22
26
  import { createUpdateService } from './update-service.js';
27
+ import { createImageQueue } from './image-queue.js';
28
+ import { createCallRegistry, createJobJournal } from './image-jobs.js';
29
+ import {
30
+ attachFailure, callAsyncImage, callImageApi, followTask,
31
+ setImageExecutionLogger, stableStringify, TOTAL_BUDGET_MS
32
+ } from './image-execution.js';
33
+ export { callImageApi };
34
+ import {
35
+ activeImageState, assertLocalRequest, canUseCredentials, capabilityManifest, createConfigStore,
36
+ describeImageStatus as describeImageStatusBase, normalizeConfig, normalizeDefaults,
37
+ normalizeModelOptions, publicConfig, readConfig, readConfigSync, resolveProviderCredential,
38
+ resolveQuality, resolveSizeRequest, saveConfigWithCredentials
39
+ } from './config-store.js';
40
+ export {
41
+ capabilityManifest, normalizeConfig, normalizeDefaults, normalizeModelOptions,
42
+ resolveSizeRequest, workflowParamsOf
43
+ } from './config-store.js';
44
+ import { MAPPING_KEYS, DEFAULT_EXPOSED } from './comfy-workflow.js';
45
+ import { STATUS_CONTRACT, editCapableModels, pickAutoEditModel } from './status.js';
23
46
 
24
47
  const PLUGIN = 'dsh-mo-image';
25
48
  function dshHome() {
@@ -45,8 +68,12 @@ function pluginVersion() {
45
68
  return '0.0.0';
46
69
  }
47
70
  }
71
+ /** 配置快照本身不知道插件版本;状态服务在这一层把版本补上。 */
72
+ function describeImageStatus(store) {
73
+ return describeImageStatusBase(store, pluginVersion());
74
+ }
48
75
  const UPDATE_CHECK_TTL_MS = 12 * 60 * 60 * 1000;
49
- const MAX_BODY = 2 * 1024 * 1024;
76
+ const MAX_BODY = 8 * 1024 * 1024;
50
77
  const MAX_REF_BYTES = 15 * 1024 * 1024;
51
78
  const MAX_REF_TOTAL = 48 * 1024 * 1024;
52
79
  const MAX_JSON_EDIT_TOTAL = 10 * 1024 * 1024;
@@ -107,419 +134,6 @@ function resolvePreviewToken(token) {
107
134
  return value && typeof value.p === 'string' && path.isAbsolute(value.p) ? value.p : '';
108
135
  } catch (_error) { return ''; }
109
136
  }
110
- function emptyConfig() {
111
- return {
112
- version: 1, providers: [], active: { providerId: '', model: '' },
113
- defaults: { quality: 'high', auto: true, width: 1024, height: 1024, promptOptimization: true }
114
- };
115
- }
116
- /** 质量值由适配器的 options 决定;这里只保留旧配置里的合法字符串,具体对齐交给 adapter。 */
117
- const QUALITY_VALUES = new Set(['off', 'low', 'medium', 'high', 'max', 'auto', 'standard', 'hd', 'default', 'quality', 'turbo']);
118
- function normalizeQuality(value) {
119
- const raw = String(value || '').trim().toLowerCase();
120
- if (raw === 'xhigh') return 'max';
121
- return QUALITY_VALUES.has(raw) ? raw : 'high';
122
- }
123
- function normalizeDefaults(raw) {
124
- const source = raw && typeof raw === 'object' ? raw : {};
125
- const side = (value, fallback) => {
126
- const number = Number(value);
127
- if (!Number.isFinite(number) || number <= 0) return fallback;
128
- return Math.min(4096, Math.max(64, Math.round(number)));
129
- };
130
- let width = side(source.width, 0);
131
- let height = side(source.height, 0);
132
- if (!width || !height) {
133
- // 兼容上一版的 { size: "1024x1024" }
134
- const legacy = /^(\d{2,5})x(\d{2,5})$/.exec(String(source.size || '').trim().toLowerCase().replace(/[×*]/g, 'x'));
135
- if (legacy) { width = side(legacy[1], 1024); height = side(legacy[2], 1024); }
136
- }
137
- return {
138
- quality: normalizeQuality(source.quality),
139
- auto: source.auto === undefined ? true : !!source.auto,
140
- width: width || 1024,
141
- height: height || 1024,
142
- promptOptimization: source.promptOptimization === undefined ? true : !!source.promptOptimization
143
- };
144
- }
145
- /** 质量、尺寸都只取选择器默认值;工具不再接受模型传入的参数。 */
146
- function resolveQuality(defaults) {
147
- return normalizeQuality(defaults && defaults.quality);
148
- }
149
- function resolveSizeArg(defaults) {
150
- if (defaults && defaults.auto === false) return (defaults.width || 1024) + 'x' + (defaults.height || 1024);
151
- return 'none';
152
- }
153
- /** 每个模型的可选配置(目前只有自定义工作流),只保留仍存在的模型,限制体积。 */
154
- const MODEL_WORKFLOW_MAX = 200000;
155
- export function normalizeModelOptions(raw, models) {
156
- const out = {};
157
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
158
- const allowed = new Set(Array.isArray(models) ? models : []);
159
- for (const model of Object.keys(raw)) {
160
- if (!allowed.has(model)) continue;
161
- const entry = raw[model];
162
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
163
- const workflow = typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
164
- if (!workflow || workflow.length > MODEL_WORKFLOW_MAX) continue;
165
- out[model] = { workflow };
166
- }
167
- return out;
168
- }
169
-
170
- export function normalizeConfig(raw) {
171
- const out = emptyConfig();
172
- if (!raw || typeof raw !== 'object') return out;
173
- const providers = Array.isArray(raw.providers) ? raw.providers : [];
174
- for (const item of providers) {
175
- if (!item || typeof item !== 'object') continue;
176
- const models = Array.from(new Set((Array.isArray(item.models) ? item.models : [])
177
- .map((m) => String(m || '').trim()).filter(Boolean)));
178
- const names = {};
179
- if (item.names && typeof item.names === 'object') for (const model of models) if (typeof item.names[model] === 'string') names[model] = item.names[model];
180
- const modelOptions = normalizeModelOptions(item.modelOptions, models);
181
- const key = String(item.key || '');
182
- const provider = {
183
- id: String(item.id || randomUUID()), name: String(item.name || ''),
184
- baseUrl: String(item.baseUrl || '').replace(/\/+$/, ''),
185
- apiKeyEnv: validKeyRef(item.apiKeyEnv),
186
- optionalKey: !!item.optionalKey,
187
- protocol: String(item.protocol || 'openai-images'), adapter: String(item.adapter || ''), models, names
188
- };
189
- // 自定义工作流只有 ComfyUI 适配器会读;别的提供商留着也没用,直接丢弃。
190
- if (provider.adapter === 'comfyui' && Object.keys(modelOptions).length > 0) provider.modelOptions = modelOptions;
191
- if (key) provider.key = key;
192
- out.providers.push(provider);
193
- }
194
- const wanted = raw.active && typeof raw.active === 'object' ? raw.active : {};
195
- const provider = out.providers.find((p) => p.id === wanted.providerId);
196
- // "auto" 是选择器里的特殊行:允许对话模型在提供商列表内自选模型。
197
- const wantedModel = String(wanted.model || '').trim();
198
- const keepModel = wantedModel === 'auto' || (provider && provider.models.includes(wantedModel));
199
- out.active = { providerId: provider ? provider.id : '', model: keepModel ? wantedModel : '' };
200
- out.defaults = normalizeDefaults(raw.defaults);
201
- return out;
202
- }
203
- /** DSH 凭据库(ctx.credentials)里的引用名;只允许我们自己的 MO_IMAGE_ 命名空间。 */
204
- const KEY_REF_PREFIX = 'MO_IMAGE_';
205
- const KEY_REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
206
- function createConfigStore(options) {
207
- return {
208
- configFile: options.configFile,
209
- ensureDirs: options.ensureDirs,
210
- logHost: options.logHost,
211
- credentialsAccessor: options.credentialsAccessor,
212
- cache: null,
213
- stamp: '',
214
- webOriginHost: '',
215
- keyMigration: null,
216
- writeQueue: Promise.resolve()
217
- };
218
- }
219
- function credentialsService(store) {
220
- if (!store || typeof store.credentialsAccessor !== 'function') return undefined;
221
- try { return store.credentialsAccessor(); } catch (_error) { return undefined; }
222
- }
223
- function validKeyRef(value) {
224
- const ref = String(value || '').trim();
225
- return KEY_REF_PATTERN.test(ref) && ref.startsWith(KEY_REF_PREFIX) ? ref : '';
226
- }
227
- /** 按 provider id 生成稳定的环境变量名,例如 MO_IMAGE_P_ABC_API_KEY。 */
228
- function deriveKeyRef(id, used) {
229
- const stem = String(id || 'provider').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'PROVIDER';
230
- const base = KEY_REF_PREFIX + stem + '_API_KEY';
231
- let ref = base;
232
- for (let n = 2; used && used.has(ref); n++) ref = base.replace(/_API_KEY$/, '_' + n + '_API_KEY');
233
- return ref;
234
- }
235
- function hasLegacyKeys(config) {
236
- return (config.providers || []).some((provider) => provider.key || !validKeyRef(provider.apiKeyEnv));
237
- }
238
- /** describe() 的 configured 也可能来自环境变量;只有不是 env fallback 才算已存进凭据库。 */
239
- function credentialIsStored(info) {
240
- if (!info || !info.configured) return false;
241
- const source = String(info.source || '');
242
- return source !== 'env' && source !== 'project-env' && source !== 'user-env';
243
- }
244
-
245
- function requestHostName(req) {
246
- const raw = String((req.headers && req.headers.host) || '').trim().toLowerCase();
247
- if (!raw) return '';
248
- const withoutPort = raw.replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
249
- return withoutPort;
250
- }
251
- /**
252
- * 配置写接口是本插件自己的本地 HTTP 路由,不走 DSH 的 remote 权限层,所以
253
- * 至少挡掉跨站浏览器请求和 DNS rebinding:Host 必须是回环、IP 字面量或
254
- * DSH_WEB_URL 公布的域名;Origin 必须同源;POST 必须是 application/json。
255
- * 同一 OS 用户的进程本来就能读凭据文件,这里不是对抗同 UID 进程的边界。
256
- */
257
- function assertLocalRequest(store, req, write) {
258
- const hostName = requestHostName(req);
259
- if (!hostName) {
260
- const error = new Error('missing Host header'); error.status = 403; throw error;
261
- }
262
- const allowed = new Set(['127.0.0.1', 'localhost', '::1']);
263
- for (const value of [process.env.DSH_WEB_URL, store && store.webOriginHost]) {
264
- try {
265
- const parsed = new URL(String(value || ''));
266
- if (parsed.hostname) allowed.add(parsed.hostname.toLowerCase());
267
- } catch (_error) { /* ignore */ }
268
- }
269
- if (!allowed.has(hostName) && isIP(hostName) === 0) {
270
- const error = new Error('unexpected Host header'); error.status = 403; throw error;
271
- }
272
- const origin = req.headers && req.headers.origin;
273
- if (origin !== undefined) {
274
- let originUrl;
275
- try { originUrl = new URL(String(origin)); } catch (_error) {
276
- const error = new Error('invalid Origin'); error.status = 403; throw error;
277
- }
278
- const hostHeader = String(req.headers.host || '').toLowerCase();
279
- if (originUrl.host.toLowerCase() !== hostHeader) {
280
- const error = new Error('cross-origin request rejected'); error.status = 403; throw error;
281
- }
282
- }
283
- const site = req.headers && req.headers['sec-fetch-site'];
284
- if (site && site !== 'same-origin' && site !== 'none') {
285
- const error = new Error('cross-site request rejected'); error.status = 403; throw error;
286
- }
287
- if (write) {
288
- const type = String((req.headers && req.headers['content-type']) || '').toLowerCase();
289
- if (!type.startsWith('application/json')) {
290
- const error = new Error('content-type must be application/json'); error.status = 415; throw error;
291
- }
292
- }
293
- }
294
- /** 系统提示词节是同步渲染的,这里用 mtime 缓存一份配置副本。 */
295
- function rememberConfig(store, config) {
296
- store.cache = config;
297
- store.stamp = '';
298
- }
299
- function readConfigSync(store) {
300
- try {
301
- const info = statSync(store.configFile);
302
- const stamp = info.mtimeMs + ':' + info.size;
303
- if (!store.cache || stamp !== store.stamp) {
304
- store.cache = normalizeConfig(JSON.parse(readFileSync(store.configFile, 'utf8')));
305
- store.stamp = stamp;
306
- }
307
- } catch (_error) {
308
- if (!store.cache) store.cache = emptyConfig();
309
- }
310
- return store.cache;
311
- }
312
- /** 当前选中的生图模型;编辑也用同一个(严格模式,不做任何回退)。 */
313
- function activeImageState(store) {
314
- const config = readConfigSync(store);
315
- const provider = (config.providers || []).find((item) => item.id === config.active.providerId);
316
- const model = String((config.active && config.active.model) || '').trim();
317
- if (!provider || !model) return null;
318
- let adapter = null;
319
- try { adapter = resolveAdapter(provider, model); } catch (_error) { adapter = null; }
320
- return {
321
- provider, model, adapter, models: provider.models || [],
322
- editModel: model, editAdapter: adapter,
323
- promptOptimization: config.defaults.promptOptimization !== false, defaults: config.defaults
324
- };
325
- }
326
- function canUseCredentials(store) {
327
- const credentials = credentialsService(store);
328
- return !!(credentials && typeof credentials.describe === 'function' && typeof credentials.resolve === 'function' && typeof credentials.set === 'function');
329
- }
330
- /** 浏览器只拿 hasKey/keySource,永远拿不到明文密钥。 */
331
- async function publicConfig(store, config) {
332
- const credentials = credentialsService(store);
333
- const providers = await Promise.all((config.providers || []).map(async (provider) => {
334
- const copy = Object.assign({}, provider);
335
- delete copy.key;
336
- const ref = validKeyRef(provider.apiKeyEnv);
337
- let hasKey = false;
338
- let keySource = '';
339
- if (ref && credentials && typeof credentials.describe === 'function') {
340
- try {
341
- const info = await credentials.describe(ref);
342
- hasKey = !!info.configured;
343
- keySource = info.source || '';
344
- } catch (error) { store.logHost('credential describe failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
345
- }
346
- if (!hasKey && ref && process.env[ref]) { hasKey = true; keySource = 'env'; }
347
- if (!hasKey && provider.key) { hasKey = true; keySource = 'config'; }
348
- return Object.assign(copy, { hasKey: hasKey, keySource: keySource });
349
- }));
350
- return Object.assign({}, config, { providers: providers });
351
- }
352
- /** 选择器用的模型能力表:目前先下发每个模型可用的质量档位。 */
353
- function capabilityManifest(config) {
354
- return (config.providers || []).map((provider) => ({
355
- providerId: provider.id,
356
- models: (provider.models || []).map((model) => {
357
- let quality = null;
358
- try { quality = qualityOptionsFor(resolveAdapter(provider, model), model); } catch (_error) { quality = null; }
359
- return { model: model, quality: quality };
360
- })
361
- }));
362
- }
363
- /**
364
- * 把旧版 config.json 里的明文 key 迁到 DSH 凭据库,并在配置里只留下 apiKeyEnv 引用。
365
- * 凭据服务不存在(自定义 composition)时保持旧字段,避免把用户锁死。
366
- */
367
- async function migrateConfigKeys(store, input) {
368
- if (!canUseCredentials(store)) return input;
369
- const credentials = credentialsService(store);
370
- const config = normalizeConfig(input);
371
- const used = new Set();
372
- let migrated = 0;
373
- let changed = false;
374
- for (const provider of config.providers) {
375
- let ref = validKeyRef(provider.apiKeyEnv);
376
- if (!ref) {
377
- ref = deriveKeyRef(provider.id, used);
378
- provider.apiKeyEnv = ref;
379
- changed = true;
380
- } else if (used.has(ref)) {
381
- ref = deriveKeyRef(provider.id, used);
382
- provider.apiKeyEnv = ref;
383
- changed = true;
384
- }
385
- used.add(ref);
386
- if (!provider.key) continue;
387
- try {
388
- const info = await credentials.describe(ref);
389
- if (!credentialIsStored(info)) {
390
- await credentials.set(ref, provider.key);
391
- migrated++;
392
- }
393
- delete provider.key;
394
- changed = true;
395
- } catch (error) {
396
- store.logHost('credential migration failed for provider ' + provider.id + ': ' + String(error && error.message ? error.message : error));
397
- }
398
- }
399
- if (!changed) return config;
400
- const saved = await writeConfig(store, config);
401
- if (migrated > 0) store.logHost('migrated ' + migrated + ' API key(s) to credentials store');
402
- return saved;
403
- }
404
- function migrateKeysOnce(store, config) {
405
- if (!store.keyMigration) store.keyMigration = migrateConfigKeys(store, config).finally(() => { store.keyMigration = null; });
406
- return store.keyMigration;
407
- }
408
- async function readConfig(store) {
409
- try {
410
- if (!existsSync(store.configFile)) {
411
- const empty = emptyConfig();
412
- rememberConfig(store, empty);
413
- return empty;
414
- }
415
- let config = normalizeConfig(JSON.parse(await readFile(store.configFile, 'utf8')));
416
- if (hasLegacyKeys(config) && canUseCredentials(store)) {
417
- try { config = await migrateKeysOnce(store, config); } catch (error) { store.logHost('config key migration failed: ' + String(error && error.message ? error.message : error)); }
418
- }
419
- rememberConfig(store, config);
420
- return config;
421
- } catch (_error) { return emptyConfig(); }
422
- }
423
- async function writeConfig(store, config) {
424
- const next = normalizeConfig(config);
425
- const task = store.writeQueue.then(async () => {
426
- store.ensureDirs();
427
- const tempFile = store.configFile + '.tmp-' + process.pid + '-' + randomUUID().slice(0, 8);
428
- try {
429
- await writeFile(tempFile, JSON.stringify(next, null, 2), { encoding: 'utf8', mode: 0o600 });
430
- await rename(tempFile, store.configFile);
431
- } finally {
432
- try { await unlink(tempFile); } catch (_error) { /* rename 成功后临时文件已不存在 */ }
433
- }
434
- rememberConfig(store, next);
435
- return next;
436
- });
437
- store.writeQueue = task.catch(() => {});
438
- return task;
439
- }
440
- /** 每次请求才解析一次密钥;不在内存里长期缓存,轮换后下一请求生效。 */
441
- async function resolveProviderCredential(store, provider) {
442
- const ref = validKeyRef(provider.apiKeyEnv);
443
- const credentials = credentialsService(store);
444
- if (ref) {
445
- if (credentials && typeof credentials.resolve === 'function') {
446
- try {
447
- const hit = await credentials.resolve(ref);
448
- if (hit && typeof hit.value === 'string' && hit.value.trim().length > 0) {
449
- return Object.assign({}, provider, { key: hit.value.trim() });
450
- }
451
- } catch (error) { store.logHost('credential resolve failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
452
- }
453
- const env = process.env[ref];
454
- if (env && env.trim()) return Object.assign({}, provider, { key: env.trim() });
455
- }
456
- if (provider.key) return provider;
457
- if (provider.optionalKey) return provider;
458
- throw localizedError(
459
- new Error('生图提供商「' + (provider.name || provider.id) + '」缺少 API Key,请到 DSH 设置 → 生图模型填写'
460
- + (ref ? '(凭据 ' + ref + ')' : '') + '。'),
461
- ref ? 'provider.missingKeyWithRef' : 'provider.missingKey',
462
- { provider: provider.name || provider.id, ref: ref }
463
- );
464
- }
465
- /** 保存配置前先把每个 provider 的新 key 写进凭据库,配置文件只保留 apiKeyEnv。 */
466
- async function saveConfigWithCredentials(store, raw) {
467
- const incoming = normalizeConfig(raw);
468
- const current = await readConfig(store);
469
- const credentials = credentialsService(store);
470
- const canStore = !!(credentials && typeof credentials.set === 'function');
471
- const canDescribe = !!(credentials && typeof credentials.describe === 'function');
472
- const currentById = new Map(current.providers.map((provider) => [provider.id, provider]));
473
- const used = new Set();
474
- const providers = [];
475
- for (const provider of incoming.providers) {
476
- const old = currentById.get(provider.id);
477
- let ref = validKeyRef(provider.apiKeyEnv) || validKeyRef(old && old.apiKeyEnv) || deriveKeyRef(provider.id, used);
478
- if (used.has(ref)) ref = deriveKeyRef(provider.id, used);
479
- used.add(ref);
480
- provider.apiKeyEnv = ref;
481
- const newKey = String(provider.key || '').trim();
482
- delete provider.key;
483
- if (newKey) {
484
- if (!canStore) throw localizedError(new Error('DSH 凭据服务未挂载,无法安全保存 API Key;请确认 base composition 包含 dsh-credentials-local。'), 'config.credentialsUnavailable');
485
- try {
486
- await credentials.set(ref, newKey);
487
- } catch (error) {
488
- const message = String(error && error.message ? error.message : error);
489
- throw localizedError(new Error('保存 API Key 失败:' + message), 'config.credentialSaveFailed', { message: message });
490
- }
491
- } else if (old && old.key) {
492
- if (canStore && canDescribe) {
493
- try {
494
- const info = await credentials.describe(ref);
495
- if (!credentialIsStored(info)) await credentials.set(ref, old.key);
496
- } catch (error) {
497
- const message = String(error && error.message ? error.message : error);
498
- throw localizedError(new Error('旧 API Key 迁移失败:' + message), 'config.legacyKeyMigrationFailed', { message: message });
499
- }
500
- } else {
501
- provider.key = old.key;
502
- }
503
- }
504
- providers.push(provider);
505
- }
506
- if (credentials && typeof credentials.unset === 'function') {
507
- const kept = new Set(providers.map((provider) => provider.id));
508
- for (const old of current.providers) {
509
- if (kept.has(old.id)) continue;
510
- const ref = validKeyRef(old.apiKeyEnv);
511
- if (!ref || used.has(ref)) continue;
512
- try { await credentials.unset(ref); } catch (error) { store.logHost('credential removal failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
513
- }
514
- }
515
- incoming.providers = providers;
516
- try {
517
- return await writeConfig(store, incoming);
518
- } catch (error) {
519
- const message = String(error && error.message ? error.message : error);
520
- throw localizedError(new Error('保存生图配置失败:' + message), 'config.writeFailed', { message: message });
521
- }
522
- }
523
137
  function sendJson(res, status, value) {
524
138
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
525
139
  res.end(JSON.stringify(value));
@@ -563,13 +177,28 @@ function pickProvider(config, purpose, args) {
563
177
  }
564
178
  let model;
565
179
  if (activeModel === 'auto') {
566
- if (!requestedModel) {
567
- throw new Error('Auto 模式下要由你选一个模型:' + ((provider.models || []).join(' / ') || '(列表为空,请让用户先在设置里添加模型)') + ',通过 model 传入。');
568
- }
569
- if (!(provider.models || []).includes(requestedModel)) {
570
- throw new Error('Auto 模式只能选当前提供商列表里的模型:' + requestedModel + '。可选:' + ((provider.models || []).join(' / ') || '(列表为空)'));
180
+ if (purpose === 'edit') {
181
+ // Auto 改图:只在能图生图的模型里选。没传 model 时自动取第一个,
182
+ // 传了但不能图生图就报清楚可选项,不要把问题拖到适配器层。
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);
187
+ if (!picked.model) {
188
+ throw new Error(picked.capable.length
189
+ ? 'Auto 模式下该模型不支持图生图:' + requestedModel + '。可改图的模型:' + picked.capable.join(' / ')
190
+ : 'Auto 模式下当前提供商没有支持图生图的模型,请到设置 → 生图模型换一个支持编辑的模型。');
191
+ }
192
+ model = picked.model;
193
+ } 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
+ }
200
+ model = requestedModel;
571
201
  }
572
- model = requestedModel;
573
202
  } else {
574
203
  if (requestedModel && requestedModel !== activeModel) {
575
204
  throw new Error('当前选中的模型是 ' + activeModel + '(提供商 ' + (provider.name || provider.id) + '),请求的是 ' + requestedModel + '。模型只能由用户在设置里切换。');
@@ -577,21 +206,18 @@ function pickProvider(config, purpose, args) {
577
206
  model = activeModel;
578
207
  }
579
208
  if (!(provider.models || []).includes(model)) {
580
- if (provider.models && provider.models.length) throw new Error('当前模型不在提供商的模型目录里,请到设置 → 生图模型补全。' + (purpose === 'edit' ? '图片编辑建议使用 gpt-image-2.5-sunburst 等编辑模型。' : ''));
209
+ if (provider.models && provider.models.length) throw new Error('当前模型不在提供商的模型目录里,请到设置 → 生图模型补全。');
581
210
  throw new Error('当前提供商还没有模型 ID,请到设置 → 生图模型添加并选择模型。');
582
211
  }
212
+ // 固定模型改图:提前说清楚,别等调用上游才报错。
213
+ if (purpose === 'edit' && editCapableModels(provider, [model]).length === 0) {
214
+ throw new Error('该模型不支持图生图:' + model + '。请到设置 → 生图模型换一个支持编辑的模型。');
215
+ }
583
216
  // 协议/适配器解析交给 resolveAdapter():不同模型族的请求形状由适配器描述符定义。
584
217
  // API Key 由 resolveProviderCredential() 在请求前从 DSH 凭据库解析,不在这里检查。
585
218
  if (!provider.baseUrl) throw new Error('生图提供商缺少 API 地址,请到设置 → 生图模型补全。');
586
219
  return { provider, model };
587
220
  }
588
- function safeExt(contentType) {
589
- const type = String(contentType || '').toLowerCase();
590
- if (type.includes('jpeg') || type.includes('jpg')) return 'jpg';
591
- if (type.includes('webp')) return 'webp';
592
- if (type.includes('gif')) return 'gif';
593
- return 'png';
594
- }
595
221
  function makeSignal(exec, timeoutMs) {
596
222
  const signals = [];
597
223
  if (exec && exec.signal) signals.push(exec.signal);
@@ -599,255 +225,175 @@ function makeSignal(exec, timeoutMs) {
599
225
  if (!signals.length) return undefined;
600
226
  return signals.length > 1 && AbortSignal.any ? AbortSignal.any(signals) : signals[0];
601
227
  }
602
- function sleep(ms) {
603
- return new Promise((resolve) => setTimeout(resolve, ms));
604
- }
605
- function safeJson(buffer) {
606
- try { return JSON.parse(buffer.toString('utf8')); } catch (_error) { return null; }
607
- }
608
- function sizeLabel(fitted) {
609
- if (!fitted) return '';
610
- if (fitted.omit || fitted.size === 'none') return 'auto';
611
- if (fitted.size === 'auto') return fitted.width && fitted.height ? fitted.width + 'x' + fitted.height : 'auto';
612
- return fitted.size;
613
- }
614
- function imageErrorText(failure) {
615
- const text = '生图接口失败:' + failure.message;
616
- const suffix = '(模型与提供商只能由用户在选择器里切换)';
617
- if (failure.kind === 'size') return text + '(该模型对尺寸有最小/最大像素限制,换一个尺寸或换支持该尺寸的模型)' + suffix;
618
- if (failure.kind === 'auth') return text + '(检查 API Key 与地址是否正确)' + suffix;
619
- if (failure.kind === 'param') return text + '(请求参数与模型不兼容)' + suffix;
620
- return text + suffix;
621
- }
622
228
  /**
623
- * 上游说「这个模型不支持这类操作」时,翻译成统一说法,
624
- * 免得对话模型把「模型不支持」当成临时故障去换模型重试。
229
+ * 上游生图任务的全局并发槽。
230
+ *
231
+ * 排队等待也算在工具总超时里(signal 已经带 timeout):用户不能看到工具卡在队列里
232
+ * 却一直没有截止时间。槽位只包住真正发往上游的那一段,本地参考图读取不占位。
625
233
  */
626
- function unsupportedModelMessage(kind, failure) {
627
- const text = String((failure && failure.message) || '');
628
- if (!/(model|模型)/i.test(text)) return '';
629
- if (!/(not support|does not support|unsupported|不支持|cannot|无法)/i.test(text)) return '';
630
- return '该模型不支持' + (kind === 'edit' ? '图生图' : '文生图') + ':' + text;
234
+ async function withUpstreamSlot(queue, signal, task) {
235
+ if (!queue) return task();
236
+ const release = await queue.acquire(signal);
237
+ try {
238
+ return await task();
239
+ } finally {
240
+ release();
241
+ }
631
242
  }
632
243
  /**
633
- * 真正发请求的地方:按适配器组装 → 发 → 解码。
634
- * 上游报错时只在三类情况下自愈:字段不认识(摘掉重试)、尺寸被拒(往上抬一档)、限流/5xx(退避重试)。
244
+ * 恢复一个已经提交过的异步任务:不重新提交,只沿任务日志里的
245
+ * submission / taskId / pollTarget 继续轮询并下载。
246
+ *
247
+ * 只支持异步任务;同步任务没有可查询的远端状态,任务日志也不会为它们落盘。
635
248
  */
636
- /**
637
- * 异步入队型:提交任务 → 轮询到 SUCCEEDED → 下载图片。
638
- * 提交阶段的参数错误照旧自愈(摘字段 / 抬尺寸),轮询阶段只对 429、5xx 继续等。
639
- */
640
- async function callAsyncImage(kind, adapter, provider, input, signal) {
641
- if (kind === 'edit') throw new Error('该模型(' + adapter.label + ')暂不支持参考图编辑,请到设置里换一个编辑模型。');
642
- const drops = new Set();
643
- let fitted = input.fitted;
644
- let submission = null;
645
- let lastFailure = null;
646
- let retries = 0;
647
-
648
- for (let attempt = 1; attempt <= 5; attempt++) {
649
- const built = prepareAsync(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops);
650
- const response = await request(adapterBase(provider) + built.path, {
651
- method: 'POST', headers: built.headers, body: built.body, signal: signal
249
+ async function resumeImageJob(args, exec, store, snapshot, queue, journal) {
250
+ const jobId = String((args && args.resume_job_id) || '').trim();
251
+ if (!jobId) throw new Error('resume_job_id 不能为空');
252
+ const job = await journal.get(jobId);
253
+ if (!job) {
254
+ throw attachFailure(new Error('找不到可恢复的生图任务:' + jobId + '。任务日志只保留最近 7 天,或任务已被清理。'), {
255
+ code: 'job_not_found', phase: 'resume'
652
256
  });
653
- const buffer = await readResponseBytes(response, 2 * 1024 * 1024);
654
- if (response.ok) {
655
- submission = safeJson(buffer);
656
- break;
657
- }
658
- const failure = classifyFailure(response.status, buffer.toString('utf8'));
659
- lastFailure = failure;
660
- logHost(kind + ' async submit ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
661
- const capability = unsupportedModelMessage(kind, failure);
662
- if (capability) throw new Error(capability);
663
-
664
- if (failure.kind === 'param' && failure.drop && !drops.has(failure.drop)) {
665
- drops.add(failure.drop);
666
- logHost(kind + ' async drop param "' + failure.drop + '"');
667
- continue;
668
- }
669
- if (failure.kind === 'size') {
670
- const next = escalateSize(adapter, fitted);
671
- if (next.size !== fitted.size) {
672
- fitted = next;
673
- logHost(kind + ' async size escalate → ' + next.size);
674
- continue;
675
- }
676
- }
677
- if (failure.retryable && retries < 2) {
678
- retries++;
679
- logHost(kind + ' async submit retry #' + retries + ' in ' + (600 * retries) + 'ms');
680
- await sleep(600 * retries);
681
- continue;
682
- }
683
- throw new Error(imageErrorText(failure));
684
257
  }
685
- if (!submission) throw new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '任务提交失败' }));
686
-
687
- const taskId = readTaskId(adapter, submission);
688
- if (!taskId) throw new Error('任务提交后没有拿到 task_id:' + JSON.stringify(submission).slice(0, 200));
689
- logHost(kind + ' async task=' + taskId + ' submitted');
258
+ const config = snapshot || await readConfig(store);
259
+ const defaults = (config && config.defaults) || {};
690
260
 
691
- const poll = adapter.poll || {};
692
- const deadline = Date.now() + (Number(poll.timeoutMs) || 300000);
693
- let interval = Number(poll.intervalMs) || 2000;
694
- let state = null;
695
- while (Date.now() < deadline) {
696
- await sleep(interval);
697
- const response = await request(pollUrlFor(adapter, provider, taskId), {
698
- method: 'GET', headers: pollHeaders(provider), signal: signal
699
- });
700
- const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
701
- const payload = safeJson(buffer);
702
- if (!response.ok || !payload) {
703
- const failure = classifyFailure(response.status, buffer.toString('utf8'));
704
- if (failure.retryable) continue;
705
- throw new Error(imageErrorText(failure));
706
- }
707
- state = readTaskState(adapter, payload);
708
- if (state.state === 'success') {
709
- const decoded = decodeImagePayload(state.node, null);
710
- const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
711
- logHost(kind + ' async task=' + taskId + ' done');
712
- return { fitted: fitted, bytes: image.bytes, contentType: image.contentType };
713
- }
714
- if (state.state === 'failure') {
715
- throw new Error('生图任务失败(' + state.status + '):' + state.message);
716
- }
717
- interval = Math.min(Math.round(interval * 1.15), 5000);
261
+ // 已经保存过、文件还在:直接返回原结果,不再打上游。
262
+ if (job.status === 'saved' && job.file && existsSync(job.file)) {
263
+ return {
264
+ file: job.file, filename: path.basename(job.file), provider: job.providerName || job.providerId,
265
+ model: job.model, size: job.size, bytes: 0, contentType: '',
266
+ generated: job.generated || '', original: job.original || '', note: job.note || '', jobId: job.id
267
+ };
718
268
  }
719
- throw new Error('生图任务超时(' + taskId + (state ? ',最后状态 ' + state.status : '') + ')');
720
- }
721
- async function callImageApi(kind, adapter, provider, input, signal) {
722
- if (!adapterSupportsKind(adapter, kind)) {
723
- throw new Error('该模型不支持' + (kind === 'edit' ? '图生图' : '文生图')
724
- + '(' + String(input.model || adapter.label) + ')。请到设置 → 生图模型换一个支持它的模型。');
269
+ if (job.status === 'submitting') {
270
+ throw attachFailure(new Error('这个任务在提交途中中断,无法确认上游是否已经受理;请先按原提示词重新提交,避免重复计费。'), {
271
+ code: 'submission_unknown', phase: 'resume', submissionState: 'unknown', jobId: job.id
272
+ });
725
273
  }
726
- if (adapter.async) return callAsyncImage(kind, adapter, provider, input, signal);
727
- if (typeof adapter.execute === 'function') {
728
- const out = await adapter.execute(kind, provider, input, signal);
729
- return { fitted: input.fitted, bytes: out.bytes, contentType: out.contentType };
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
277
+ });
730
278
  }
731
- const fieldNames = (adapter.editFields && adapter.editFields.length) ? adapter.editFields : ['image'];
732
- const drops = new Set();
733
- let fitted = input.fitted;
734
- let fieldIndex = 0;
735
- let sizeRetries = 0;
736
- let retries = 0;
737
- let lastFailure = null;
738
279
 
739
- for (let attempt = 1; attempt <= 5; attempt++) {
740
- const built = kind === 'edit'
741
- ? prepareEdit(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops, fieldNames[fieldIndex])
742
- : prepareGenerate(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops);
743
- const response = await request(adapterBase(provider) + built.path, {
744
- method: 'POST', headers: built.headers, body: built.body, signal: signal
280
+ const provider = (config.providers || []).find((item) => item && item.id === job.providerId);
281
+ if (!provider) {
282
+ throw attachFailure(new Error('恢复任务所属的提供商已不存在:' + job.providerId + '。请恢复提供商配置后再试。'), {
283
+ code: 'job_provider_missing', phase: 'resume', jobId: job.id
745
284
  });
746
- const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
747
-
748
- if (response.ok) {
749
- const parsed = safeJson(buffer);
750
- const decoded = parsed ? decodeImagePayload(parsed, null) : decodeImagePayload(null, buffer);
751
- const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
752
- return { fitted: fitted, bytes: image.bytes, contentType: image.contentType };
753
- }
754
-
755
- const failure = classifyFailure(response.status, buffer.toString('utf8'));
756
- lastFailure = failure;
757
- logHost(kind + ' upstream ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
758
-
759
- const capability = unsupportedModelMessage(kind, failure);
760
- if (capability) throw new Error(capability);
285
+ }
286
+ const resolved = await resolveProviderCredential(store, provider);
287
+ const adapter = resolveAdapter(resolved, job.model);
761
288
 
762
- if (failure.kind === 'param' && failure.drop && !drops.has(failure.drop)) {
763
- drops.add(failure.drop);
764
- logHost(kind + ' drop param "' + failure.drop + '" for adapter ' + adapter.id);
765
- continue;
766
- }
767
- if (kind === 'edit' && response.status === 400 && /image/i.test(failure.message) && fieldIndex + 1 < fieldNames.length) {
768
- fieldIndex++;
769
- logHost(kind + ' retry with form field "' + fieldNames[fieldIndex] + '"');
770
- continue;
771
- }
772
- if (failure.kind === 'size' && sizeRetries < 2) {
773
- const next = escalateSize(adapter, fitted);
774
- if (next.size !== fitted.size) {
775
- fitted = next;
776
- sizeRetries++;
777
- logHost(kind + ' size escalate → ' + next.size + '(' + next.reason + ')');
778
- continue;
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
+ }
779
311
  }
780
- }
781
- if (failure.retryable && retries < 2) {
782
- retries++;
783
- await sleep(600 * retries);
784
- continue;
785
- }
786
- throw new Error(imageErrorText(failure));
312
+ ));
313
+ } else {
314
+ throw attachFailure(new Error('该任务不是异步队列任务,无法从任务日志恢复。'), {
315
+ code: 'job_not_resumable', phase: 'resume', jobId: job.id
316
+ });
787
317
  }
788
- throw new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '重试次数用尽' }));
789
- }
790
- /** 尺寸被抬大过,就尽量缩回用户要的尺寸。 */
791
- export function finalizeImage(result) {
792
- let bytes = result.bytes;
793
- let contentType = result.contentType;
794
- let fitted = result.fitted;
795
- let note = '';
796
- const wanted = fitted && fitted.requested;
797
- const wantedPixels = wanted ? wanted.width * wanted.height : 0;
798
- const fittedPixels = fitted ? (fitted.width || 0) * (fitted.height || 0) : 0;
799
- // 只有用户要的尺寸比模型实际生成的小才缩回去。用户要的更大时,
800
- // 上游已经按上限生成,不能再放大冒充用户尺寸(会损失画质)。
801
- if (fitted && fitted.adjusted && wanted && wanted.width && wanted.height
802
- && wanted.text !== fitted.size && fittedPixels > wantedPixels) {
803
- const resized = resizeTo(bytes, wanted.width, wanted.height);
804
- if (resized) {
805
- bytes = resized.bytes;
806
- contentType = resized.contentType;
807
- logHost('resize ' + fitted.size + ' → ' + wanted.text);
808
- fitted = Object.assign({}, fitted, { size: wanted.text, width: wanted.width, height: wanted.height, adjusted: false });
809
- } else {
810
- logHost('resize unavailable, keep ' + fitted.size + '(用户要 ' + wanted.text + ')');
811
- }
812
- } else if (fitted && fitted.adjusted && wanted && fittedPixels < wantedPixels) {
813
- note = '该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + wanted.text + ',未放大)。';
814
- logHost('keep model max ' + fitted.size + '(用户要 ' + wanted.text + ',不放大)');
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;
815
324
  }
816
- return { bytes: bytes, contentType: contentType, fitted: fitted, note: note };
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;
817
332
  }
818
- async function saveImage(bytes, contentType, provider, model, size, exec) {
819
- ensureDirs();
820
- const dir = generatedImageDir(exec);
821
- mkdirSync(dir, { recursive: true });
822
- const ext = safeExt(contentType);
823
- const filename = 'mo-' + Date.now() + '-' + randomUUID().slice(0, 8) + '.' + ext;
824
- const file = path.join(dir, filename);
825
- await writeFile(file, bytes);
826
- return { file, filename, provider: provider.name || provider.id, model, size, bytes: bytes.length, contentType };
333
+ /** 只保留有值的 params;别的形状一律当没传。 */
334
+ function readParamsArg(args) {
335
+ const raw = args && args.params;
336
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
337
+ const out = {};
338
+ for (const [key, value] of Object.entries(raw)) {
339
+ if (value === undefined || value === null) continue;
340
+ out[key] = value;
341
+ }
342
+ return Object.keys(out).length ? out : null;
827
343
  }
828
- async function generate(args, exec, store) {
344
+
345
+ async function generate(args, exec, store, snapshot, queue, journal) {
829
346
  const prompt = String(args.prompt || '').trim();
830
347
  if (!prompt) throw new Error('prompt 不能为空:先按当前模型的提示词公式写好完整提示词。');
831
348
  const negativePrompt = String(args.negative_prompt || '').trim();
832
- const config = await readConfig(store);
349
+ // 工具入口已经把配置读成快照传进来:同一次调用里不再读第二次,
350
+ // 免得检查、选模型和发请求之间用户改配置,一次生图用到两套设置。
351
+ const config = snapshot || await readConfig(store);
833
352
  const picked = pickProvider(config, 'generate', args);
834
353
  const model = picked.model;
835
354
  const provider = await resolveProviderCredential(store, picked.provider);
836
355
  const adapter = resolveAdapter(provider, model);
837
356
  const profile = resolvePromptProfile(model, adapter);
838
357
  const defaults = (config && config.defaults) || {};
839
- const quality = qualityForAdapter(adapter, resolveQuality(defaults));
840
- const fitted = fitSize(adapter, resolveSizeArg(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;
841
364
  if (fitted.rejected) throw new Error(fitted.reason);
842
365
  logHost('generate adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + (fitted.adjusted ? '(' + fitted.reason + ')' : ''));
843
366
  const signal = makeSignal(exec, 360000);
844
- const result = await callImageApi('generate', adapter, provider, {
845
- model: model, prompt: prompt, negativePrompt: negativePrompt || undefined,
846
- fitted: fitted, quality: quality
847
- }, signal);
848
- const final = finalizeImage(result);
849
- const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
850
- if (final.note) saved.note = final.note;
367
+ const extraParams = readParamsArg(args);
368
+ const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
369
+ 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
+ }
851
397
  return saved;
852
398
  }
853
399
  const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
@@ -975,34 +521,61 @@ export async function readReferences(sources, signal, totalLimit = MAX_REF_TOTAL
975
521
  return images;
976
522
  }
977
523
 
978
- async function edit(args, exec, store) {
524
+ async function edit(args, exec, store, snapshot, queue, journal) {
979
525
  const prompt = String(args.prompt || '').trim();
980
526
  if (!prompt) throw new Error('prompt 不能为空:图片编辑需要写清保留什么、只改什么。');
981
527
  const negativePrompt = String(args.negative_prompt || '').trim();
982
528
  const sources = Array.isArray(args.images) ? args.images.filter((item) => String(item || '').trim()) : [];
983
529
  if (!sources.length) throw new Error('图片编辑至少需要 1 张参考图。');
984
530
  if (sources.length > MAX_REF_COUNT) throw new Error('参考图最多 ' + MAX_REF_COUNT + ' 张,当前 ' + sources.length + ' 张。');
985
- const config = await readConfig(store);
531
+ const config = snapshot || await readConfig(store);
986
532
  const defaults = (config && config.defaults) || {};
987
533
  const picked = pickProvider(config, 'edit', args);
988
534
  const model = picked.model;
989
535
  const provider = await resolveProviderCredential(store, picked.provider);
990
536
  const adapter = resolveAdapter(provider, model);
991
537
  const profile = resolvePromptProfile(model, adapter);
992
- const quality = qualityForAdapter(adapter, resolveQuality(defaults));
993
- const fitted = fitSize(adapter, resolveSizeArg(defaults));
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;
994
544
  if (fitted.rejected) throw new Error(fitted.reason);
995
545
  const signal = makeSignal(exec, 360000);
996
546
  const totalLimit = referenceLimitFor(adapter);
997
547
  const images = await readReferences(sources, signal, totalLimit);
998
548
  logHost('edit adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + ' refs=' + images.length);
999
- const result = await callImageApi('edit', adapter, provider, {
1000
- model: model, prompt: prompt, negativePrompt: negativePrompt || undefined,
1001
- fitted: fitted, quality: quality, images: images
1002
- }, signal);
1003
- const final = finalizeImage(result);
1004
- const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
1005
- if (final.note) saved.note = final.note;
549
+ const extraParams = readParamsArg(args);
550
+ const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
551
+ 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
+ }
1006
579
  return saved;
1007
580
  }
1008
581
 
@@ -1040,13 +613,37 @@ function parseSkillMarkdown(raw) {
1040
613
  function installPromptRecipe(ctx, store) {
1041
614
  const register = (target) => {
1042
615
  if (!target.systemPrompt || typeof target.systemPrompt.section !== 'function') return;
616
+ // 配置状态按会话算:本会话读过、之后配置没变,模型就直接生图,不必再读一遍。
617
+ // 先登记变量,再写占位符:占位符进了提示词、变量却没登记上,整段组装会报错。
618
+ let marker = '';
619
+ if (typeof target.systemPrompt.variable === 'function') {
620
+ try {
621
+ target.effect(() => target.systemPrompt.variable(CONFIG_STATE_VARIABLE, (context) => {
622
+ try {
623
+ const session = context && context.agent ? context.agent.session : null;
624
+ const signature = settingsSignature(settingsPayload(activeImageState(store)));
625
+ return configStateText(settingsState(session, signature));
626
+ } catch (error) {
627
+ logHost('config state marker error: ' + String(error && error.message ? error.message : error));
628
+ return configStateText('unread');
629
+ }
630
+ }), 'mo-image: config state');
631
+ marker = CONFIG_STATE_MARKER;
632
+ } catch (error) { logHost('config state marker register error: ' + String(error && error.message ? error.message : error)); }
633
+ }
634
+ // 老宿主没有变量机制就当场算:section 的 text 拿到本次组装的上下文,一样按会话算。
635
+ const sectionText = (session) => {
636
+ const state = activeImageState(store);
637
+ if (!state) return '';
638
+ const value = marker || configStateText(settingsState(session, settingsSignature(settingsPayload(state))));
639
+ return promptSectionText(state, value);
640
+ };
1043
641
  target.effect(() => target.systemPrompt.section({
1044
642
  name: 'mo-image:prompt-recipe',
1045
643
  order: 2950,
1046
- text: () => {
644
+ text: (context) => {
1047
645
  try {
1048
- const state = activeImageState(store);
1049
- return state ? promptSectionText(state) : '';
646
+ return sectionText(context && context.agent ? context.agent.session : null);
1050
647
  } catch (error) {
1051
648
  logHost('prompt recipe error: ' + String(error && error.message ? error.message : error));
1052
649
  return '';
@@ -1131,7 +728,22 @@ async function modelsForRequest(store, body) {
1131
728
  try { adapter = resolveAdapter(Object.assign({}, provider, { adapter: 'openai-images' }), ''); } catch (_error) { /* keep original */ }
1132
729
  }
1133
730
  if (!adapter || typeof adapter.listModels !== 'function') throw localizedError(new Error('该部署方式不支持获取模型列表'), 'models.unsupported');
1134
- const entries = await listProviderModelEntries(adapter, provider, AbortSignal.timeout(20000));
731
+ let entries;
732
+ try {
733
+ entries = await listProviderModelEntries(adapter, provider, AbortSignal.timeout(20000));
734
+ } catch (error) {
735
+ // 没有 /models 的端点常见于网关和特殊版本:提醒用户手动填模型 ID,而不是只甩一个 404。
736
+ const localized = error && error.localized;
737
+ if (localized && localized.code === 'upstream.http' && Number(localized.params && localized.params.status) === 404) {
738
+ const wrapped = localizedError(
739
+ new Error('该地址没有模型列表接口(HTTP 404),请手动填写模型 ID。'),
740
+ 'models.notFound'
741
+ );
742
+ wrapped.status = 404;
743
+ throw wrapped;
744
+ }
745
+ throw error;
746
+ }
1135
747
  const seen = new Set();
1136
748
  const allModels = [];
1137
749
  const names = {};
@@ -1151,6 +763,7 @@ async function modelsForRequest(store, body) {
1151
763
  export function apply(ctx, options = {}) {
1152
764
  ensureDirs();
1153
765
  logHost('apply');
766
+ setImageExecutionLogger(logHost);
1154
767
  setNetworkLogger(logHost);
1155
768
  // 配置写入是权限问题,不是提示词问题:任何工具调用只要指向插件配置就拒绝。
1156
769
  try {
@@ -1165,8 +778,27 @@ export function apply(ctx, options = {}) {
1165
778
  logHost: logHost,
1166
779
  credentialsAccessor: () => (typeof ctx.get === 'function' ? ctx.get('credentials') : undefined)
1167
780
  });
781
+ // 上游并发是进程级资源;每个 apply 实例一条队列,测试和多次挂载互不污染。
782
+ const imageQueue = createImageQueue(options.queue && typeof options.queue === 'object' ? options.queue : {});
783
+ // 同一个 callId 的重放复用结果;只在内存里,进程重启后的恢复另由任务日志负责。
784
+ const callRegistry = createCallRegistry();
785
+ // 异步任务日志:提交后先落盘,进程重启时还能凭 jobId 找回远端任务。
786
+ const jobJournal = createJobJournal({ dir: path.join(stateDir(), 'jobs') });
787
+ Promise.resolve(jobJournal.prune(7 * 24 * 60 * 60 * 1000))
788
+ .catch((error) => logHost('job journal prune failed: ' + String(error && error.message ? error.message : error)));
1168
789
  try { store.webOriginHost = new URL(ctx.webServer.getOrigin()).hostname; } catch (_error) { store.webOriginHost = ''; }
1169
790
  readConfigSync(store);
791
+ // 只读状态服务:工作台等其它插件通过 ctx.get('moImageStatus') 取快照,
792
+ // 不再各自解析 config.json / 凭据库,也不靠模型名猜编辑能力。
793
+ try {
794
+ if (typeof ctx.provide === 'function') {
795
+ ctx.effect(() => ctx.provide('moImageStatus', {
796
+ contract: STATUS_CONTRACT,
797
+ describe: () => describeImageStatus(store)
798
+ }), 'mo-image: status service');
799
+ logHost('status service registered (moImageStatus)');
800
+ }
801
+ } catch (error) { logHost('status service error: ' + String(error && error.message ? error.message : error)); }
1170
802
  if (canUseCredentials(store)) {
1171
803
  readConfig(store).catch((error) => logHost('config key migration failed: ' + String(error && error.message ? error.message : error)));
1172
804
  }
@@ -1261,6 +893,33 @@ export function apply(ctx, options = {}) {
1261
893
  } catch (error) { logHost('models route error: ' + String(error)); return () => {}; }
1262
894
  }, 'mo-image: models route');
1263
895
 
896
+ ctx.effect(() => {
897
+ try {
898
+ return ctx.webServer.register({
899
+ kind: 'exact', path: '/api/mo-image/comfy/analyze',
900
+ handler: async (req, res) => {
901
+ try {
902
+ assertLocalRequest(store, req, true);
903
+ if (req.method !== 'POST') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
904
+ 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
+ const workflow = String(body.workflow || '');
911
+ 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 });
914
+ return sendJson(res, 200, { ok: true, ...analysis });
915
+ } catch (error) {
916
+ return sendJson(res, 200, { ok: false, error: String(error && error.message ? error.message : error) });
917
+ }
918
+ }
919
+ });
920
+ } catch (error) { logHost('analyze route error: ' + String(error)); return () => {}; }
921
+ }, 'mo-image: analyze route');
922
+
1264
923
  ctx.effect(() => {
1265
924
  try {
1266
925
  return ctx.webServer.register({
@@ -1332,6 +991,8 @@ export function apply(ctx, options = {}) {
1332
991
  }, 'mo-image: update route');
1333
992
 
1334
993
  const renderImage = (_args, value) => {
994
+ // 配置交接:这次没有生成图片,整个返回值按 JSON 交给模型(含 settings),不渲染图片行。
995
+ if (value && value.needsSettings) return [{ type: 'text', text: JSON.stringify(value) }];
1335
996
  let ref = '';
1336
997
  try { ref = value && value.path ? signPreview(value.path) : ''; } catch (error) { logHost('preview sign error: ' + String(error && error.message ? error.message : error)); }
1337
998
  if (!ref) ref = path.basename((value && value.path) || '');
@@ -1340,6 +1001,8 @@ export function apply(ctx, options = {}) {
1340
1001
  text: '![生成图片](' + publicOrigin() + '/api/mo-image/preview/' + encodeURIComponent(ref) + ')'
1341
1002
  }];
1342
1003
  if (value && value.note) blocks.push({ type: 'text', text: value.note });
1004
+ // 异步任务 id 必须让模型看得见:任务中断时,下一轮才有 resume_job_id 可传。
1005
+ if (value && value.jobId) blocks.push({ type: 'text', text: '任务 ID:' + value.jobId + '(中断后可用 resume_job_id 继续)' });
1343
1006
  return blocks;
1344
1007
  };
1345
1008
  const pendingPresentations = new Map();
@@ -1373,85 +1036,160 @@ export function apply(ctx, options = {}) {
1373
1036
  type: 'object', additionalProperties: false, required: ['path'],
1374
1037
  properties: {
1375
1038
  path: { type: 'string' },
1376
- note: { type: 'string' }
1039
+ model: { type: 'string' },
1040
+ // 成品尺寸与上游原始尺寸:严格模式靠这两个值解释"我缩过 / 上游没按你说的出"。
1041
+ size: { type: 'string' },
1042
+ generated: { type: 'string' },
1043
+ original: { type: 'string' },
1044
+ note: { type: 'string' },
1045
+ jobId: { type: 'string' },
1046
+ // 配置没对齐时用这个形状回答:不生成图片,直接把当前配置交给模型。
1047
+ needsSettings: { type: 'boolean' },
1048
+ settings: { type: 'object' }
1377
1049
  }
1378
1050
  },
1379
1051
  render: renderImage
1380
1052
  };
1381
1053
  // DSH 的工具契约要求每个工具声明 output { schema, render? };settings
1382
1054
  // 返回值就是给模型看的全部内容:一个最小 JSON(提供商/模型唯一 id + 优化开关 + 一句写法提示)。
1055
+ // 配置没变时只回 { unchanged, hint },所以 schema 只把 hint 标成必填。
1383
1056
  const modelsOutput = {
1384
1057
  schema: {
1385
1058
  type: 'object', additionalProperties: false,
1386
- required: ['provider', 'model', 'promptOptimization', 'hint'],
1059
+ required: ['hint'],
1387
1060
  properties: {
1388
1061
  provider: { type: 'string' },
1389
1062
  model: { type: 'string' },
1390
1063
  promptOptimization: { type: 'boolean' },
1064
+ canEdit: { type: 'boolean' },
1065
+ sizeMode: { type: 'string', enum: ['auto', 'fixed'] },
1066
+ strict: { type: 'boolean' },
1067
+ size: { type: 'string' },
1068
+ control: { type: 'string' },
1069
+ sizeOptions: { type: 'array', items: { type: 'string' } },
1391
1070
  hint: { type: 'string' },
1392
- models: { type: 'array', items: { type: 'string' } }
1071
+ unchanged: { type: 'boolean' },
1072
+ models: { type: 'array', items: { type: 'string' } },
1073
+ editModels: { type: 'array', items: { type: 'string' } },
1074
+ params: { type: 'array', items: { type: 'object' } }
1393
1075
  }
1394
1076
  },
1395
1077
  render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }]
1396
1078
  };
1397
1079
 
1398
- // 生图前必须先读配置。只靠系统提示词时,多轮之后模型会按上一条提示词的习惯继续写,
1399
- // 换了模型、关了提示词优化都不看;把当前配置放进工具结果,能让它每次写之前重读一遍。
1400
- // 一次读取在当前回合内有效,配置一变(换模型、切优化开关)就作废。
1401
- const marks = new WeakMap();
1402
- const signatureOf = (state) => {
1403
- if (!state) return '';
1404
- const defaults = state.defaults || {};
1405
- return [
1406
- (state.provider && state.provider.id) || '', state.model,
1407
- state.promptOptimization === false ? 'off' : 'on',
1408
- defaults.quality || '', defaults.width || '', defaults.height || ''
1409
- ].join('|');
1410
- };
1080
+ // 生图前要读过当前配置,但只在「这个会话还没读过」或「配置真的变了」时才需要重读。
1081
+ // 记忆按会话保存(见 settings-memory),比较的是配置快照而不是变更次数:用户改了又
1082
+ // 改回去、中间没有对话,仍然算没有变化。系统提示词里的「配置状态」用同一个判断。
1083
+ //
1084
+ // 「读过」= 这一刻的配置已经锁进这次调用的结果(settings 的 payload / 交接的 settings)。
1085
+ // 之后用户再改,签名就变了,下一次调用会重新判断;所以这次锁定不会因为后续修改而失真,
1086
+ // 进行中的请求也不受后续修改影响。
1087
+ //
1088
+ // 没读完就调用生图工具时不报错:把当前配置直接交回去,让模型按它重写提示词再调一次。
1089
+ // 一次失败的工具调用对用户就是一条红字,而模型本来就能从结果里把配置读懂。
1411
1090
  const sessionOf = (exec) => (exec && exec.agent && exec.agent.session) || null;
1412
- const currentTurn = (session) => {
1413
- try {
1414
- const projections = ctx.get && ctx.get('sessionProjections');
1415
- if (!projections || typeof projections.stateOf !== 'function') return null;
1416
- const boundary = projections.stateOf(session, 'turnBoundary');
1417
- const seq = boundary && boundary.openTurnStartSeq;
1418
- return typeof seq === 'number' ? seq : null;
1419
- } catch (error) { logHost('turn lookup error: ' + String(error && error.message ? error.message : error)); return null; }
1420
- };
1421
- const rememberSettings = (exec) => {
1422
- const session = sessionOf(exec);
1423
- if (!session) return;
1424
- marks.set(session, { signature: signatureOf(activeImageState(store)), turn: currentTurn(session) });
1425
- };
1426
- const requireSettings = (exec) => {
1091
+ const settingsHandoff = (exec, mode, snapshot) => {
1427
1092
  const session = sessionOf(exec);
1428
- if (!session) return; // 没有会话上下文(脚本调用)时无从比对,不拦。
1429
- const mark = marks.get(session);
1430
- const turn = currentTurn(session);
1431
- const fresh = !!mark
1432
- && mark.signature === signatureOf(activeImageState(store))
1433
- && (turn === null || mark.turn === turn);
1434
- if (!fresh) {
1435
- throw new Error('生成前先读当前配置:调用 mo_image_settings,按它返回的模型写法和提示词优化状态写提示词,再调用本工具。');
1093
+ if (!session) return null; // 没有会话上下文(脚本调用)时无从比对,不拦。
1094
+ const payload = settingsPayload(activeImageState(store, snapshot));
1095
+ // 没有选模型不是「配置过期」问题:不记成已读,也别让模型重试到 generate() 里去撞红字。
1096
+ if (!payload.model) {
1097
+ return {
1098
+ path: '',
1099
+ needsSettings: true,
1100
+ settings: payload,
1101
+ note: '还没有选择生图模型,这次没有生成。请让用户先在设置 → 生图模型里选一个,再按 settings 写提示词调用本工具。'
1102
+ };
1436
1103
  }
1104
+ // 模型不支持改图时不要用交接盖住它:让 edit() 抛那条带模型名、能被本地化的能力错误。
1105
+ // 用交接会变成“重写提示词再调用”,重试还是同一个错误,只是多绕一轮。
1106
+ 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);
1111
+ return {
1112
+ path: '',
1113
+ needsSettings: true,
1114
+ settings: payload,
1115
+ note: (state === 'stale'
1116
+ ? '配置在你上次读取后改过了,这次没有生成。'
1117
+ : '本会话还没读过生图配置,这次没有生成。')
1118
+ + '按 settings 里的模型写法和提示词优化状态重写提示词,再调用一次本工具。'
1119
+ };
1437
1120
  };
1438
- // 拿不到回合号时退回一次一读:生成成功后作废这次读取,失败不消耗。
1439
- const consumeSettings = (exec) => {
1440
- const session = sessionOf(exec);
1441
- if (session && currentTurn(session) === null) marks.delete(session);
1121
+
1122
+ // 调用身份:同一会话 + 同一个 callId。会话对象用 WeakMap 编号,避免依赖宿主是否
1123
+ // 暴露 session id;没有 callId 的脚本入口不做去重(宿主没有稳定身份,猜不得)。
1124
+ const sessionIds = new WeakMap();
1125
+ let nextSessionId = 0;
1126
+ const sessionIdOf = (session) => {
1127
+ if (!session || typeof session !== 'object') return 'no-session';
1128
+ let id = sessionIds.get(session);
1129
+ if (!id) { id = 's' + (++nextSessionId); sessionIds.set(session, id); }
1130
+ return id;
1131
+ };
1132
+ const invocationKey = (exec, tool) => {
1133
+ const callId = String((exec && exec.callId) || '').trim();
1134
+ if (!callId) return '';
1135
+ return tool + ':' + sessionIdOf(sessionOf(exec)) + ':' + callId;
1136
+ };
1137
+ /** 有效请求摘要:参数 + 配置快照 + 提供商地址。键顺序必须稳定。 */
1138
+ const invocationFingerprint = (tool, args, snapshot) => {
1139
+ const state = activeImageState(store, snapshot);
1140
+ const input = {
1141
+ prompt: String((args && args.prompt) || ''),
1142
+ negative_prompt: String((args && args.negative_prompt) || ''),
1143
+ images: Array.isArray(args && args.images) ? args.images.map((item) => String(item || '')) : [],
1144
+ size: String((args && args.size) || ''),
1145
+ model: String((args && args.model) || ''),
1146
+ provider: String((args && args.provider) || ''),
1147
+ params: args && args.params && typeof args.params === 'object' ? args.params : null
1148
+ };
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
+ ]);
1158
+ };
1159
+ const imagePayload = (result) => {
1160
+ const payload = { path: result.file, model: String(result.model || '') };
1161
+ if (result.size) payload.size = String(result.size);
1162
+ if (result.generated) payload.generated = String(result.generated);
1163
+ if (result.original) payload.original = String(result.original);
1164
+ if (result.note) payload.note = result.note;
1165
+ // 异步任务 id:日志/恢复入口用;同步任务没有。
1166
+ if (result.jobId) payload.jobId = String(result.jobId);
1167
+ return payload;
1442
1168
  };
1443
1169
 
1444
1170
  // 每个工具单独兜底:一个工具的契约不满足时,不会连带其它工具一起注册失败。
1445
1171
  try {
1446
1172
  ctx.tools.register({
1447
1173
  name: 'mo_image_settings',
1448
- description: 'Read the current image settings before every generation or edit: the picked provider and model, whether prompt optimization is on, and a one-line hint for how to write the prompt for that model. Calling mo_image_generate or mo_image_edit without reading this first in the current turn is rejected, so read it again after the user switches models or toggles a setting.',
1449
- parameters: { type: 'object', additionalProperties: false, properties: {} },
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.',
1175
+ parameters: {
1176
+ type: 'object', additionalProperties: false,
1177
+ properties: {
1178
+ refresh: { type: 'boolean', description: 'Re-read the full payload after compaction, or when the earlier read is no longer in context.' }
1179
+ }
1180
+ },
1450
1181
  output: modelsOutput,
1451
1182
  timeoutMs: 15000,
1452
- async execute(_args, exec) {
1453
- rememberSettings(exec);
1454
- return settingsPayload(activeImageState(store));
1183
+ async execute(args, exec) {
1184
+ const payload = settingsPayload(activeImageState(store));
1185
+ const signature = settingsSignature(payload);
1186
+ 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 重读。' };
1191
+ }
1192
+ return payload;
1455
1193
  }
1456
1194
  });
1457
1195
  } catch (error) { logHost('settings tool register error: ' + String(error)); }
@@ -1459,23 +1197,44 @@ export function apply(ctx, options = {}) {
1459
1197
  try {
1460
1198
  ctx.tools.register({
1461
1199
  name: 'mo_image_generate',
1462
- description: 'Generate a new image with the active image model. Call mo_image_settings first in this turn: it returns the current model, the prompt-optimization state and the writing rules for that model, and this tool rejects a call that did not read it. Then follow what it returned: when optimization is On, write the final prompt in the active model\'s dialect; when Off, pass the user\'s original wording unchanged. Model, size, and quality come from the picker, so leave the model argument out; only in Auto mode must you pass one id from the active provider list. Load the mo-image-generation skill only when you have not already read this model\'s writing rules in this conversation; when optimization is Off, use only its invocation and output guidance, not its prompt formulas. The tool returns a Markdown image line and a file card; reply with that Markdown line and nothing else. Output is final: never judge or describe the image, never switch provider, model or tool (local image models, Blender, scripting) on your own, and do not open or read the image unless the user explicitly asks to look at it. On failure report the error verbatim and at most ask the user whether to switch.',
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.',
1463
1201
  parameters: {
1464
- type: 'object', additionalProperties: false, required: ['prompt'],
1202
+ type: 'object', additionalProperties: false,
1465
1203
  properties: {
1466
- prompt: { type: 'string', description: 'Final prompt adapted to the active model when optimization is On; otherwise the user\'s original wording. Cover subject, action, environment, style, lighting, composition, and constraints; quote in-image text exactly.' },
1467
- negative_prompt: { type: 'string', description: 'Optional prompt content. Only for models that support negative prompts; list artifacts and undesired elements. Omit otherwise.' },
1468
- model: { type: 'string', description: 'Optional outside Auto mode: omit it and the picker\'s model is used. In Auto mode it is required — one id from the active provider list. A value other than the picked model is rejected; never use it to switch models.' },
1469
- provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' }
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.' },
1205
+ 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.' },
1207
+ 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
+ provider: { type: 'string', description: 'Optional. The user-selected provider; validated against the picker, never switched.' },
1209
+ params: {
1210
+ type: 'object', additionalProperties: true,
1211
+ description: 'Optional workflow params from mo_image_settings; omit unneeded ones (defaults apply); unsupported keys are ignored and reported.'
1212
+ },
1213
+ resume_job_id: { type: 'string', description: 'Optional. Resume a previously submitted async job by its jobId; no new submission is made. Leave prompt/images out unless you are starting a new task.' }
1470
1214
  }
1471
1215
  },
1472
1216
  output, timeoutMs: 360000,
1473
1217
  async execute(args, exec) {
1474
- requireSettings(exec);
1475
- const result = await generate(args, exec, store);
1476
- consumeSettings(exec);
1477
- presentImage(exec, result);
1478
- return result.note ? { path: result.file, note: result.note } : { path: result.file };
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;
1479
1238
  }
1480
1239
  });
1481
1240
  } catch (error) { logHost('generate tool register error: ' + String(error)); }
@@ -1483,24 +1242,43 @@ export function apply(ctx, options = {}) {
1483
1242
  try {
1484
1243
  ctx.tools.register({
1485
1244
  name: 'mo_image_edit',
1486
- description: 'Edit or refine an existing image with one or more reference images. Call mo_image_settings first in this turn: it returns the current model, the prompt-optimization state and the writing rules for that model, and this tool rejects a call that did not read it. Follow what it returned: when optimization is Off, use the user\'s original edit wording and do not expand it. Model, size, and quality come from the picker, so leave the model argument out; only in Auto mode must you pass one id from the active provider list. Name each reference as 图1/图2 in the prompt. For a full redo that must not copy the current image, use mo_image_generate instead. Load the mo-image-editing skill only when you have not already read this model\'s editing rules in this conversation; when optimization is Off, use only its invocation and output guidance, not its edit formula. Output is final: never judge or describe the image, never switch provider, model or tool (local image models, Blender, scripting) on your own, and do not open or read the image unless the user explicitly asks to look at it. On failure report the error verbatim and at most ask the user whether to switch.',
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.',
1487
1246
  parameters: {
1488
- type: 'object', additionalProperties: false, required: ['prompt', 'images'],
1247
+ type: 'object', additionalProperties: false,
1489
1248
  properties: {
1490
- prompt: { type: 'string', description: 'Final edit prompt. Name each reference image (图1/图2), state exactly what to change, and state that everything else must stay unchanged.' },
1491
- images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute local paths or http(s) URLs; order matters and corresponds to 图1/图2.' },
1492
- negative_prompt: { type: 'string', description: 'Optional prompt content. Only for models that support negative prompts; list artifacts and undesired elements. Omit otherwise.' },
1493
- model: { type: 'string', description: 'Optional outside Auto mode: omit it and the picker\'s model is used. In Auto mode it is required — one id from the active provider list. A value other than the picked model is rejected; never use it to switch models.' },
1494
- provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' }
1249
+ prompt: { type: 'string', description: 'Final edit prompt: name each reference (图1/图2); state exactly what changes and that everything else stays.' },
1250
+ images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute local paths or http(s) URLs, in 图1/图2 order.' },
1251
+ 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.' },
1254
+ provider: { type: 'string', description: 'Optional. The user-selected provider; validated against the picker, never switched.' },
1255
+ params: {
1256
+ type: 'object', additionalProperties: true,
1257
+ description: 'Optional workflow params from mo_image_settings; omit unneeded ones (defaults apply); unsupported keys are ignored and reported.'
1258
+ },
1259
+ resume_job_id: { type: 'string', description: 'Optional. Resume a previously submitted async job by its jobId; no new submission is made. Leave prompt/images out unless you are starting a new task.' }
1495
1260
  }
1496
1261
  },
1497
1262
  output, timeoutMs: 360000,
1498
1263
  async execute(args, exec) {
1499
- requireSettings(exec);
1500
- const result = await edit(args, exec, store);
1501
- consumeSettings(exec);
1502
- presentImage(exec, result);
1503
- return result.note ? { path: result.file, note: result.note } : { path: result.file };
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;
1504
1282
  }
1505
1283
  });
1506
1284
  } catch (error) { logHost('edit tool register error: ' + String(error)); }