dsh-mo-image 0.6.0 → 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/CHANGELOG.md +11 -0
- package/README.md +57 -17
- package/icon.png +0 -0
- package/lib/adapter-kit.js +363 -11
- package/lib/adapters/async.js +258 -31
- package/lib/adapters/cn.js +13 -0
- package/lib/adapters/openai.js +21 -2
- package/lib/adapters.js +880 -139
- package/lib/client.js +459 -131
- package/lib/comfy-workflow.js +7 -3
- package/lib/config-store.js +692 -0
- package/lib/image-execution.js +835 -0
- package/lib/image-jobs.js +333 -0
- package/lib/image-queue.js +195 -0
- package/lib/image-service.js +226 -0
- package/lib/image-worker.js +195 -0
- package/lib/index.js +439 -858
- package/lib/png-scale.js +103 -28
- package/lib/prompt-profiles.js +139 -68
- package/lib/request-auth.js +143 -0
- package/lib/retry.js +162 -0
- package/lib/settings-memory.js +33 -0
- package/lib/status.js +187 -0
- package/locale/messages.csv +226 -214
- package/package.json +3 -1
- package/skills/mo-image-editing/SKILL.md +34 -72
- package/skills/mo-image-generation/SKILL.md +59 -152
package/lib/index.js
CHANGED
|
@@ -7,20 +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,
|
|
10
|
+
resolveAdapter, describeAdapter, fitSize, sizePolicyFor, sizeSpecFor,
|
|
11
|
+
parseSize, nearestAspect, nearestTier, sizeForAspect,
|
|
11
12
|
qualityForAdapter, qualityOptionsFor, filterImageModels,
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
listProviderModelEntries, adapterManifest, localPresetManifest, providerPresetManifest, MAX_IMAGE_BYTES,
|
|
16
|
-
adapterSupportsKind, analyzeComfyWorkflow
|
|
13
|
+
readResponseBytes, looksLikeImage, sniffType,
|
|
14
|
+
listProviderModelEntries, adapterManifest, localPresetManifest, providerPresetManifest,
|
|
15
|
+
analyzeComfyWorkflow, A1111_PARAMS
|
|
17
16
|
} from './adapters.js';
|
|
18
|
-
import {
|
|
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';
|
|
23
44
|
import { MAPPING_KEYS, DEFAULT_EXPOSED } from './comfy-workflow.js';
|
|
45
|
+
import { STATUS_CONTRACT, editCapableModels, pickAutoEditModel } from './status.js';
|
|
24
46
|
|
|
25
47
|
const PLUGIN = 'dsh-mo-image';
|
|
26
48
|
function dshHome() {
|
|
@@ -46,6 +68,10 @@ function pluginVersion() {
|
|
|
46
68
|
return '0.0.0';
|
|
47
69
|
}
|
|
48
70
|
}
|
|
71
|
+
/** 配置快照本身不知道插件版本;状态服务在这一层把版本补上。 */
|
|
72
|
+
function describeImageStatus(store) {
|
|
73
|
+
return describeImageStatusBase(store, pluginVersion());
|
|
74
|
+
}
|
|
49
75
|
const UPDATE_CHECK_TTL_MS = 12 * 60 * 60 * 1000;
|
|
50
76
|
const MAX_BODY = 8 * 1024 * 1024;
|
|
51
77
|
const MAX_REF_BYTES = 15 * 1024 * 1024;
|
|
@@ -108,518 +134,6 @@ function resolvePreviewToken(token) {
|
|
|
108
134
|
return value && typeof value.p === 'string' && path.isAbsolute(value.p) ? value.p : '';
|
|
109
135
|
} catch (_error) { return ''; }
|
|
110
136
|
}
|
|
111
|
-
function emptyConfig() {
|
|
112
|
-
return {
|
|
113
|
-
version: 1, providers: [], active: { providerId: '', model: '' },
|
|
114
|
-
defaults: { quality: 'high', auto: true, width: 1024, height: 1024, promptOptimization: true }
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
/** 质量值由适配器的 options 决定;这里只保留旧配置里的合法字符串,具体对齐交给 adapter。 */
|
|
118
|
-
const QUALITY_VALUES = new Set(['off', 'low', 'medium', 'high', 'xhigh', 'max', 'auto', 'standard', 'hd', 'default', 'quality', 'turbo']);
|
|
119
|
-
function normalizeQuality(value) {
|
|
120
|
-
const raw = String(value || '').trim().toLowerCase();
|
|
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 = 2000000;
|
|
155
|
-
/**
|
|
156
|
-
* 映射要么完整,要么没有:任何一项形状不对就整体丢弃,
|
|
157
|
-
* 免得生成时一半注入一半不注入,产出用户看不懂的图。
|
|
158
|
-
*/
|
|
159
|
-
function sanitizeMapping(raw) {
|
|
160
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
|
|
161
|
-
const out = {};
|
|
162
|
-
for (const key of MAPPING_KEYS) {
|
|
163
|
-
if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
|
|
164
|
-
const value = raw[key];
|
|
165
|
-
if (value === null) { out[key] = null; continue; }
|
|
166
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
|
|
167
|
-
const node = typeof value.node === 'string' ? value.node.trim() : '';
|
|
168
|
-
const input = typeof value.input === 'string' ? value.input.trim() : '';
|
|
169
|
-
if (!node || !input) return undefined;
|
|
170
|
-
out[key] = { node, input };
|
|
171
|
-
}
|
|
172
|
-
return Object.keys(out).length ? out : undefined;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* 可调参数清单来自解析结果,形状固定:name/node/input/type/default[/options]。
|
|
177
|
-
* 任何一项不合法就整体丢弃——宁可不让模型看到,也不要报一个假的默认值。
|
|
178
|
-
*/
|
|
179
|
-
function sanitizeParams(raw) {
|
|
180
|
-
if (!Array.isArray(raw)) return undefined;
|
|
181
|
-
const out = [];
|
|
182
|
-
for (const item of raw) {
|
|
183
|
-
if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
|
|
184
|
-
const name = typeof item.name === 'string' ? item.name.trim() : '';
|
|
185
|
-
const node = typeof item.node === 'string' ? item.node.trim() : '';
|
|
186
|
-
const input = typeof item.input === 'string' ? item.input.trim() : '';
|
|
187
|
-
if (!name || !node || !input) return undefined;
|
|
188
|
-
const param = { name, node, input, type: String(item.type || 'string') };
|
|
189
|
-
if (Array.isArray(item.options)) param.options = item.options.map(String).slice(0, 64);
|
|
190
|
-
if (item.role === true) param.role = true;
|
|
191
|
-
if (item.expose === false) param.expose = false;
|
|
192
|
-
if (Array.isArray(item.candidates)) {
|
|
193
|
-
const seen = new Set();
|
|
194
|
-
param.candidates = [];
|
|
195
|
-
for (const candidate of item.candidates) {
|
|
196
|
-
if (!candidate || typeof candidate !== 'object') continue;
|
|
197
|
-
const node = typeof candidate.node === 'string' ? candidate.node.trim() : '';
|
|
198
|
-
const input = typeof candidate.input === 'string' ? candidate.input.trim() : '';
|
|
199
|
-
const key = node + '::' + input;
|
|
200
|
-
if (!node || !input || seen.has(key)) continue;
|
|
201
|
-
seen.add(key);
|
|
202
|
-
param.candidates.push({ node, input });
|
|
203
|
-
}
|
|
204
|
-
if (!param.candidates.length) delete param.candidates;
|
|
205
|
-
}
|
|
206
|
-
out.push(param);
|
|
207
|
-
}
|
|
208
|
-
return out.length ? out : undefined;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
/** 逐项暴露开关:只存布尔值,未出现的项按角色/可调参数各自默认。 */
|
|
212
|
-
function sanitizeExpose(raw) {
|
|
213
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
|
|
214
|
-
const out = {};
|
|
215
|
-
for (const [key, value] of Object.entries(raw)) {
|
|
216
|
-
const name = String(key || '').trim();
|
|
217
|
-
if (!name || typeof value !== 'boolean') continue;
|
|
218
|
-
out[name] = value;
|
|
219
|
-
}
|
|
220
|
-
return Object.keys(out).length ? out : undefined;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
export function normalizeModelOptions(raw, models) {
|
|
224
|
-
const out = {};
|
|
225
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
|
|
226
|
-
const allowed = new Set(Array.isArray(models) ? models : []);
|
|
227
|
-
for (const model of Object.keys(raw)) {
|
|
228
|
-
if (!allowed.has(model)) continue;
|
|
229
|
-
const entry = raw[model];
|
|
230
|
-
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
|
|
231
|
-
const workflow = typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
|
|
232
|
-
if (!workflow || workflow.length > MODEL_WORKFLOW_MAX) continue;
|
|
233
|
-
const mapping = sanitizeMapping(entry.mapping);
|
|
234
|
-
const params = sanitizeParams(entry.params);
|
|
235
|
-
const expose = sanitizeExpose(entry.expose);
|
|
236
|
-
const next = { workflow };
|
|
237
|
-
if (mapping) next.mapping = mapping;
|
|
238
|
-
if (params) next.params = params;
|
|
239
|
-
if (expose) next.expose = expose;
|
|
240
|
-
out[model] = next;
|
|
241
|
-
}
|
|
242
|
-
return out;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
export function normalizeConfig(raw) {
|
|
246
|
-
const out = emptyConfig();
|
|
247
|
-
if (!raw || typeof raw !== 'object') return out;
|
|
248
|
-
const providers = Array.isArray(raw.providers) ? raw.providers : [];
|
|
249
|
-
for (const item of providers) {
|
|
250
|
-
if (!item || typeof item !== 'object') continue;
|
|
251
|
-
const models = Array.from(new Set((Array.isArray(item.models) ? item.models : [])
|
|
252
|
-
.map((m) => String(m || '').trim()).filter(Boolean)));
|
|
253
|
-
const names = {};
|
|
254
|
-
if (item.names && typeof item.names === 'object') for (const model of models) if (typeof item.names[model] === 'string') names[model] = item.names[model];
|
|
255
|
-
const modelOptions = normalizeModelOptions(item.modelOptions, models);
|
|
256
|
-
const key = String(item.key || '');
|
|
257
|
-
const provider = {
|
|
258
|
-
id: String(item.id || randomUUID()), name: String(item.name || ''),
|
|
259
|
-
baseUrl: String(item.baseUrl || '').replace(/\/+$/, ''),
|
|
260
|
-
apiKeyEnv: validKeyRef(item.apiKeyEnv),
|
|
261
|
-
optionalKey: !!item.optionalKey,
|
|
262
|
-
protocol: String(item.protocol || 'openai-images'), adapter: String(item.adapter || ''), models, names
|
|
263
|
-
};
|
|
264
|
-
// Responses API 需要一个能调工具的主模型;只有这个适配器要留。
|
|
265
|
-
if (provider.adapter === 'openai-responses') {
|
|
266
|
-
const hostModel = String(item.hostModel || '').trim();
|
|
267
|
-
if (hostModel) provider.hostModel = hostModel;
|
|
268
|
-
}
|
|
269
|
-
// 自定义工作流只有 ComfyUI 适配器会读;别的提供商留着也没用,直接丢弃。
|
|
270
|
-
if (provider.adapter === 'comfyui' && Object.keys(modelOptions).length > 0) provider.modelOptions = modelOptions;
|
|
271
|
-
if (key) provider.key = key;
|
|
272
|
-
out.providers.push(provider);
|
|
273
|
-
}
|
|
274
|
-
const wanted = raw.active && typeof raw.active === 'object' ? raw.active : {};
|
|
275
|
-
const provider = out.providers.find((p) => p.id === wanted.providerId);
|
|
276
|
-
// "auto" 是选择器里的特殊行:允许对话模型在提供商列表内自选模型。
|
|
277
|
-
const wantedModel = String(wanted.model || '').trim();
|
|
278
|
-
const keepModel = wantedModel === 'auto' || (provider && provider.models.includes(wantedModel));
|
|
279
|
-
out.active = { providerId: provider ? provider.id : '', model: keepModel ? wantedModel : '' };
|
|
280
|
-
out.defaults = normalizeDefaults(raw.defaults);
|
|
281
|
-
return out;
|
|
282
|
-
}
|
|
283
|
-
/** DSH 凭据库(ctx.credentials)里的引用名;只允许我们自己的 MO_IMAGE_ 命名空间。 */
|
|
284
|
-
const KEY_REF_PREFIX = 'MO_IMAGE_';
|
|
285
|
-
const KEY_REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
286
|
-
function createConfigStore(options) {
|
|
287
|
-
return {
|
|
288
|
-
configFile: options.configFile,
|
|
289
|
-
ensureDirs: options.ensureDirs,
|
|
290
|
-
logHost: options.logHost,
|
|
291
|
-
credentialsAccessor: options.credentialsAccessor,
|
|
292
|
-
cache: null,
|
|
293
|
-
stamp: '',
|
|
294
|
-
webOriginHost: '',
|
|
295
|
-
keyMigration: null,
|
|
296
|
-
writeQueue: Promise.resolve()
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
function credentialsService(store) {
|
|
300
|
-
if (!store || typeof store.credentialsAccessor !== 'function') return undefined;
|
|
301
|
-
try { return store.credentialsAccessor(); } catch (_error) { return undefined; }
|
|
302
|
-
}
|
|
303
|
-
function validKeyRef(value) {
|
|
304
|
-
const ref = String(value || '').trim();
|
|
305
|
-
return KEY_REF_PATTERN.test(ref) && ref.startsWith(KEY_REF_PREFIX) ? ref : '';
|
|
306
|
-
}
|
|
307
|
-
/** 按 provider id 生成稳定的环境变量名,例如 MO_IMAGE_P_ABC_API_KEY。 */
|
|
308
|
-
function deriveKeyRef(id, used) {
|
|
309
|
-
const stem = String(id || 'provider').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'PROVIDER';
|
|
310
|
-
const base = KEY_REF_PREFIX + stem + '_API_KEY';
|
|
311
|
-
let ref = base;
|
|
312
|
-
for (let n = 2; used && used.has(ref); n++) ref = base.replace(/_API_KEY$/, '_' + n + '_API_KEY');
|
|
313
|
-
return ref;
|
|
314
|
-
}
|
|
315
|
-
function hasLegacyKeys(config) {
|
|
316
|
-
return (config.providers || []).some((provider) => provider.key || !validKeyRef(provider.apiKeyEnv));
|
|
317
|
-
}
|
|
318
|
-
/** describe() 的 configured 也可能来自环境变量;只有不是 env fallback 才算已存进凭据库。 */
|
|
319
|
-
function credentialIsStored(info) {
|
|
320
|
-
if (!info || !info.configured) return false;
|
|
321
|
-
const source = String(info.source || '');
|
|
322
|
-
return source !== 'env' && source !== 'project-env' && source !== 'user-env';
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
function requestHostName(req) {
|
|
326
|
-
const raw = String((req.headers && req.headers.host) || '').trim().toLowerCase();
|
|
327
|
-
if (!raw) return '';
|
|
328
|
-
const withoutPort = raw.replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
|
|
329
|
-
return withoutPort;
|
|
330
|
-
}
|
|
331
|
-
/**
|
|
332
|
-
* 配置写接口是本插件自己的本地 HTTP 路由,不走 DSH 的 remote 权限层,所以
|
|
333
|
-
* 至少挡掉跨站浏览器请求和 DNS rebinding:Host 必须是回环、IP 字面量或
|
|
334
|
-
* DSH_WEB_URL 公布的域名;Origin 必须同源;POST 必须是 application/json。
|
|
335
|
-
* 同一 OS 用户的进程本来就能读凭据文件,这里不是对抗同 UID 进程的边界。
|
|
336
|
-
*/
|
|
337
|
-
function assertLocalRequest(store, req, write) {
|
|
338
|
-
const hostName = requestHostName(req);
|
|
339
|
-
if (!hostName) {
|
|
340
|
-
const error = new Error('missing Host header'); error.status = 403; throw error;
|
|
341
|
-
}
|
|
342
|
-
const allowed = new Set(['127.0.0.1', 'localhost', '::1']);
|
|
343
|
-
for (const value of [process.env.DSH_WEB_URL, store && store.webOriginHost]) {
|
|
344
|
-
try {
|
|
345
|
-
const parsed = new URL(String(value || ''));
|
|
346
|
-
if (parsed.hostname) allowed.add(parsed.hostname.toLowerCase());
|
|
347
|
-
} catch (_error) { /* ignore */ }
|
|
348
|
-
}
|
|
349
|
-
if (!allowed.has(hostName) && isIP(hostName) === 0) {
|
|
350
|
-
const error = new Error('unexpected Host header'); error.status = 403; throw error;
|
|
351
|
-
}
|
|
352
|
-
const origin = req.headers && req.headers.origin;
|
|
353
|
-
if (origin !== undefined) {
|
|
354
|
-
let originUrl;
|
|
355
|
-
try { originUrl = new URL(String(origin)); } catch (_error) {
|
|
356
|
-
const error = new Error('invalid Origin'); error.status = 403; throw error;
|
|
357
|
-
}
|
|
358
|
-
const hostHeader = String(req.headers.host || '').toLowerCase();
|
|
359
|
-
if (originUrl.host.toLowerCase() !== hostHeader) {
|
|
360
|
-
const error = new Error('cross-origin request rejected'); error.status = 403; throw error;
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
const site = req.headers && req.headers['sec-fetch-site'];
|
|
364
|
-
if (site && site !== 'same-origin' && site !== 'none') {
|
|
365
|
-
const error = new Error('cross-site request rejected'); error.status = 403; throw error;
|
|
366
|
-
}
|
|
367
|
-
if (write) {
|
|
368
|
-
const type = String((req.headers && req.headers['content-type']) || '').toLowerCase();
|
|
369
|
-
if (!type.startsWith('application/json')) {
|
|
370
|
-
const error = new Error('content-type must be application/json'); error.status = 415; throw error;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
/** 系统提示词节是同步渲染的,这里用 mtime 缓存一份配置副本。 */
|
|
375
|
-
function rememberConfig(store, config) {
|
|
376
|
-
store.cache = config;
|
|
377
|
-
store.stamp = '';
|
|
378
|
-
}
|
|
379
|
-
function readConfigSync(store) {
|
|
380
|
-
try {
|
|
381
|
-
const info = statSync(store.configFile);
|
|
382
|
-
const stamp = info.mtimeMs + ':' + info.size;
|
|
383
|
-
if (!store.cache || stamp !== store.stamp) {
|
|
384
|
-
store.cache = normalizeConfig(JSON.parse(readFileSync(store.configFile, 'utf8')));
|
|
385
|
-
store.stamp = stamp;
|
|
386
|
-
}
|
|
387
|
-
} catch (_error) {
|
|
388
|
-
if (!store.cache) store.cache = emptyConfig();
|
|
389
|
-
}
|
|
390
|
-
return store.cache;
|
|
391
|
-
}
|
|
392
|
-
/** 当前选中的生图模型;编辑也用同一个(严格模式,不做任何回退)。 */
|
|
393
|
-
function activeImageState(store) {
|
|
394
|
-
const config = readConfigSync(store);
|
|
395
|
-
const provider = (config.providers || []).find((item) => item.id === config.active.providerId);
|
|
396
|
-
const model = String((config.active && config.active.model) || '').trim();
|
|
397
|
-
if (!provider || !model) return null;
|
|
398
|
-
let adapter = null;
|
|
399
|
-
try { adapter = resolveAdapter(provider, model); } catch (_error) { adapter = null; }
|
|
400
|
-
return {
|
|
401
|
-
provider, model, adapter, models: provider.models || [],
|
|
402
|
-
editModel: model, editAdapter: adapter,
|
|
403
|
-
// 只有 ComfyUI 部署才有工作流参数;用户关掉暴露时不返回。
|
|
404
|
-
workflowParams: workflowParamsOf(provider, model, adapter),
|
|
405
|
-
promptOptimization: config.defaults.promptOptimization !== false, defaults: config.defaults
|
|
406
|
-
};
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/** 当前模型的工作流可调参数;非 ComfyUI 或用户逐项关闭时不返回。 */
|
|
410
|
-
/** 当前模型的 ComfyUI 工作流参数;角色参数默认暴露,可调参数默认不暴露。 */
|
|
411
|
-
export function workflowParamsOf(provider, model, adapter) {
|
|
412
|
-
try {
|
|
413
|
-
if (!adapter || adapter.id !== 'comfyui') return undefined;
|
|
414
|
-
const entry = provider && provider.modelOptions ? provider.modelOptions[model] : null;
|
|
415
|
-
if (!entry || !Array.isArray(entry.params)) return undefined;
|
|
416
|
-
const expose = entry.expose && typeof entry.expose === 'object' ? entry.expose : {};
|
|
417
|
-
const exposed = entry.params.filter((param) => {
|
|
418
|
-
if (!param) return false;
|
|
419
|
-
const explicit = expose[param.name];
|
|
420
|
-
if (explicit !== undefined) return explicit !== false;
|
|
421
|
-
return DEFAULT_EXPOSED.has(param.name);
|
|
422
|
-
});
|
|
423
|
-
return exposed.length ? exposed : undefined;
|
|
424
|
-
} catch (_error) { return undefined; }
|
|
425
|
-
}
|
|
426
|
-
function canUseCredentials(store) {
|
|
427
|
-
const credentials = credentialsService(store);
|
|
428
|
-
return !!(credentials && typeof credentials.describe === 'function' && typeof credentials.resolve === 'function' && typeof credentials.set === 'function');
|
|
429
|
-
}
|
|
430
|
-
/** 浏览器只拿 hasKey/keySource,永远拿不到明文密钥。 */
|
|
431
|
-
async function publicConfig(store, config) {
|
|
432
|
-
const credentials = credentialsService(store);
|
|
433
|
-
const providers = await Promise.all((config.providers || []).map(async (provider) => {
|
|
434
|
-
const copy = Object.assign({}, provider);
|
|
435
|
-
delete copy.key;
|
|
436
|
-
const ref = validKeyRef(provider.apiKeyEnv);
|
|
437
|
-
let hasKey = false;
|
|
438
|
-
let keySource = '';
|
|
439
|
-
if (ref && credentials && typeof credentials.describe === 'function') {
|
|
440
|
-
try {
|
|
441
|
-
const info = await credentials.describe(ref);
|
|
442
|
-
hasKey = !!info.configured;
|
|
443
|
-
keySource = info.source || '';
|
|
444
|
-
} catch (error) { store.logHost('credential describe failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
|
|
445
|
-
}
|
|
446
|
-
if (!hasKey && ref && process.env[ref]) { hasKey = true; keySource = 'env'; }
|
|
447
|
-
if (!hasKey && provider.key) { hasKey = true; keySource = 'config'; }
|
|
448
|
-
return Object.assign(copy, { hasKey: hasKey, keySource: keySource });
|
|
449
|
-
}));
|
|
450
|
-
return Object.assign({}, config, { providers: providers });
|
|
451
|
-
}
|
|
452
|
-
/** 选择器用的模型能力表:目前先下发每个模型可用的质量档位。 */
|
|
453
|
-
function capabilityManifest(config) {
|
|
454
|
-
return (config.providers || []).map((provider) => ({
|
|
455
|
-
providerId: provider.id,
|
|
456
|
-
models: (provider.models || []).map((model) => {
|
|
457
|
-
let quality = null;
|
|
458
|
-
try { quality = qualityOptionsFor(resolveAdapter(provider, model), model); } catch (_error) { quality = null; }
|
|
459
|
-
return { model: model, quality: quality };
|
|
460
|
-
})
|
|
461
|
-
}));
|
|
462
|
-
}
|
|
463
|
-
/**
|
|
464
|
-
* 把旧版 config.json 里的明文 key 迁到 DSH 凭据库,并在配置里只留下 apiKeyEnv 引用。
|
|
465
|
-
* 凭据服务不存在(自定义 composition)时保持旧字段,避免把用户锁死。
|
|
466
|
-
*/
|
|
467
|
-
async function migrateConfigKeys(store, input) {
|
|
468
|
-
if (!canUseCredentials(store)) return input;
|
|
469
|
-
const credentials = credentialsService(store);
|
|
470
|
-
const config = normalizeConfig(input);
|
|
471
|
-
const used = new Set();
|
|
472
|
-
let migrated = 0;
|
|
473
|
-
let changed = false;
|
|
474
|
-
for (const provider of config.providers) {
|
|
475
|
-
let ref = validKeyRef(provider.apiKeyEnv);
|
|
476
|
-
if (!ref) {
|
|
477
|
-
ref = deriveKeyRef(provider.id, used);
|
|
478
|
-
provider.apiKeyEnv = ref;
|
|
479
|
-
changed = true;
|
|
480
|
-
} else if (used.has(ref)) {
|
|
481
|
-
ref = deriveKeyRef(provider.id, used);
|
|
482
|
-
provider.apiKeyEnv = ref;
|
|
483
|
-
changed = true;
|
|
484
|
-
}
|
|
485
|
-
used.add(ref);
|
|
486
|
-
if (!provider.key) continue;
|
|
487
|
-
try {
|
|
488
|
-
const info = await credentials.describe(ref);
|
|
489
|
-
if (!credentialIsStored(info)) {
|
|
490
|
-
await credentials.set(ref, provider.key);
|
|
491
|
-
migrated++;
|
|
492
|
-
}
|
|
493
|
-
delete provider.key;
|
|
494
|
-
changed = true;
|
|
495
|
-
} catch (error) {
|
|
496
|
-
store.logHost('credential migration failed for provider ' + provider.id + ': ' + String(error && error.message ? error.message : error));
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
if (!changed) return config;
|
|
500
|
-
const saved = await writeConfig(store, config);
|
|
501
|
-
if (migrated > 0) store.logHost('migrated ' + migrated + ' API key(s) to credentials store');
|
|
502
|
-
return saved;
|
|
503
|
-
}
|
|
504
|
-
function migrateKeysOnce(store, config) {
|
|
505
|
-
if (!store.keyMigration) store.keyMigration = migrateConfigKeys(store, config).finally(() => { store.keyMigration = null; });
|
|
506
|
-
return store.keyMigration;
|
|
507
|
-
}
|
|
508
|
-
async function readConfig(store) {
|
|
509
|
-
try {
|
|
510
|
-
if (!existsSync(store.configFile)) {
|
|
511
|
-
const empty = emptyConfig();
|
|
512
|
-
rememberConfig(store, empty);
|
|
513
|
-
return empty;
|
|
514
|
-
}
|
|
515
|
-
let config = normalizeConfig(JSON.parse(await readFile(store.configFile, 'utf8')));
|
|
516
|
-
if (hasLegacyKeys(config) && canUseCredentials(store)) {
|
|
517
|
-
try { config = await migrateKeysOnce(store, config); } catch (error) { store.logHost('config key migration failed: ' + String(error && error.message ? error.message : error)); }
|
|
518
|
-
}
|
|
519
|
-
rememberConfig(store, config);
|
|
520
|
-
return config;
|
|
521
|
-
} catch (_error) { return emptyConfig(); }
|
|
522
|
-
}
|
|
523
|
-
async function writeConfig(store, config) {
|
|
524
|
-
const next = normalizeConfig(config);
|
|
525
|
-
const task = store.writeQueue.then(async () => {
|
|
526
|
-
store.ensureDirs();
|
|
527
|
-
const tempFile = store.configFile + '.tmp-' + process.pid + '-' + randomUUID().slice(0, 8);
|
|
528
|
-
try {
|
|
529
|
-
await writeFile(tempFile, JSON.stringify(next, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
530
|
-
await rename(tempFile, store.configFile);
|
|
531
|
-
} finally {
|
|
532
|
-
try { await unlink(tempFile); } catch (_error) { /* rename 成功后临时文件已不存在 */ }
|
|
533
|
-
}
|
|
534
|
-
rememberConfig(store, next);
|
|
535
|
-
return next;
|
|
536
|
-
});
|
|
537
|
-
store.writeQueue = task.catch(() => {});
|
|
538
|
-
return task;
|
|
539
|
-
}
|
|
540
|
-
/** 每次请求才解析一次密钥;不在内存里长期缓存,轮换后下一请求生效。 */
|
|
541
|
-
async function resolveProviderCredential(store, provider) {
|
|
542
|
-
const ref = validKeyRef(provider.apiKeyEnv);
|
|
543
|
-
const credentials = credentialsService(store);
|
|
544
|
-
if (ref) {
|
|
545
|
-
if (credentials && typeof credentials.resolve === 'function') {
|
|
546
|
-
try {
|
|
547
|
-
const hit = await credentials.resolve(ref);
|
|
548
|
-
if (hit && typeof hit.value === 'string' && hit.value.trim().length > 0) {
|
|
549
|
-
return Object.assign({}, provider, { key: hit.value.trim() });
|
|
550
|
-
}
|
|
551
|
-
} catch (error) { store.logHost('credential resolve failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
|
|
552
|
-
}
|
|
553
|
-
const env = process.env[ref];
|
|
554
|
-
if (env && env.trim()) return Object.assign({}, provider, { key: env.trim() });
|
|
555
|
-
}
|
|
556
|
-
if (provider.key) return provider;
|
|
557
|
-
if (provider.optionalKey) return provider;
|
|
558
|
-
throw localizedError(
|
|
559
|
-
new Error('生图提供商「' + (provider.name || provider.id) + '」缺少 API Key,请到 DSH 设置 → 生图模型填写'
|
|
560
|
-
+ (ref ? '(凭据 ' + ref + ')' : '') + '。'),
|
|
561
|
-
ref ? 'provider.missingKeyWithRef' : 'provider.missingKey',
|
|
562
|
-
{ provider: provider.name || provider.id, ref: ref }
|
|
563
|
-
);
|
|
564
|
-
}
|
|
565
|
-
/** 保存配置前先把每个 provider 的新 key 写进凭据库,配置文件只保留 apiKeyEnv。 */
|
|
566
|
-
async function saveConfigWithCredentials(store, raw) {
|
|
567
|
-
const incoming = normalizeConfig(raw);
|
|
568
|
-
const current = await readConfig(store);
|
|
569
|
-
const credentials = credentialsService(store);
|
|
570
|
-
const canStore = !!(credentials && typeof credentials.set === 'function');
|
|
571
|
-
const canDescribe = !!(credentials && typeof credentials.describe === 'function');
|
|
572
|
-
const currentById = new Map(current.providers.map((provider) => [provider.id, provider]));
|
|
573
|
-
const used = new Set();
|
|
574
|
-
const providers = [];
|
|
575
|
-
for (const provider of incoming.providers) {
|
|
576
|
-
const old = currentById.get(provider.id);
|
|
577
|
-
let ref = validKeyRef(provider.apiKeyEnv) || validKeyRef(old && old.apiKeyEnv) || deriveKeyRef(provider.id, used);
|
|
578
|
-
if (used.has(ref)) ref = deriveKeyRef(provider.id, used);
|
|
579
|
-
used.add(ref);
|
|
580
|
-
provider.apiKeyEnv = ref;
|
|
581
|
-
const newKey = String(provider.key || '').trim();
|
|
582
|
-
delete provider.key;
|
|
583
|
-
if (newKey) {
|
|
584
|
-
if (!canStore) throw localizedError(new Error('DSH 凭据服务未挂载,无法安全保存 API Key;请确认 base composition 包含 dsh-credentials-local。'), 'config.credentialsUnavailable');
|
|
585
|
-
try {
|
|
586
|
-
await credentials.set(ref, newKey);
|
|
587
|
-
} catch (error) {
|
|
588
|
-
const message = String(error && error.message ? error.message : error);
|
|
589
|
-
throw localizedError(new Error('保存 API Key 失败:' + message), 'config.credentialSaveFailed', { message: message });
|
|
590
|
-
}
|
|
591
|
-
} else if (old && old.key) {
|
|
592
|
-
if (canStore && canDescribe) {
|
|
593
|
-
try {
|
|
594
|
-
const info = await credentials.describe(ref);
|
|
595
|
-
if (!credentialIsStored(info)) await credentials.set(ref, old.key);
|
|
596
|
-
} catch (error) {
|
|
597
|
-
const message = String(error && error.message ? error.message : error);
|
|
598
|
-
throw localizedError(new Error('旧 API Key 迁移失败:' + message), 'config.legacyKeyMigrationFailed', { message: message });
|
|
599
|
-
}
|
|
600
|
-
} else {
|
|
601
|
-
provider.key = old.key;
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
providers.push(provider);
|
|
605
|
-
}
|
|
606
|
-
if (credentials && typeof credentials.unset === 'function') {
|
|
607
|
-
const kept = new Set(providers.map((provider) => provider.id));
|
|
608
|
-
for (const old of current.providers) {
|
|
609
|
-
if (kept.has(old.id)) continue;
|
|
610
|
-
const ref = validKeyRef(old.apiKeyEnv);
|
|
611
|
-
if (!ref || used.has(ref)) continue;
|
|
612
|
-
try { await credentials.unset(ref); } catch (error) { store.logHost('credential removal failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
incoming.providers = providers;
|
|
616
|
-
try {
|
|
617
|
-
return await writeConfig(store, incoming);
|
|
618
|
-
} catch (error) {
|
|
619
|
-
const message = String(error && error.message ? error.message : error);
|
|
620
|
-
throw localizedError(new Error('保存生图配置失败:' + message), 'config.writeFailed', { message: message });
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
137
|
function sendJson(res, status, value) {
|
|
624
138
|
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
625
139
|
res.end(JSON.stringify(value));
|
|
@@ -663,13 +177,28 @@ function pickProvider(config, purpose, args) {
|
|
|
663
177
|
}
|
|
664
178
|
let model;
|
|
665
179
|
if (activeModel === 'auto') {
|
|
666
|
-
if (
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
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;
|
|
671
201
|
}
|
|
672
|
-
model = requestedModel;
|
|
673
202
|
} else {
|
|
674
203
|
if (requestedModel && requestedModel !== activeModel) {
|
|
675
204
|
throw new Error('当前选中的模型是 ' + activeModel + '(提供商 ' + (provider.name || provider.id) + '),请求的是 ' + requestedModel + '。模型只能由用户在设置里切换。');
|
|
@@ -677,21 +206,18 @@ function pickProvider(config, purpose, args) {
|
|
|
677
206
|
model = activeModel;
|
|
678
207
|
}
|
|
679
208
|
if (!(provider.models || []).includes(model)) {
|
|
680
|
-
if (provider.models && provider.models.length) throw new Error('当前模型不在提供商的模型目录里,请到设置 → 生图模型补全。'
|
|
209
|
+
if (provider.models && provider.models.length) throw new Error('当前模型不在提供商的模型目录里,请到设置 → 生图模型补全。');
|
|
681
210
|
throw new Error('当前提供商还没有模型 ID,请到设置 → 生图模型添加并选择模型。');
|
|
682
211
|
}
|
|
212
|
+
// 固定模型改图:提前说清楚,别等调用上游才报错。
|
|
213
|
+
if (purpose === 'edit' && editCapableModels(provider, [model]).length === 0) {
|
|
214
|
+
throw new Error('该模型不支持图生图:' + model + '。请到设置 → 生图模型换一个支持编辑的模型。');
|
|
215
|
+
}
|
|
683
216
|
// 协议/适配器解析交给 resolveAdapter():不同模型族的请求形状由适配器描述符定义。
|
|
684
217
|
// API Key 由 resolveProviderCredential() 在请求前从 DSH 凭据库解析,不在这里检查。
|
|
685
218
|
if (!provider.baseUrl) throw new Error('生图提供商缺少 API 地址,请到设置 → 生图模型补全。');
|
|
686
219
|
return { provider, model };
|
|
687
220
|
}
|
|
688
|
-
function safeExt(contentType) {
|
|
689
|
-
const type = String(contentType || '').toLowerCase();
|
|
690
|
-
if (type.includes('jpeg') || type.includes('jpg')) return 'jpg';
|
|
691
|
-
if (type.includes('webp')) return 'webp';
|
|
692
|
-
if (type.includes('gif')) return 'gif';
|
|
693
|
-
return 'png';
|
|
694
|
-
}
|
|
695
221
|
function makeSignal(exec, timeoutMs) {
|
|
696
222
|
const signals = [];
|
|
697
223
|
if (exec && exec.signal) signals.push(exec.signal);
|
|
@@ -699,255 +225,110 @@ function makeSignal(exec, timeoutMs) {
|
|
|
699
225
|
if (!signals.length) return undefined;
|
|
700
226
|
return signals.length > 1 && AbortSignal.any ? AbortSignal.any(signals) : signals[0];
|
|
701
227
|
}
|
|
702
|
-
function sleep(ms) {
|
|
703
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
704
|
-
}
|
|
705
|
-
function safeJson(buffer) {
|
|
706
|
-
try { return JSON.parse(buffer.toString('utf8')); } catch (_error) { return null; }
|
|
707
|
-
}
|
|
708
|
-
function sizeLabel(fitted) {
|
|
709
|
-
if (!fitted) return '';
|
|
710
|
-
if (fitted.omit || fitted.size === 'none') return 'auto';
|
|
711
|
-
if (fitted.size === 'auto') return fitted.width && fitted.height ? fitted.width + 'x' + fitted.height : 'auto';
|
|
712
|
-
return fitted.size;
|
|
713
|
-
}
|
|
714
|
-
function imageErrorText(failure) {
|
|
715
|
-
const text = '生图接口失败:' + failure.message;
|
|
716
|
-
const suffix = '(模型与提供商只能由用户在选择器里切换)';
|
|
717
|
-
if (failure.kind === 'size') return text + '(该模型对尺寸有最小/最大像素限制,换一个尺寸或换支持该尺寸的模型)' + suffix;
|
|
718
|
-
if (failure.kind === 'auth') return text + '(检查 API Key 与地址是否正确)' + suffix;
|
|
719
|
-
if (failure.kind === 'param') return text + '(请求参数与模型不兼容)' + suffix;
|
|
720
|
-
return text + suffix;
|
|
721
|
-
}
|
|
722
228
|
/**
|
|
723
|
-
*
|
|
724
|
-
*
|
|
229
|
+
* 上游生图任务的全局并发槽。
|
|
230
|
+
*
|
|
231
|
+
* 排队等待也算在工具总超时里(signal 已经带 timeout):用户不能看到工具卡在队列里
|
|
232
|
+
* 却一直没有截止时间。槽位只包住真正发往上游的那一段,本地参考图读取不占位。
|
|
725
233
|
*/
|
|
726
|
-
function
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
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
|
+
}
|
|
731
242
|
}
|
|
732
243
|
/**
|
|
733
|
-
*
|
|
734
|
-
*
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
* 异步入队型:提交任务 → 轮询到 SUCCEEDED → 下载图片。
|
|
738
|
-
* 提交阶段的参数错误照旧自愈(摘字段 / 抬尺寸),轮询阶段只对 429、5xx 继续等。
|
|
244
|
+
* 恢复一个已经提交过的异步任务:不重新提交,只沿任务日志里的
|
|
245
|
+
* submission / taskId / pollTarget 继续轮询并下载。
|
|
246
|
+
*
|
|
247
|
+
* 只支持异步任务;同步任务没有可查询的远端状态,任务日志也不会为它们落盘。
|
|
739
248
|
*/
|
|
740
|
-
async function
|
|
741
|
-
const
|
|
742
|
-
if (
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
let submission = null;
|
|
748
|
-
let lastFailure = null;
|
|
749
|
-
let lastNote = '';
|
|
750
|
-
let retries = 0;
|
|
751
|
-
|
|
752
|
-
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
753
|
-
const attemptInput = Object.assign({}, input, { fitted: fitted });
|
|
754
|
-
const built = phase
|
|
755
|
-
? await preparePhaseAsync(adapter, provider, attemptInput, signal)
|
|
756
|
-
: prepareAsync(adapter, provider, attemptInput, drops);
|
|
757
|
-
if (built.note) lastNote = built.note;
|
|
758
|
-
const submitUrl = /^https?:\/\//i.test(built.path) ? built.path : adapterBase(provider) + built.path;
|
|
759
|
-
const response = await request(submitUrl, {
|
|
760
|
-
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'
|
|
761
256
|
});
|
|
762
|
-
const buffer = await readResponseBytes(response, 2 * 1024 * 1024);
|
|
763
|
-
if (response.ok) {
|
|
764
|
-
submission = safeJson(buffer);
|
|
765
|
-
break;
|
|
766
|
-
}
|
|
767
|
-
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
768
|
-
lastFailure = failure;
|
|
769
|
-
logHost(kind + ' async submit ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
|
|
770
|
-
const capability = unsupportedModelMessage(kind, failure);
|
|
771
|
-
if (capability) throw new Error(capability);
|
|
772
|
-
|
|
773
|
-
if (failure.kind === 'param' && failure.drop && !drops.has(failure.drop)) {
|
|
774
|
-
drops.add(failure.drop);
|
|
775
|
-
logHost(kind + ' async drop param "' + failure.drop + '"');
|
|
776
|
-
continue;
|
|
777
|
-
}
|
|
778
|
-
if (failure.kind === 'size') {
|
|
779
|
-
const next = escalateSize(adapter, fitted);
|
|
780
|
-
if (next.size !== fitted.size) {
|
|
781
|
-
fitted = next;
|
|
782
|
-
logHost(kind + ' async size escalate → ' + next.size);
|
|
783
|
-
continue;
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
if (failure.retryable && retries < 2) {
|
|
787
|
-
retries++;
|
|
788
|
-
logHost(kind + ' async submit retry #' + retries + ' in ' + (600 * retries) + 'ms');
|
|
789
|
-
await sleep(600 * retries);
|
|
790
|
-
continue;
|
|
791
|
-
}
|
|
792
|
-
throw new Error(imageErrorText(failure));
|
|
793
257
|
}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
const taskId = phase ? String(submission.id || '') : readTaskId(adapter, submission);
|
|
797
|
-
if (!phase && !taskId) throw new Error('任务提交后没有拿到 task_id:' + JSON.stringify(submission).slice(0, 200));
|
|
798
|
-
logHost(kind + ' async task=' + (taskId || 'unknown') + ' submitted');
|
|
258
|
+
const config = snapshot || await readConfig(store);
|
|
259
|
+
const defaults = (config && config.defaults) || {};
|
|
799
260
|
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
const headers = phase && typeof phase.pollHeaders === 'function' ? phase.pollHeaders(provider) : pollHeaders(provider);
|
|
808
|
-
const response = await request(target, {
|
|
809
|
-
method: 'GET', headers: headers, signal: signal
|
|
810
|
-
});
|
|
811
|
-
const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
812
|
-
// fal 用 202 表示「还在跑」,不能当成错误。
|
|
813
|
-
if (phase && response.status === 202) {
|
|
814
|
-
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
815
|
-
continue;
|
|
816
|
-
}
|
|
817
|
-
const payload = safeJson(buffer);
|
|
818
|
-
if (!response.ok || !payload) {
|
|
819
|
-
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
820
|
-
if (failure.retryable) continue;
|
|
821
|
-
throw new Error(imageErrorText(failure));
|
|
822
|
-
}
|
|
823
|
-
state = phase ? phase.statusOf(payload) : readTaskState(adapter, payload);
|
|
824
|
-
if (state.state === 'success') {
|
|
825
|
-
if (phase) {
|
|
826
|
-
const resolved = await phase.resolve(payload, provider, signal, submission);
|
|
827
|
-
if (!resolved) throw new Error('生图任务没有返回图片');
|
|
828
|
-
const image = resolved.bytes ? resolved : await fetchImageUrl(resolved.url, signal);
|
|
829
|
-
logHost(kind + ' async task=' + (taskId || 'unknown') + ' done');
|
|
830
|
-
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType, note: lastNote };
|
|
831
|
-
}
|
|
832
|
-
const decoded = decodeImagePayload(state.node, null);
|
|
833
|
-
const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
|
|
834
|
-
logHost(kind + ' async task=' + taskId + ' done');
|
|
835
|
-
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType };
|
|
836
|
-
}
|
|
837
|
-
if (state.state === 'failure') {
|
|
838
|
-
throw new Error('生图任务失败(' + state.status + '):' + state.message);
|
|
839
|
-
}
|
|
840
|
-
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
|
+
};
|
|
841
268
|
}
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
throw new Error('该模型不支持' + (kind === 'edit' ? '图生图' : '文生图')
|
|
847
|
-
+ '(' + 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
|
+
});
|
|
848
273
|
}
|
|
849
|
-
if (
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
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
|
+
});
|
|
853
278
|
}
|
|
854
|
-
const fieldNames = (adapter.editFields && adapter.editFields.length) ? adapter.editFields : ['image'];
|
|
855
|
-
const drops = new Set();
|
|
856
|
-
let fitted = input.fitted;
|
|
857
|
-
let fieldIndex = 0;
|
|
858
|
-
let sizeRetries = 0;
|
|
859
|
-
let retries = 0;
|
|
860
|
-
let lastFailure = null;
|
|
861
279
|
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
:
|
|
866
|
-
const response = await request(adapterBase(provider) + built.path, {
|
|
867
|
-
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
|
|
868
284
|
});
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
const parsed = safeJson(buffer);
|
|
873
|
-
const decoded = parsed ? decodeImagePayload(parsed, null) : decodeImagePayload(null, buffer);
|
|
874
|
-
const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
|
|
875
|
-
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType };
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
879
|
-
lastFailure = failure;
|
|
880
|
-
logHost(kind + ' upstream ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
|
|
881
|
-
|
|
882
|
-
const capability = unsupportedModelMessage(kind, failure);
|
|
883
|
-
if (capability) throw new Error(capability);
|
|
285
|
+
}
|
|
286
|
+
const resolved = await resolveProviderCredential(store, provider);
|
|
287
|
+
const adapter = resolveAdapter(resolved, job.model);
|
|
884
288
|
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
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
|
+
}
|
|
902
311
|
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
}
|
|
909
|
-
throw new Error(imageErrorText(failure));
|
|
312
|
+
));
|
|
313
|
+
} else {
|
|
314
|
+
throw attachFailure(new Error('该任务不是异步队列任务,无法从任务日志恢复。'), {
|
|
315
|
+
code: 'job_not_resumable', phase: 'resume', jobId: job.id
|
|
316
|
+
});
|
|
910
317
|
}
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
let fitted = result.fitted;
|
|
918
|
-
let note = result && result.note ? String(result.note) : '';
|
|
919
|
-
const wanted = fitted && fitted.requested;
|
|
920
|
-
const wantedPixels = wanted ? wanted.width * wanted.height : 0;
|
|
921
|
-
const fittedPixels = fitted ? (fitted.width || 0) * (fitted.height || 0) : 0;
|
|
922
|
-
// 只有用户要的尺寸比模型实际生成的小才缩回去。用户要的更大时,
|
|
923
|
-
// 上游已经按上限生成,不能再放大冒充用户尺寸(会损失画质)。
|
|
924
|
-
if (fitted && fitted.adjusted && wanted && wanted.width && wanted.height
|
|
925
|
-
&& wanted.text !== fitted.size && fittedPixels > wantedPixels) {
|
|
926
|
-
const resized = resizeTo(bytes, wanted.width, wanted.height);
|
|
927
|
-
if (resized) {
|
|
928
|
-
bytes = resized.bytes;
|
|
929
|
-
contentType = resized.contentType;
|
|
930
|
-
logHost('resize ' + fitted.size + ' → ' + wanted.text);
|
|
931
|
-
fitted = Object.assign({}, fitted, { size: wanted.text, width: wanted.width, height: wanted.height, adjusted: false });
|
|
932
|
-
} else {
|
|
933
|
-
logHost('resize unavailable, keep ' + fitted.size + '(用户要 ' + wanted.text + ')');
|
|
934
|
-
}
|
|
935
|
-
} else if (fitted && fitted.adjusted && wanted && fittedPixels < wantedPixels) {
|
|
936
|
-
const sizeNote = '该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + wanted.text + ',未放大)。';
|
|
937
|
-
note = note ? note + ';' + sizeNote : sizeNote;
|
|
938
|
-
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;
|
|
939
324
|
}
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
const filename = 'mo-' + Date.now() + '-' + randomUUID().slice(0, 8) + '.' + ext;
|
|
948
|
-
const file = path.join(dir, filename);
|
|
949
|
-
await writeFile(file, bytes);
|
|
950
|
-
return { file, filename, provider: provider.name || provider.id, model, size, bytes: bytes.length, contentType };
|
|
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;
|
|
951
332
|
}
|
|
952
333
|
/** 只保留有值的 params;别的形状一律当没传。 */
|
|
953
334
|
function readParamsArg(args) {
|
|
@@ -961,11 +342,13 @@ function readParamsArg(args) {
|
|
|
961
342
|
return Object.keys(out).length ? out : null;
|
|
962
343
|
}
|
|
963
344
|
|
|
964
|
-
async function generate(args, exec, store) {
|
|
345
|
+
async function generate(args, exec, store, snapshot, queue, journal) {
|
|
965
346
|
const prompt = String(args.prompt || '').trim();
|
|
966
347
|
if (!prompt) throw new Error('prompt 不能为空:先按当前模型的提示词公式写好完整提示词。');
|
|
967
348
|
const negativePrompt = String(args.negative_prompt || '').trim();
|
|
968
|
-
|
|
349
|
+
// 工具入口已经把配置读成快照传进来:同一次调用里不再读第二次,
|
|
350
|
+
// 免得检查、选模型和发请求之间用户改配置,一次生图用到两套设置。
|
|
351
|
+
const config = snapshot || await readConfig(store);
|
|
969
352
|
const picked = pickProvider(config, 'generate', args);
|
|
970
353
|
const model = picked.model;
|
|
971
354
|
const provider = await resolveProviderCredential(store, picked.provider);
|
|
@@ -973,22 +356,44 @@ async function generate(args, exec, store) {
|
|
|
973
356
|
const profile = resolvePromptProfile(model, adapter);
|
|
974
357
|
const defaults = (config && config.defaults) || {};
|
|
975
358
|
const quality = qualityForAdapter(adapter, resolveQuality(defaults), model);
|
|
976
|
-
const
|
|
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;
|
|
977
364
|
if (fitted.rejected) throw new Error(fitted.reason);
|
|
978
365
|
logHost('generate adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + (fitted.adjusted ? '(' + fitted.reason + ')' : ''));
|
|
979
366
|
const signal = makeSignal(exec, 360000);
|
|
980
367
|
const extraParams = readParamsArg(args);
|
|
981
368
|
const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
|
|
982
|
-
const
|
|
983
|
-
|
|
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,
|
|
984
372
|
fitted: fitted, quality: quality, params: extraParams
|
|
985
|
-
}, signal);
|
|
986
|
-
const final =
|
|
987
|
-
const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
|
|
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
|
+
}
|
|
988
381
|
const notes = [];
|
|
382
|
+
if (stitched.note) notes.push(stitched.note);
|
|
989
383
|
if (final.note) notes.push(final.note);
|
|
384
|
+
if (requested.note) notes.push(requested.note);
|
|
385
|
+
if (fitted.reason) notes.push('尺寸 ' + fitted.reason);
|
|
990
386
|
if (unsupported.length) notes.push('当前模型不支持工作流参数,已忽略:' + unsupported.join('、'));
|
|
991
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
|
+
}
|
|
992
397
|
return saved;
|
|
993
398
|
}
|
|
994
399
|
const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
|
|
@@ -1116,14 +521,14 @@ export async function readReferences(sources, signal, totalLimit = MAX_REF_TOTAL
|
|
|
1116
521
|
return images;
|
|
1117
522
|
}
|
|
1118
523
|
|
|
1119
|
-
async function edit(args, exec, store) {
|
|
524
|
+
async function edit(args, exec, store, snapshot, queue, journal) {
|
|
1120
525
|
const prompt = String(args.prompt || '').trim();
|
|
1121
526
|
if (!prompt) throw new Error('prompt 不能为空:图片编辑需要写清保留什么、只改什么。');
|
|
1122
527
|
const negativePrompt = String(args.negative_prompt || '').trim();
|
|
1123
528
|
const sources = Array.isArray(args.images) ? args.images.filter((item) => String(item || '').trim()) : [];
|
|
1124
529
|
if (!sources.length) throw new Error('图片编辑至少需要 1 张参考图。');
|
|
1125
530
|
if (sources.length > MAX_REF_COUNT) throw new Error('参考图最多 ' + MAX_REF_COUNT + ' 张,当前 ' + sources.length + ' 张。');
|
|
1126
|
-
const config = await readConfig(store);
|
|
531
|
+
const config = snapshot || await readConfig(store);
|
|
1127
532
|
const defaults = (config && config.defaults) || {};
|
|
1128
533
|
const picked = pickProvider(config, 'edit', args);
|
|
1129
534
|
const model = picked.model;
|
|
@@ -1131,7 +536,11 @@ async function edit(args, exec, store) {
|
|
|
1131
536
|
const adapter = resolveAdapter(provider, model);
|
|
1132
537
|
const profile = resolvePromptProfile(model, adapter);
|
|
1133
538
|
const quality = qualityForAdapter(adapter, resolveQuality(defaults), model);
|
|
1134
|
-
const
|
|
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;
|
|
1135
544
|
if (fitted.rejected) throw new Error(fitted.reason);
|
|
1136
545
|
const signal = makeSignal(exec, 360000);
|
|
1137
546
|
const totalLimit = referenceLimitFor(adapter);
|
|
@@ -1139,16 +548,34 @@ async function edit(args, exec, store) {
|
|
|
1139
548
|
logHost('edit adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + ' refs=' + images.length);
|
|
1140
549
|
const extraParams = readParamsArg(args);
|
|
1141
550
|
const unsupported = extraParams && adapter.id !== 'comfyui' ? Object.keys(extraParams) : [];
|
|
1142
|
-
const
|
|
1143
|
-
|
|
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,
|
|
1144
554
|
fitted: fitted, quality: quality, images: images, params: extraParams
|
|
1145
|
-
}, signal);
|
|
1146
|
-
const final =
|
|
1147
|
-
const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
|
|
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
|
+
}
|
|
1148
563
|
const notes = [];
|
|
564
|
+
if (stitched.note) notes.push(stitched.note);
|
|
1149
565
|
if (final.note) notes.push(final.note);
|
|
566
|
+
if (requested.note) notes.push(requested.note);
|
|
567
|
+
if (fitted.reason) notes.push('尺寸 ' + fitted.reason);
|
|
1150
568
|
if (unsupported.length) notes.push('当前模型不支持工作流参数,已忽略:' + unsupported.join('、'));
|
|
1151
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
|
+
}
|
|
1152
579
|
return saved;
|
|
1153
580
|
}
|
|
1154
581
|
|
|
@@ -1186,13 +613,37 @@ function parseSkillMarkdown(raw) {
|
|
|
1186
613
|
function installPromptRecipe(ctx, store) {
|
|
1187
614
|
const register = (target) => {
|
|
1188
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
|
+
};
|
|
1189
641
|
target.effect(() => target.systemPrompt.section({
|
|
1190
642
|
name: 'mo-image:prompt-recipe',
|
|
1191
643
|
order: 2950,
|
|
1192
|
-
text: () => {
|
|
644
|
+
text: (context) => {
|
|
1193
645
|
try {
|
|
1194
|
-
|
|
1195
|
-
return state ? promptSectionText(state) : '';
|
|
646
|
+
return sectionText(context && context.agent ? context.agent.session : null);
|
|
1196
647
|
} catch (error) {
|
|
1197
648
|
logHost('prompt recipe error: ' + String(error && error.message ? error.message : error));
|
|
1198
649
|
return '';
|
|
@@ -1312,6 +763,7 @@ async function modelsForRequest(store, body) {
|
|
|
1312
763
|
export function apply(ctx, options = {}) {
|
|
1313
764
|
ensureDirs();
|
|
1314
765
|
logHost('apply');
|
|
766
|
+
setImageExecutionLogger(logHost);
|
|
1315
767
|
setNetworkLogger(logHost);
|
|
1316
768
|
// 配置写入是权限问题,不是提示词问题:任何工具调用只要指向插件配置就拒绝。
|
|
1317
769
|
try {
|
|
@@ -1326,8 +778,27 @@ export function apply(ctx, options = {}) {
|
|
|
1326
778
|
logHost: logHost,
|
|
1327
779
|
credentialsAccessor: () => (typeof ctx.get === 'function' ? ctx.get('credentials') : undefined)
|
|
1328
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)));
|
|
1329
789
|
try { store.webOriginHost = new URL(ctx.webServer.getOrigin()).hostname; } catch (_error) { store.webOriginHost = ''; }
|
|
1330
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)); }
|
|
1331
802
|
if (canUseCredentials(store)) {
|
|
1332
803
|
readConfig(store).catch((error) => logHost('config key migration failed: ' + String(error && error.message ? error.message : error)));
|
|
1333
804
|
}
|
|
@@ -1520,6 +991,8 @@ export function apply(ctx, options = {}) {
|
|
|
1520
991
|
}, 'mo-image: update route');
|
|
1521
992
|
|
|
1522
993
|
const renderImage = (_args, value) => {
|
|
994
|
+
// 配置交接:这次没有生成图片,整个返回值按 JSON 交给模型(含 settings),不渲染图片行。
|
|
995
|
+
if (value && value.needsSettings) return [{ type: 'text', text: JSON.stringify(value) }];
|
|
1523
996
|
let ref = '';
|
|
1524
997
|
try { ref = value && value.path ? signPreview(value.path) : ''; } catch (error) { logHost('preview sign error: ' + String(error && error.message ? error.message : error)); }
|
|
1525
998
|
if (!ref) ref = path.basename((value && value.path) || '');
|
|
@@ -1528,6 +1001,8 @@ export function apply(ctx, options = {}) {
|
|
|
1528
1001
|
text: ' + '/api/mo-image/preview/' + encodeURIComponent(ref) + ')'
|
|
1529
1002
|
}];
|
|
1530
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 继续)' });
|
|
1531
1006
|
return blocks;
|
|
1532
1007
|
};
|
|
1533
1008
|
const pendingPresentations = new Map();
|
|
@@ -1561,86 +1036,160 @@ export function apply(ctx, options = {}) {
|
|
|
1561
1036
|
type: 'object', additionalProperties: false, required: ['path'],
|
|
1562
1037
|
properties: {
|
|
1563
1038
|
path: { type: 'string' },
|
|
1564
|
-
|
|
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' }
|
|
1565
1049
|
}
|
|
1566
1050
|
},
|
|
1567
1051
|
render: renderImage
|
|
1568
1052
|
};
|
|
1569
1053
|
// DSH 的工具契约要求每个工具声明 output { schema, render? };settings
|
|
1570
1054
|
// 返回值就是给模型看的全部内容:一个最小 JSON(提供商/模型唯一 id + 优化开关 + 一句写法提示)。
|
|
1055
|
+
// 配置没变时只回 { unchanged, hint },所以 schema 只把 hint 标成必填。
|
|
1571
1056
|
const modelsOutput = {
|
|
1572
1057
|
schema: {
|
|
1573
1058
|
type: 'object', additionalProperties: false,
|
|
1574
|
-
required: ['
|
|
1059
|
+
required: ['hint'],
|
|
1575
1060
|
properties: {
|
|
1576
1061
|
provider: { type: 'string' },
|
|
1577
1062
|
model: { type: 'string' },
|
|
1578
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' } },
|
|
1579
1070
|
hint: { type: 'string' },
|
|
1071
|
+
unchanged: { type: 'boolean' },
|
|
1580
1072
|
models: { type: 'array', items: { type: 'string' } },
|
|
1073
|
+
editModels: { type: 'array', items: { type: 'string' } },
|
|
1581
1074
|
params: { type: 'array', items: { type: 'object' } }
|
|
1582
1075
|
}
|
|
1583
1076
|
},
|
|
1584
1077
|
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }]
|
|
1585
1078
|
};
|
|
1586
1079
|
|
|
1587
|
-
//
|
|
1588
|
-
//
|
|
1589
|
-
//
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
defaults.quality || '', defaults.width || '', defaults.height || ''
|
|
1598
|
-
].join('|');
|
|
1599
|
-
};
|
|
1080
|
+
// 生图前要读过当前配置,但只在「这个会话还没读过」或「配置真的变了」时才需要重读。
|
|
1081
|
+
// 记忆按会话保存(见 settings-memory),比较的是配置快照而不是变更次数:用户改了又
|
|
1082
|
+
// 改回去、中间没有对话,仍然算没有变化。系统提示词里的「配置状态」用同一个判断。
|
|
1083
|
+
//
|
|
1084
|
+
// 「读过」= 这一刻的配置已经锁进这次调用的结果(settings 的 payload / 交接的 settings)。
|
|
1085
|
+
// 之后用户再改,签名就变了,下一次调用会重新判断;所以这次锁定不会因为后续修改而失真,
|
|
1086
|
+
// 进行中的请求也不受后续修改影响。
|
|
1087
|
+
//
|
|
1088
|
+
// 没读完就调用生图工具时不报错:把当前配置直接交回去,让模型按它重写提示词再调一次。
|
|
1089
|
+
// 一次失败的工具调用对用户就是一条红字,而模型本来就能从结果里把配置读懂。
|
|
1600
1090
|
const sessionOf = (exec) => (exec && exec.agent && exec.agent.session) || null;
|
|
1601
|
-
const
|
|
1602
|
-
try {
|
|
1603
|
-
const projections = ctx.get && ctx.get('sessionProjections');
|
|
1604
|
-
if (!projections || typeof projections.stateOf !== 'function') return null;
|
|
1605
|
-
const boundary = projections.stateOf(session, 'turnBoundary');
|
|
1606
|
-
const seq = boundary && boundary.openTurnStartSeq;
|
|
1607
|
-
return typeof seq === 'number' ? seq : null;
|
|
1608
|
-
} catch (error) { logHost('turn lookup error: ' + String(error && error.message ? error.message : error)); return null; }
|
|
1609
|
-
};
|
|
1610
|
-
const rememberSettings = (exec) => {
|
|
1091
|
+
const settingsHandoff = (exec, mode, snapshot) => {
|
|
1611
1092
|
const session = sessionOf(exec);
|
|
1612
|
-
if (!session) return;
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
&& (turn === null || mark.turn === turn);
|
|
1623
|
-
if (!fresh) {
|
|
1624
|
-
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
|
+
};
|
|
1625
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
|
+
};
|
|
1626
1120
|
};
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
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;
|
|
1631
1168
|
};
|
|
1632
1169
|
|
|
1633
1170
|
// 每个工具单独兜底:一个工具的契约不满足时,不会连带其它工具一起注册失败。
|
|
1634
1171
|
try {
|
|
1635
1172
|
ctx.tools.register({
|
|
1636
1173
|
name: 'mo_image_settings',
|
|
1637
|
-
description: 'Read the current image settings
|
|
1638
|
-
parameters: {
|
|
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
|
+
},
|
|
1639
1181
|
output: modelsOutput,
|
|
1640
1182
|
timeoutMs: 15000,
|
|
1641
|
-
async execute(
|
|
1642
|
-
|
|
1643
|
-
|
|
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;
|
|
1644
1193
|
}
|
|
1645
1194
|
});
|
|
1646
1195
|
} catch (error) { logHost('settings tool register error: ' + String(error)); }
|
|
@@ -1648,27 +1197,44 @@ export function apply(ctx, options = {}) {
|
|
|
1648
1197
|
try {
|
|
1649
1198
|
ctx.tools.register({
|
|
1650
1199
|
name: 'mo_image_generate',
|
|
1651
|
-
description: 'Generate a new image with the active
|
|
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.',
|
|
1652
1201
|
parameters: {
|
|
1653
|
-
type: 'object', additionalProperties: false,
|
|
1202
|
+
type: 'object', additionalProperties: false,
|
|
1654
1203
|
properties: {
|
|
1655
|
-
prompt: { type: 'string', description: 'Final prompt
|
|
1656
|
-
negative_prompt: { type: 'string', description: 'Optional
|
|
1657
|
-
|
|
1658
|
-
|
|
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.' },
|
|
1659
1209
|
params: {
|
|
1660
1210
|
type: 'object', additionalProperties: true,
|
|
1661
|
-
description: 'Optional workflow
|
|
1662
|
-
}
|
|
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.' }
|
|
1663
1214
|
}
|
|
1664
1215
|
},
|
|
1665
1216
|
output, timeoutMs: 360000,
|
|
1666
1217
|
async execute(args, exec) {
|
|
1667
|
-
|
|
1668
|
-
const
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
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;
|
|
1672
1238
|
}
|
|
1673
1239
|
});
|
|
1674
1240
|
} catch (error) { logHost('generate tool register error: ' + String(error)); }
|
|
@@ -1676,28 +1242,43 @@ export function apply(ctx, options = {}) {
|
|
|
1676
1242
|
try {
|
|
1677
1243
|
ctx.tools.register({
|
|
1678
1244
|
name: 'mo_image_edit',
|
|
1679
|
-
description: 'Edit or refine
|
|
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.',
|
|
1680
1246
|
parameters: {
|
|
1681
|
-
type: 'object', additionalProperties: false,
|
|
1247
|
+
type: 'object', additionalProperties: false,
|
|
1682
1248
|
properties: {
|
|
1683
|
-
prompt: { type: 'string', description: 'Final edit prompt
|
|
1684
|
-
images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute local paths or http(s) URLs
|
|
1685
|
-
negative_prompt: { type: 'string', description: 'Optional
|
|
1686
|
-
|
|
1687
|
-
|
|
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.' },
|
|
1688
1255
|
params: {
|
|
1689
1256
|
type: 'object', additionalProperties: true,
|
|
1690
|
-
description: 'Optional workflow
|
|
1691
|
-
}
|
|
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.' }
|
|
1692
1260
|
}
|
|
1693
1261
|
},
|
|
1694
1262
|
output, timeoutMs: 360000,
|
|
1695
1263
|
async execute(args, exec) {
|
|
1696
|
-
|
|
1697
|
-
const
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
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;
|
|
1701
1282
|
}
|
|
1702
1283
|
});
|
|
1703
1284
|
} catch (error) { logHost('edit tool register error: ' + String(error)); }
|