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