dsh-mo-image 0.0.0-stage → 0.5.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 +31 -0
- package/LICENSE +21 -0
- package/README.md +392 -3
- package/THIRD-PARTY-NOTICES.md +32 -0
- package/cordis.patch.yml +3 -0
- package/lib/adapters.js +1824 -0
- package/lib/client.js +4693 -0
- package/lib/config-guard.js +51 -0
- package/lib/index.js +1465 -0
- package/lib/localized-error.js +66 -0
- package/lib/net.js +158 -0
- package/lib/png-scale.js +231 -0
- package/lib/prompt-profiles.js +311 -0
- package/lib/proxy-dispatcher.js +212 -0
- package/lib/proxy.js +232 -0
- package/lib/update-service.js +298 -0
- package/lib/update.js +250 -0
- package/locale/messages.csv +178 -0
- package/package.json +71 -4
- package/scripts/build-locales.mjs +274 -0
- package/scripts/release.mjs +532 -0
- package/skills/mo-image-editing/SKILL.md +152 -0
- package/skills/mo-image-generation/SKILL.md +239 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1465 @@
|
|
|
1
|
+
import { mkdirSync, existsSync, appendFileSync, readFileSync, writeFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { readFile, writeFile, stat, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { randomUUID, randomBytes, createHmac, timingSafeEqual } from 'node:crypto';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { lookup } from 'node:dns/promises';
|
|
8
|
+
import { isIP } from 'node:net';
|
|
9
|
+
import {
|
|
10
|
+
resolveAdapter, describeAdapter, fitSize, escalateSize,
|
|
11
|
+
qualityForAdapter, qualityOptionsFor, filterImageModels,
|
|
12
|
+
prepareGenerate, prepareEdit, prepareAsync, pollUrlFor, pollHeaders,
|
|
13
|
+
readTaskId, readTaskState, decodeImagePayload, classifyFailure,
|
|
14
|
+
fetchImageUrl, resizeTo, adapterBase, readResponseBytes, looksLikeImage, sniffType,
|
|
15
|
+
listProviderModelEntries, adapterManifest, localPresetManifest, providerPresetManifest, MAX_IMAGE_BYTES,
|
|
16
|
+
adapterSupportsKind
|
|
17
|
+
} from './adapters.js';
|
|
18
|
+
import { promptSectionText, resolvePromptProfile } from './prompt-profiles.js';
|
|
19
|
+
import { request, setNetworkLogger } from './net.js';
|
|
20
|
+
import { configWriteReason } from './config-guard.js';
|
|
21
|
+
import { localizedError, errorBody } from './localized-error.js';
|
|
22
|
+
import { createUpdateService } from './update-service.js';
|
|
23
|
+
|
|
24
|
+
const PLUGIN = 'dsh-mo-image';
|
|
25
|
+
function dshHome() {
|
|
26
|
+
return process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
|
|
27
|
+
}
|
|
28
|
+
function stateDir() {
|
|
29
|
+
return path.join(dshHome(), 'mo-image');
|
|
30
|
+
}
|
|
31
|
+
function configFile() {
|
|
32
|
+
return path.join(stateDir(), 'config.json');
|
|
33
|
+
}
|
|
34
|
+
function outputDir() {
|
|
35
|
+
return path.join(stateDir(), 'out');
|
|
36
|
+
}
|
|
37
|
+
function hostLogFile() {
|
|
38
|
+
return path.join(stateDir(), 'host.log');
|
|
39
|
+
}
|
|
40
|
+
/** 插件自己的版本号,用来和 GitHub 上的 Release 比。 */
|
|
41
|
+
function pluginVersion() {
|
|
42
|
+
try {
|
|
43
|
+
return String(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version || '0.0.0');
|
|
44
|
+
} catch (_error) {
|
|
45
|
+
return '0.0.0';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const UPDATE_CHECK_TTL_MS = 12 * 60 * 60 * 1000;
|
|
49
|
+
const MAX_BODY = 2 * 1024 * 1024;
|
|
50
|
+
const MAX_REF_BYTES = 15 * 1024 * 1024;
|
|
51
|
+
const MAX_REF_TOTAL = 48 * 1024 * 1024;
|
|
52
|
+
const MAX_JSON_EDIT_TOTAL = 10 * 1024 * 1024;
|
|
53
|
+
const MAX_REF_COUNT = 16;
|
|
54
|
+
const MAX_REF_CONCURRENCY = 3;
|
|
55
|
+
const ALLOW_PRIVATE_REFS = String(process.env.MO_IMAGE_ALLOW_PRIVATE_REFS || '').trim() === '1';
|
|
56
|
+
|
|
57
|
+
function ensureDirs() { mkdirSync(outputDir(), { recursive: true }); }
|
|
58
|
+
function logHost(message) {
|
|
59
|
+
try { appendFileSync(hostLogFile(), new Date().toISOString() + ' ' + message + '\n'); } catch (_error) { /* diagnostics */ }
|
|
60
|
+
}
|
|
61
|
+
function sessionCwd(exec) {
|
|
62
|
+
try {
|
|
63
|
+
const cwd = exec && exec.agent && exec.agent.session && exec.agent.session.header && exec.agent.session.header.cwd;
|
|
64
|
+
return typeof cwd === 'string' && path.isAbsolute(cwd) ? cwd : '';
|
|
65
|
+
} catch (_error) { return ''; }
|
|
66
|
+
}
|
|
67
|
+
/** 新图优先写进当前项目目录;没有 session cwd 时退回 DSH 状态目录。 */
|
|
68
|
+
function generatedImageDir(exec) {
|
|
69
|
+
const cwd = sessionCwd(exec);
|
|
70
|
+
return cwd ? path.join(cwd, 'generated-images') : outputDir();
|
|
71
|
+
}
|
|
72
|
+
let previewKeyCache = null;
|
|
73
|
+
/** 预览 URL 用 HMAC 签名,图片本体留在项目目录,宿主只保存一把很小的 key。 */
|
|
74
|
+
function previewKey() {
|
|
75
|
+
const file = path.join(stateDir(), 'preview.key');
|
|
76
|
+
if (previewKeyCache && previewKeyCache.file === file) return previewKeyCache.key;
|
|
77
|
+
ensureDirs();
|
|
78
|
+
let key = null;
|
|
79
|
+
try { key = readFileSync(file); } catch (_error) { key = null; }
|
|
80
|
+
if (!key || key.length !== 32) {
|
|
81
|
+
key = randomBytes(32);
|
|
82
|
+
try {
|
|
83
|
+
writeFileSync(file, key, { mode: 0o600, flag: 'wx' });
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!error || error.code !== 'EEXIST') throw error;
|
|
86
|
+
key = readFileSync(file);
|
|
87
|
+
}
|
|
88
|
+
if (!key || key.length !== 32) throw new Error('preview key is invalid');
|
|
89
|
+
}
|
|
90
|
+
previewKeyCache = { file: file, key: key };
|
|
91
|
+
return key;
|
|
92
|
+
}
|
|
93
|
+
function signPreview(file) {
|
|
94
|
+
const payload = Buffer.from(JSON.stringify({ p: file }), 'utf8').toString('base64url');
|
|
95
|
+
const signature = createHmac('sha256', previewKey()).update(payload).digest('base64url');
|
|
96
|
+
return payload + '.' + signature;
|
|
97
|
+
}
|
|
98
|
+
function resolvePreviewToken(token) {
|
|
99
|
+
const parts = String(token || '').split('.');
|
|
100
|
+
if (parts.length !== 2) return '';
|
|
101
|
+
const payload = parts[0];
|
|
102
|
+
try {
|
|
103
|
+
const expected = createHmac('sha256', previewKey()).update(payload).digest();
|
|
104
|
+
const actual = Buffer.from(parts[1], 'base64url');
|
|
105
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) return '';
|
|
106
|
+
const value = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
|
107
|
+
return value && typeof value.p === 'string' && path.isAbsolute(value.p) ? value.p : '';
|
|
108
|
+
} catch (_error) { return ''; }
|
|
109
|
+
}
|
|
110
|
+
function emptyConfig() {
|
|
111
|
+
return {
|
|
112
|
+
version: 1, providers: [], active: { providerId: '', model: '' },
|
|
113
|
+
defaults: { quality: 'high', auto: true, width: 1024, height: 1024, promptOptimization: true }
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** 质量值由适配器的 options 决定;这里只保留旧配置里的合法字符串,具体对齐交给 adapter。 */
|
|
117
|
+
const QUALITY_VALUES = new Set(['off', 'low', 'medium', 'high', 'max', 'auto', 'standard', 'hd', 'default', 'quality', 'turbo']);
|
|
118
|
+
function normalizeQuality(value) {
|
|
119
|
+
const raw = String(value || '').trim().toLowerCase();
|
|
120
|
+
if (raw === 'xhigh') return 'max';
|
|
121
|
+
return QUALITY_VALUES.has(raw) ? raw : 'high';
|
|
122
|
+
}
|
|
123
|
+
function normalizeDefaults(raw) {
|
|
124
|
+
const source = raw && typeof raw === 'object' ? raw : {};
|
|
125
|
+
const side = (value, fallback) => {
|
|
126
|
+
const number = Number(value);
|
|
127
|
+
if (!Number.isFinite(number) || number <= 0) return fallback;
|
|
128
|
+
return Math.min(4096, Math.max(64, Math.round(number)));
|
|
129
|
+
};
|
|
130
|
+
let width = side(source.width, 0);
|
|
131
|
+
let height = side(source.height, 0);
|
|
132
|
+
if (!width || !height) {
|
|
133
|
+
// 兼容上一版的 { size: "1024x1024" }
|
|
134
|
+
const legacy = /^(\d{2,5})x(\d{2,5})$/.exec(String(source.size || '').trim().toLowerCase().replace(/[×*]/g, 'x'));
|
|
135
|
+
if (legacy) { width = side(legacy[1], 1024); height = side(legacy[2], 1024); }
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
quality: normalizeQuality(source.quality),
|
|
139
|
+
auto: source.auto === undefined ? true : !!source.auto,
|
|
140
|
+
width: width || 1024,
|
|
141
|
+
height: height || 1024,
|
|
142
|
+
promptOptimization: source.promptOptimization === undefined ? true : !!source.promptOptimization
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** 质量、尺寸都只取选择器默认值;工具不再接受模型传入的参数。 */
|
|
146
|
+
function resolveQuality(defaults) {
|
|
147
|
+
return normalizeQuality(defaults && defaults.quality);
|
|
148
|
+
}
|
|
149
|
+
function resolveSizeArg(defaults) {
|
|
150
|
+
if (defaults && defaults.auto === false) return (defaults.width || 1024) + 'x' + (defaults.height || 1024);
|
|
151
|
+
return 'none';
|
|
152
|
+
}
|
|
153
|
+
/** 每个模型的可选配置(目前只有自定义工作流),只保留仍存在的模型,限制体积。 */
|
|
154
|
+
const MODEL_WORKFLOW_MAX = 200000;
|
|
155
|
+
export function normalizeModelOptions(raw, models) {
|
|
156
|
+
const out = {};
|
|
157
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
|
|
158
|
+
const allowed = new Set(Array.isArray(models) ? models : []);
|
|
159
|
+
for (const model of Object.keys(raw)) {
|
|
160
|
+
if (!allowed.has(model)) continue;
|
|
161
|
+
const entry = raw[model];
|
|
162
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
|
|
163
|
+
const workflow = typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
|
|
164
|
+
if (!workflow || workflow.length > MODEL_WORKFLOW_MAX) continue;
|
|
165
|
+
out[model] = { workflow };
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function normalizeConfig(raw) {
|
|
171
|
+
const out = emptyConfig();
|
|
172
|
+
if (!raw || typeof raw !== 'object') return out;
|
|
173
|
+
const providers = Array.isArray(raw.providers) ? raw.providers : [];
|
|
174
|
+
for (const item of providers) {
|
|
175
|
+
if (!item || typeof item !== 'object') continue;
|
|
176
|
+
const models = Array.from(new Set((Array.isArray(item.models) ? item.models : [])
|
|
177
|
+
.map((m) => String(m || '').trim()).filter(Boolean)));
|
|
178
|
+
const names = {};
|
|
179
|
+
if (item.names && typeof item.names === 'object') for (const model of models) if (typeof item.names[model] === 'string') names[model] = item.names[model];
|
|
180
|
+
const modelOptions = normalizeModelOptions(item.modelOptions, models);
|
|
181
|
+
const key = String(item.key || '');
|
|
182
|
+
const provider = {
|
|
183
|
+
id: String(item.id || randomUUID()), name: String(item.name || ''),
|
|
184
|
+
baseUrl: String(item.baseUrl || '').replace(/\/+$/, ''),
|
|
185
|
+
apiKeyEnv: validKeyRef(item.apiKeyEnv),
|
|
186
|
+
optionalKey: !!item.optionalKey,
|
|
187
|
+
protocol: String(item.protocol || 'openai-images'), adapter: String(item.adapter || ''), models, names
|
|
188
|
+
};
|
|
189
|
+
// 自定义工作流只有 ComfyUI 适配器会读;别的提供商留着也没用,直接丢弃。
|
|
190
|
+
if (provider.adapter === 'comfyui' && Object.keys(modelOptions).length > 0) provider.modelOptions = modelOptions;
|
|
191
|
+
if (key) provider.key = key;
|
|
192
|
+
out.providers.push(provider);
|
|
193
|
+
}
|
|
194
|
+
const wanted = raw.active && typeof raw.active === 'object' ? raw.active : {};
|
|
195
|
+
const provider = out.providers.find((p) => p.id === wanted.providerId);
|
|
196
|
+
// "auto" 是选择器里的特殊行:允许对话模型在提供商列表内自选模型。
|
|
197
|
+
const wantedModel = String(wanted.model || '').trim();
|
|
198
|
+
const keepModel = wantedModel === 'auto' || (provider && provider.models.includes(wantedModel));
|
|
199
|
+
out.active = { providerId: provider ? provider.id : '', model: keepModel ? wantedModel : '' };
|
|
200
|
+
out.defaults = normalizeDefaults(raw.defaults);
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
/** DSH 凭据库(ctx.credentials)里的引用名;只允许我们自己的 MO_IMAGE_ 命名空间。 */
|
|
204
|
+
const KEY_REF_PREFIX = 'MO_IMAGE_';
|
|
205
|
+
const KEY_REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
206
|
+
function createConfigStore(options) {
|
|
207
|
+
return {
|
|
208
|
+
configFile: options.configFile,
|
|
209
|
+
ensureDirs: options.ensureDirs,
|
|
210
|
+
logHost: options.logHost,
|
|
211
|
+
credentialsAccessor: options.credentialsAccessor,
|
|
212
|
+
cache: null,
|
|
213
|
+
stamp: '',
|
|
214
|
+
webOriginHost: '',
|
|
215
|
+
keyMigration: null,
|
|
216
|
+
writeQueue: Promise.resolve()
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function credentialsService(store) {
|
|
220
|
+
if (!store || typeof store.credentialsAccessor !== 'function') return undefined;
|
|
221
|
+
try { return store.credentialsAccessor(); } catch (_error) { return undefined; }
|
|
222
|
+
}
|
|
223
|
+
function validKeyRef(value) {
|
|
224
|
+
const ref = String(value || '').trim();
|
|
225
|
+
return KEY_REF_PATTERN.test(ref) && ref.startsWith(KEY_REF_PREFIX) ? ref : '';
|
|
226
|
+
}
|
|
227
|
+
/** 按 provider id 生成稳定的环境变量名,例如 MO_IMAGE_P_ABC_API_KEY。 */
|
|
228
|
+
function deriveKeyRef(id, used) {
|
|
229
|
+
const stem = String(id || 'provider').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'PROVIDER';
|
|
230
|
+
const base = KEY_REF_PREFIX + stem + '_API_KEY';
|
|
231
|
+
let ref = base;
|
|
232
|
+
for (let n = 2; used && used.has(ref); n++) ref = base.replace(/_API_KEY$/, '_' + n + '_API_KEY');
|
|
233
|
+
return ref;
|
|
234
|
+
}
|
|
235
|
+
function hasLegacyKeys(config) {
|
|
236
|
+
return (config.providers || []).some((provider) => provider.key || !validKeyRef(provider.apiKeyEnv));
|
|
237
|
+
}
|
|
238
|
+
/** describe() 的 configured 也可能来自环境变量;只有不是 env fallback 才算已存进凭据库。 */
|
|
239
|
+
function credentialIsStored(info) {
|
|
240
|
+
if (!info || !info.configured) return false;
|
|
241
|
+
const source = String(info.source || '');
|
|
242
|
+
return source !== 'env' && source !== 'project-env' && source !== 'user-env';
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function requestHostName(req) {
|
|
246
|
+
const raw = String((req.headers && req.headers.host) || '').trim().toLowerCase();
|
|
247
|
+
if (!raw) return '';
|
|
248
|
+
const withoutPort = raw.replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
|
|
249
|
+
return withoutPort;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* 配置写接口是本插件自己的本地 HTTP 路由,不走 DSH 的 remote 权限层,所以
|
|
253
|
+
* 至少挡掉跨站浏览器请求和 DNS rebinding:Host 必须是回环、IP 字面量或
|
|
254
|
+
* DSH_WEB_URL 公布的域名;Origin 必须同源;POST 必须是 application/json。
|
|
255
|
+
* 同一 OS 用户的进程本来就能读凭据文件,这里不是对抗同 UID 进程的边界。
|
|
256
|
+
*/
|
|
257
|
+
function assertLocalRequest(store, req, write) {
|
|
258
|
+
const hostName = requestHostName(req);
|
|
259
|
+
if (!hostName) {
|
|
260
|
+
const error = new Error('missing Host header'); error.status = 403; throw error;
|
|
261
|
+
}
|
|
262
|
+
const allowed = new Set(['127.0.0.1', 'localhost', '::1']);
|
|
263
|
+
for (const value of [process.env.DSH_WEB_URL, store && store.webOriginHost]) {
|
|
264
|
+
try {
|
|
265
|
+
const parsed = new URL(String(value || ''));
|
|
266
|
+
if (parsed.hostname) allowed.add(parsed.hostname.toLowerCase());
|
|
267
|
+
} catch (_error) { /* ignore */ }
|
|
268
|
+
}
|
|
269
|
+
if (!allowed.has(hostName) && isIP(hostName) === 0) {
|
|
270
|
+
const error = new Error('unexpected Host header'); error.status = 403; throw error;
|
|
271
|
+
}
|
|
272
|
+
const origin = req.headers && req.headers.origin;
|
|
273
|
+
if (origin !== undefined) {
|
|
274
|
+
let originUrl;
|
|
275
|
+
try { originUrl = new URL(String(origin)); } catch (_error) {
|
|
276
|
+
const error = new Error('invalid Origin'); error.status = 403; throw error;
|
|
277
|
+
}
|
|
278
|
+
const hostHeader = String(req.headers.host || '').toLowerCase();
|
|
279
|
+
if (originUrl.host.toLowerCase() !== hostHeader) {
|
|
280
|
+
const error = new Error('cross-origin request rejected'); error.status = 403; throw error;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const site = req.headers && req.headers['sec-fetch-site'];
|
|
284
|
+
if (site && site !== 'same-origin' && site !== 'none') {
|
|
285
|
+
const error = new Error('cross-site request rejected'); error.status = 403; throw error;
|
|
286
|
+
}
|
|
287
|
+
if (write) {
|
|
288
|
+
const type = String((req.headers && req.headers['content-type']) || '').toLowerCase();
|
|
289
|
+
if (!type.startsWith('application/json')) {
|
|
290
|
+
const error = new Error('content-type must be application/json'); error.status = 415; throw error;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** 系统提示词节是同步渲染的,这里用 mtime 缓存一份配置副本。 */
|
|
295
|
+
function rememberConfig(store, config) {
|
|
296
|
+
store.cache = config;
|
|
297
|
+
store.stamp = '';
|
|
298
|
+
}
|
|
299
|
+
function readConfigSync(store) {
|
|
300
|
+
try {
|
|
301
|
+
const info = statSync(store.configFile);
|
|
302
|
+
const stamp = info.mtimeMs + ':' + info.size;
|
|
303
|
+
if (!store.cache || stamp !== store.stamp) {
|
|
304
|
+
store.cache = normalizeConfig(JSON.parse(readFileSync(store.configFile, 'utf8')));
|
|
305
|
+
store.stamp = stamp;
|
|
306
|
+
}
|
|
307
|
+
} catch (_error) {
|
|
308
|
+
if (!store.cache) store.cache = emptyConfig();
|
|
309
|
+
}
|
|
310
|
+
return store.cache;
|
|
311
|
+
}
|
|
312
|
+
/** 当前选中的生图模型;编辑也用同一个(严格模式,不做任何回退)。 */
|
|
313
|
+
function activeImageState(store) {
|
|
314
|
+
const config = readConfigSync(store);
|
|
315
|
+
const provider = (config.providers || []).find((item) => item.id === config.active.providerId);
|
|
316
|
+
const model = String((config.active && config.active.model) || '').trim();
|
|
317
|
+
if (!provider || !model) return null;
|
|
318
|
+
let adapter = null;
|
|
319
|
+
try { adapter = resolveAdapter(provider, model); } catch (_error) { adapter = null; }
|
|
320
|
+
return {
|
|
321
|
+
provider, model, adapter, models: provider.models || [],
|
|
322
|
+
editModel: model, editAdapter: adapter,
|
|
323
|
+
promptOptimization: config.defaults.promptOptimization !== false, defaults: config.defaults
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
function canUseCredentials(store) {
|
|
327
|
+
const credentials = credentialsService(store);
|
|
328
|
+
return !!(credentials && typeof credentials.describe === 'function' && typeof credentials.resolve === 'function' && typeof credentials.set === 'function');
|
|
329
|
+
}
|
|
330
|
+
/** 浏览器只拿 hasKey/keySource,永远拿不到明文密钥。 */
|
|
331
|
+
async function publicConfig(store, config) {
|
|
332
|
+
const credentials = credentialsService(store);
|
|
333
|
+
const providers = await Promise.all((config.providers || []).map(async (provider) => {
|
|
334
|
+
const copy = Object.assign({}, provider);
|
|
335
|
+
delete copy.key;
|
|
336
|
+
const ref = validKeyRef(provider.apiKeyEnv);
|
|
337
|
+
let hasKey = false;
|
|
338
|
+
let keySource = '';
|
|
339
|
+
if (ref && credentials && typeof credentials.describe === 'function') {
|
|
340
|
+
try {
|
|
341
|
+
const info = await credentials.describe(ref);
|
|
342
|
+
hasKey = !!info.configured;
|
|
343
|
+
keySource = info.source || '';
|
|
344
|
+
} catch (error) { store.logHost('credential describe failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
|
|
345
|
+
}
|
|
346
|
+
if (!hasKey && ref && process.env[ref]) { hasKey = true; keySource = 'env'; }
|
|
347
|
+
if (!hasKey && provider.key) { hasKey = true; keySource = 'config'; }
|
|
348
|
+
return Object.assign(copy, { hasKey: hasKey, keySource: keySource });
|
|
349
|
+
}));
|
|
350
|
+
return Object.assign({}, config, { providers: providers });
|
|
351
|
+
}
|
|
352
|
+
/** 选择器用的模型能力表:目前先下发每个模型可用的质量档位。 */
|
|
353
|
+
/** 本地部署器:没有云端鉴权,走本机或局域网接口。 */
|
|
354
|
+
const LOCAL_ADAPTERS = new Set(['a1111', 'comfyui', 'swarmui', 'localai']);
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* 给模型看的模型清单:只有 id、显示名、部署方式,绝不带 key 或凭据引用。
|
|
358
|
+
* 模型没有别的途径读配置(配置文件被守卫拦着),所以这里要够用。
|
|
359
|
+
*/
|
|
360
|
+
export function modelListSnapshot(config) {
|
|
361
|
+
const providers = Array.isArray(config && config.providers) ? config.providers : [];
|
|
362
|
+
const activeId = String((config && config.active && config.active.providerId) || '');
|
|
363
|
+
const activeModel = String((config && config.active && config.active.model) || '');
|
|
364
|
+
const activeProvider = providers.find((item) => item.id === activeId) || null;
|
|
365
|
+
const nameOf = (provider, model) => String((provider && provider.names && provider.names[model]) || '');
|
|
366
|
+
return {
|
|
367
|
+
auto: activeModel === 'auto',
|
|
368
|
+
active: {
|
|
369
|
+
providerId: activeProvider ? activeProvider.id : '',
|
|
370
|
+
providerName: activeProvider ? activeProvider.name : '',
|
|
371
|
+
model: activeModel,
|
|
372
|
+
modelName: activeModel === 'auto' ? '' : nameOf(activeProvider, activeModel)
|
|
373
|
+
},
|
|
374
|
+
providers: providers.map((provider) => ({
|
|
375
|
+
id: provider.id,
|
|
376
|
+
name: provider.name,
|
|
377
|
+
adapter: provider.adapter || '',
|
|
378
|
+
local: !!provider.optionalKey || LOCAL_ADAPTERS.has(String(provider.adapter || '')),
|
|
379
|
+
active: !!activeProvider && activeProvider.id === provider.id,
|
|
380
|
+
models: (provider.models || []).map((model) => ({ id: model, name: nameOf(provider, model) }))
|
|
381
|
+
}))
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function capabilityManifest(config) {
|
|
386
|
+
return (config.providers || []).map((provider) => ({
|
|
387
|
+
providerId: provider.id,
|
|
388
|
+
models: (provider.models || []).map((model) => {
|
|
389
|
+
let quality = null;
|
|
390
|
+
try { quality = qualityOptionsFor(resolveAdapter(provider, model), model); } catch (_error) { quality = null; }
|
|
391
|
+
return { model: model, quality: quality };
|
|
392
|
+
})
|
|
393
|
+
}));
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* 把旧版 config.json 里的明文 key 迁到 DSH 凭据库,并在配置里只留下 apiKeyEnv 引用。
|
|
397
|
+
* 凭据服务不存在(自定义 composition)时保持旧字段,避免把用户锁死。
|
|
398
|
+
*/
|
|
399
|
+
async function migrateConfigKeys(store, input) {
|
|
400
|
+
if (!canUseCredentials(store)) return input;
|
|
401
|
+
const credentials = credentialsService(store);
|
|
402
|
+
const config = normalizeConfig(input);
|
|
403
|
+
const used = new Set();
|
|
404
|
+
let migrated = 0;
|
|
405
|
+
let changed = false;
|
|
406
|
+
for (const provider of config.providers) {
|
|
407
|
+
let ref = validKeyRef(provider.apiKeyEnv);
|
|
408
|
+
if (!ref) {
|
|
409
|
+
ref = deriveKeyRef(provider.id, used);
|
|
410
|
+
provider.apiKeyEnv = ref;
|
|
411
|
+
changed = true;
|
|
412
|
+
} else if (used.has(ref)) {
|
|
413
|
+
ref = deriveKeyRef(provider.id, used);
|
|
414
|
+
provider.apiKeyEnv = ref;
|
|
415
|
+
changed = true;
|
|
416
|
+
}
|
|
417
|
+
used.add(ref);
|
|
418
|
+
if (!provider.key) continue;
|
|
419
|
+
try {
|
|
420
|
+
const info = await credentials.describe(ref);
|
|
421
|
+
if (!credentialIsStored(info)) {
|
|
422
|
+
await credentials.set(ref, provider.key);
|
|
423
|
+
migrated++;
|
|
424
|
+
}
|
|
425
|
+
delete provider.key;
|
|
426
|
+
changed = true;
|
|
427
|
+
} catch (error) {
|
|
428
|
+
store.logHost('credential migration failed for provider ' + provider.id + ': ' + String(error && error.message ? error.message : error));
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (!changed) return config;
|
|
432
|
+
const saved = await writeConfig(store, config);
|
|
433
|
+
if (migrated > 0) store.logHost('migrated ' + migrated + ' API key(s) to credentials store');
|
|
434
|
+
return saved;
|
|
435
|
+
}
|
|
436
|
+
function migrateKeysOnce(store, config) {
|
|
437
|
+
if (!store.keyMigration) store.keyMigration = migrateConfigKeys(store, config).finally(() => { store.keyMigration = null; });
|
|
438
|
+
return store.keyMigration;
|
|
439
|
+
}
|
|
440
|
+
async function readConfig(store) {
|
|
441
|
+
try {
|
|
442
|
+
if (!existsSync(store.configFile)) {
|
|
443
|
+
const empty = emptyConfig();
|
|
444
|
+
rememberConfig(store, empty);
|
|
445
|
+
return empty;
|
|
446
|
+
}
|
|
447
|
+
let config = normalizeConfig(JSON.parse(await readFile(store.configFile, 'utf8')));
|
|
448
|
+
if (hasLegacyKeys(config) && canUseCredentials(store)) {
|
|
449
|
+
try { config = await migrateKeysOnce(store, config); } catch (error) { store.logHost('config key migration failed: ' + String(error && error.message ? error.message : error)); }
|
|
450
|
+
}
|
|
451
|
+
rememberConfig(store, config);
|
|
452
|
+
return config;
|
|
453
|
+
} catch (_error) { return emptyConfig(); }
|
|
454
|
+
}
|
|
455
|
+
async function writeConfig(store, config) {
|
|
456
|
+
const next = normalizeConfig(config);
|
|
457
|
+
const task = store.writeQueue.then(async () => {
|
|
458
|
+
store.ensureDirs();
|
|
459
|
+
const tempFile = store.configFile + '.tmp-' + process.pid + '-' + randomUUID().slice(0, 8);
|
|
460
|
+
try {
|
|
461
|
+
await writeFile(tempFile, JSON.stringify(next, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
462
|
+
await rename(tempFile, store.configFile);
|
|
463
|
+
} finally {
|
|
464
|
+
try { await unlink(tempFile); } catch (_error) { /* rename 成功后临时文件已不存在 */ }
|
|
465
|
+
}
|
|
466
|
+
rememberConfig(store, next);
|
|
467
|
+
return next;
|
|
468
|
+
});
|
|
469
|
+
store.writeQueue = task.catch(() => {});
|
|
470
|
+
return task;
|
|
471
|
+
}
|
|
472
|
+
/** 每次请求才解析一次密钥;不在内存里长期缓存,轮换后下一请求生效。 */
|
|
473
|
+
async function resolveProviderCredential(store, provider) {
|
|
474
|
+
const ref = validKeyRef(provider.apiKeyEnv);
|
|
475
|
+
const credentials = credentialsService(store);
|
|
476
|
+
if (ref) {
|
|
477
|
+
if (credentials && typeof credentials.resolve === 'function') {
|
|
478
|
+
try {
|
|
479
|
+
const hit = await credentials.resolve(ref);
|
|
480
|
+
if (hit && typeof hit.value === 'string' && hit.value.trim().length > 0) {
|
|
481
|
+
return Object.assign({}, provider, { key: hit.value.trim() });
|
|
482
|
+
}
|
|
483
|
+
} catch (error) { store.logHost('credential resolve failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
|
|
484
|
+
}
|
|
485
|
+
const env = process.env[ref];
|
|
486
|
+
if (env && env.trim()) return Object.assign({}, provider, { key: env.trim() });
|
|
487
|
+
}
|
|
488
|
+
if (provider.key) return provider;
|
|
489
|
+
if (provider.optionalKey) return provider;
|
|
490
|
+
throw localizedError(
|
|
491
|
+
new Error('生图提供商「' + (provider.name || provider.id) + '」缺少 API Key,请到 DSH 设置 → 生图模型填写'
|
|
492
|
+
+ (ref ? '(凭据 ' + ref + ')' : '') + '。'),
|
|
493
|
+
ref ? 'provider.missingKeyWithRef' : 'provider.missingKey',
|
|
494
|
+
{ provider: provider.name || provider.id, ref: ref }
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
/** 保存配置前先把每个 provider 的新 key 写进凭据库,配置文件只保留 apiKeyEnv。 */
|
|
498
|
+
async function saveConfigWithCredentials(store, raw) {
|
|
499
|
+
const incoming = normalizeConfig(raw);
|
|
500
|
+
const current = await readConfig(store);
|
|
501
|
+
const credentials = credentialsService(store);
|
|
502
|
+
const canStore = !!(credentials && typeof credentials.set === 'function');
|
|
503
|
+
const canDescribe = !!(credentials && typeof credentials.describe === 'function');
|
|
504
|
+
const currentById = new Map(current.providers.map((provider) => [provider.id, provider]));
|
|
505
|
+
const used = new Set();
|
|
506
|
+
const providers = [];
|
|
507
|
+
for (const provider of incoming.providers) {
|
|
508
|
+
const old = currentById.get(provider.id);
|
|
509
|
+
let ref = validKeyRef(provider.apiKeyEnv) || validKeyRef(old && old.apiKeyEnv) || deriveKeyRef(provider.id, used);
|
|
510
|
+
if (used.has(ref)) ref = deriveKeyRef(provider.id, used);
|
|
511
|
+
used.add(ref);
|
|
512
|
+
provider.apiKeyEnv = ref;
|
|
513
|
+
const newKey = String(provider.key || '').trim();
|
|
514
|
+
delete provider.key;
|
|
515
|
+
if (newKey) {
|
|
516
|
+
if (!canStore) throw localizedError(new Error('DSH 凭据服务未挂载,无法安全保存 API Key;请确认 base composition 包含 dsh-credentials-local。'), 'config.credentialsUnavailable');
|
|
517
|
+
try {
|
|
518
|
+
await credentials.set(ref, newKey);
|
|
519
|
+
} catch (error) {
|
|
520
|
+
const message = String(error && error.message ? error.message : error);
|
|
521
|
+
throw localizedError(new Error('保存 API Key 失败:' + message), 'config.credentialSaveFailed', { message: message });
|
|
522
|
+
}
|
|
523
|
+
} else if (old && old.key) {
|
|
524
|
+
if (canStore && canDescribe) {
|
|
525
|
+
try {
|
|
526
|
+
const info = await credentials.describe(ref);
|
|
527
|
+
if (!credentialIsStored(info)) await credentials.set(ref, old.key);
|
|
528
|
+
} catch (error) {
|
|
529
|
+
const message = String(error && error.message ? error.message : error);
|
|
530
|
+
throw localizedError(new Error('旧 API Key 迁移失败:' + message), 'config.legacyKeyMigrationFailed', { message: message });
|
|
531
|
+
}
|
|
532
|
+
} else {
|
|
533
|
+
provider.key = old.key;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
providers.push(provider);
|
|
537
|
+
}
|
|
538
|
+
if (credentials && typeof credentials.unset === 'function') {
|
|
539
|
+
const kept = new Set(providers.map((provider) => provider.id));
|
|
540
|
+
for (const old of current.providers) {
|
|
541
|
+
if (kept.has(old.id)) continue;
|
|
542
|
+
const ref = validKeyRef(old.apiKeyEnv);
|
|
543
|
+
if (!ref || used.has(ref)) continue;
|
|
544
|
+
try { await credentials.unset(ref); } catch (error) { store.logHost('credential removal failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
incoming.providers = providers;
|
|
548
|
+
try {
|
|
549
|
+
return await writeConfig(store, incoming);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
const message = String(error && error.message ? error.message : error);
|
|
552
|
+
throw localizedError(new Error('保存生图配置失败:' + message), 'config.writeFailed', { message: message });
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
function sendJson(res, status, value) {
|
|
556
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
557
|
+
res.end(JSON.stringify(value));
|
|
558
|
+
}
|
|
559
|
+
async function readBody(req) {
|
|
560
|
+
const chunks = [];
|
|
561
|
+
let total = 0;
|
|
562
|
+
for await (const chunk of req) {
|
|
563
|
+
total += chunk.length;
|
|
564
|
+
if (total > MAX_BODY) throw localizedError(new Error('request body is too large'), 'request.bodyTooLarge');
|
|
565
|
+
chunks.push(chunk);
|
|
566
|
+
}
|
|
567
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
568
|
+
try {
|
|
569
|
+
return text ? JSON.parse(text) : {};
|
|
570
|
+
} catch (error) {
|
|
571
|
+
throw localizedError(error, 'request.invalidJson');
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function pickProvider(config, purpose, args) {
|
|
575
|
+
const providers = config.providers || [];
|
|
576
|
+
if (!providers.length) throw new Error('还没有配置生图模型。请先到 DSH 设置 → 生图模型 添加提供商、模型和 API Key。');
|
|
577
|
+
// 提供商和模型只认用户在选择器里选中的那一组:工具参数里传什么都不认,
|
|
578
|
+
// 避免对话模型在失败后绕过用户去别的提供商/模型上重试。
|
|
579
|
+
const active = config.active || {};
|
|
580
|
+
if (!active.providerId) throw new Error('还没有选择当前生图模型。请先到 DSH 设置 → 生图模型 选择当前模型。');
|
|
581
|
+
const provider = providers.find((p) => p.id === active.providerId) || null;
|
|
582
|
+
if (!provider) throw new Error('当前选中的生图提供商不存在,请到设置 → 生图模型重新选择。');
|
|
583
|
+
// 严格只用用户选中的模型:不做「编辑时自动换 sunburst」这类回退,
|
|
584
|
+
// 模型不支持对应能力时由 callImageApi 明确报「不支持」,而不是偷偷换一个。
|
|
585
|
+
// 唯一例外是用户把选择器设为 Auto:此时才允许工具传 model,且必须在本提供商列表内。
|
|
586
|
+
const activeModel = String(active.model || '').trim();
|
|
587
|
+
if (!activeModel) throw new Error('还没有选择当前生图模型。请先到 DSH 设置 → 生图模型 选择当前模型。');
|
|
588
|
+
const requestedProvider = String((args && args.provider) || '').trim();
|
|
589
|
+
const requestedModel = String((args && args.model) || '').trim();
|
|
590
|
+
// 工具调用一律要带 model(避免对话模型凭记忆漏传/错传);提供商也可以带,但只用来核对。
|
|
591
|
+
if (requestedProvider && requestedProvider !== provider.id && requestedProvider !== provider.name) {
|
|
592
|
+
throw new Error('提供商由用户在设置里固定(当前:' + (provider.name || provider.id) + '),请求的是 ' + requestedProvider + '。要换提供商请让用户在设置里切换。');
|
|
593
|
+
}
|
|
594
|
+
if (!requestedModel) {
|
|
595
|
+
throw new Error('调用生图工具时必须传 model:当前选中的是 ' + (activeModel === 'auto' ? 'Auto(可从列表选择)' : activeModel) + '。');
|
|
596
|
+
}
|
|
597
|
+
let model;
|
|
598
|
+
if (activeModel === 'auto') {
|
|
599
|
+
if (!(provider.models || []).includes(requestedModel)) {
|
|
600
|
+
throw new Error('Auto 模式只能选当前提供商列表里的模型:' + requestedModel + '。可选:' + ((provider.models || []).join(' / ') || '(列表为空)'));
|
|
601
|
+
}
|
|
602
|
+
model = requestedModel;
|
|
603
|
+
} else {
|
|
604
|
+
if (requestedModel !== activeModel) {
|
|
605
|
+
throw new Error('当前选中的模型是 ' + activeModel + '(提供商 ' + (provider.name || provider.id) + '),请求的是 ' + requestedModel + '。模型只能由用户在设置里切换。');
|
|
606
|
+
}
|
|
607
|
+
model = activeModel;
|
|
608
|
+
}
|
|
609
|
+
if (!(provider.models || []).includes(model)) {
|
|
610
|
+
if (provider.models && provider.models.length) throw new Error('当前模型不在提供商的模型目录里,请到设置 → 生图模型补全。' + (purpose === 'edit' ? '图片编辑建议使用 gpt-image-2.5-sunburst 等编辑模型。' : ''));
|
|
611
|
+
throw new Error('当前提供商还没有模型 ID,请到设置 → 生图模型添加并选择模型。');
|
|
612
|
+
}
|
|
613
|
+
// 协议/适配器解析交给 resolveAdapter():不同模型族的请求形状由适配器描述符定义。
|
|
614
|
+
// API Key 由 resolveProviderCredential() 在请求前从 DSH 凭据库解析,不在这里检查。
|
|
615
|
+
if (!provider.baseUrl) throw new Error('生图提供商缺少 API 地址,请到设置 → 生图模型补全。');
|
|
616
|
+
return { provider, model };
|
|
617
|
+
}
|
|
618
|
+
function safeExt(contentType) {
|
|
619
|
+
const type = String(contentType || '').toLowerCase();
|
|
620
|
+
if (type.includes('jpeg') || type.includes('jpg')) return 'jpg';
|
|
621
|
+
if (type.includes('webp')) return 'webp';
|
|
622
|
+
if (type.includes('gif')) return 'gif';
|
|
623
|
+
return 'png';
|
|
624
|
+
}
|
|
625
|
+
function makeSignal(exec, timeoutMs) {
|
|
626
|
+
const signals = [];
|
|
627
|
+
if (exec && exec.signal) signals.push(exec.signal);
|
|
628
|
+
if (typeof AbortSignal !== 'undefined' && AbortSignal.timeout) signals.push(AbortSignal.timeout(timeoutMs));
|
|
629
|
+
if (!signals.length) return undefined;
|
|
630
|
+
return signals.length > 1 && AbortSignal.any ? AbortSignal.any(signals) : signals[0];
|
|
631
|
+
}
|
|
632
|
+
function sleep(ms) {
|
|
633
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
634
|
+
}
|
|
635
|
+
function safeJson(buffer) {
|
|
636
|
+
try { return JSON.parse(buffer.toString('utf8')); } catch (_error) { return null; }
|
|
637
|
+
}
|
|
638
|
+
function sizeLabel(fitted) {
|
|
639
|
+
if (!fitted) return '';
|
|
640
|
+
if (fitted.omit || fitted.size === 'none') return 'auto';
|
|
641
|
+
if (fitted.size === 'auto') return fitted.width && fitted.height ? fitted.width + 'x' + fitted.height : 'auto';
|
|
642
|
+
return fitted.size;
|
|
643
|
+
}
|
|
644
|
+
function imageErrorText(failure) {
|
|
645
|
+
const text = '生图接口失败:' + failure.message;
|
|
646
|
+
const suffix = '(模型与提供商只能由用户在选择器里切换)';
|
|
647
|
+
if (failure.kind === 'size') return text + '(该模型对尺寸有最小/最大像素限制,换一个尺寸或换支持该尺寸的模型)' + suffix;
|
|
648
|
+
if (failure.kind === 'auth') return text + '(检查 API Key 与地址是否正确)' + suffix;
|
|
649
|
+
if (failure.kind === 'param') return text + '(请求参数与模型不兼容)' + suffix;
|
|
650
|
+
return text + suffix;
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* 上游说「这个模型不支持这类操作」时,翻译成统一说法,
|
|
654
|
+
* 免得对话模型把「模型不支持」当成临时故障去换模型重试。
|
|
655
|
+
*/
|
|
656
|
+
function unsupportedModelMessage(kind, failure) {
|
|
657
|
+
const text = String((failure && failure.message) || '');
|
|
658
|
+
if (!/(model|模型)/i.test(text)) return '';
|
|
659
|
+
if (!/(not support|does not support|unsupported|不支持|cannot|无法)/i.test(text)) return '';
|
|
660
|
+
return '该模型不支持' + (kind === 'edit' ? '图生图' : '文生图') + ':' + text;
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* 真正发请求的地方:按适配器组装 → 发 → 解码。
|
|
664
|
+
* 上游报错时只在三类情况下自愈:字段不认识(摘掉重试)、尺寸被拒(往上抬一档)、限流/5xx(退避重试)。
|
|
665
|
+
*/
|
|
666
|
+
/**
|
|
667
|
+
* 异步入队型:提交任务 → 轮询到 SUCCEEDED → 下载图片。
|
|
668
|
+
* 提交阶段的参数错误照旧自愈(摘字段 / 抬尺寸),轮询阶段只对 429、5xx 继续等。
|
|
669
|
+
*/
|
|
670
|
+
async function callAsyncImage(kind, adapter, provider, input, signal) {
|
|
671
|
+
if (kind === 'edit') throw new Error('该模型(' + adapter.label + ')暂不支持参考图编辑,请到设置里换一个编辑模型。');
|
|
672
|
+
const drops = new Set();
|
|
673
|
+
let fitted = input.fitted;
|
|
674
|
+
let submission = null;
|
|
675
|
+
let lastFailure = null;
|
|
676
|
+
let retries = 0;
|
|
677
|
+
|
|
678
|
+
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
679
|
+
const built = prepareAsync(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops);
|
|
680
|
+
const response = await request(adapterBase(provider) + built.path, {
|
|
681
|
+
method: 'POST', headers: built.headers, body: built.body, signal: signal
|
|
682
|
+
});
|
|
683
|
+
const buffer = await readResponseBytes(response, 2 * 1024 * 1024);
|
|
684
|
+
if (response.ok) {
|
|
685
|
+
submission = safeJson(buffer);
|
|
686
|
+
break;
|
|
687
|
+
}
|
|
688
|
+
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
689
|
+
lastFailure = failure;
|
|
690
|
+
logHost(kind + ' async submit ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
|
|
691
|
+
const capability = unsupportedModelMessage(kind, failure);
|
|
692
|
+
if (capability) throw new Error(capability);
|
|
693
|
+
|
|
694
|
+
if (failure.kind === 'param' && failure.drop && !drops.has(failure.drop)) {
|
|
695
|
+
drops.add(failure.drop);
|
|
696
|
+
logHost(kind + ' async drop param "' + failure.drop + '"');
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
if (failure.kind === 'size') {
|
|
700
|
+
const next = escalateSize(adapter, fitted);
|
|
701
|
+
if (next.size !== fitted.size) {
|
|
702
|
+
fitted = next;
|
|
703
|
+
logHost(kind + ' async size escalate → ' + next.size);
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
if (failure.retryable && retries < 2) {
|
|
708
|
+
retries++;
|
|
709
|
+
logHost(kind + ' async submit retry #' + retries + ' in ' + (600 * retries) + 'ms');
|
|
710
|
+
await sleep(600 * retries);
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
throw new Error(imageErrorText(failure));
|
|
714
|
+
}
|
|
715
|
+
if (!submission) throw new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '任务提交失败' }));
|
|
716
|
+
|
|
717
|
+
const taskId = readTaskId(adapter, submission);
|
|
718
|
+
if (!taskId) throw new Error('任务提交后没有拿到 task_id:' + JSON.stringify(submission).slice(0, 200));
|
|
719
|
+
logHost(kind + ' async task=' + taskId + ' submitted');
|
|
720
|
+
|
|
721
|
+
const poll = adapter.poll || {};
|
|
722
|
+
const deadline = Date.now() + (Number(poll.timeoutMs) || 300000);
|
|
723
|
+
let interval = Number(poll.intervalMs) || 2000;
|
|
724
|
+
let state = null;
|
|
725
|
+
while (Date.now() < deadline) {
|
|
726
|
+
await sleep(interval);
|
|
727
|
+
const response = await request(pollUrlFor(adapter, provider, taskId), {
|
|
728
|
+
method: 'GET', headers: pollHeaders(provider), signal: signal
|
|
729
|
+
});
|
|
730
|
+
const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
731
|
+
const payload = safeJson(buffer);
|
|
732
|
+
if (!response.ok || !payload) {
|
|
733
|
+
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
734
|
+
if (failure.retryable) continue;
|
|
735
|
+
throw new Error(imageErrorText(failure));
|
|
736
|
+
}
|
|
737
|
+
state = readTaskState(adapter, payload);
|
|
738
|
+
if (state.state === 'success') {
|
|
739
|
+
const decoded = decodeImagePayload(state.node, null);
|
|
740
|
+
const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
|
|
741
|
+
logHost(kind + ' async task=' + taskId + ' done');
|
|
742
|
+
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType };
|
|
743
|
+
}
|
|
744
|
+
if (state.state === 'failure') {
|
|
745
|
+
throw new Error('生图任务失败(' + state.status + '):' + state.message);
|
|
746
|
+
}
|
|
747
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
748
|
+
}
|
|
749
|
+
throw new Error('生图任务超时(' + taskId + (state ? ',最后状态 ' + state.status : '') + ')');
|
|
750
|
+
}
|
|
751
|
+
async function callImageApi(kind, adapter, provider, input, signal) {
|
|
752
|
+
if (!adapterSupportsKind(adapter, kind)) {
|
|
753
|
+
throw new Error('该模型不支持' + (kind === 'edit' ? '图生图' : '文生图')
|
|
754
|
+
+ '(' + String(input.model || adapter.label) + ')。请到设置 → 生图模型换一个支持它的模型。');
|
|
755
|
+
}
|
|
756
|
+
if (adapter.async) return callAsyncImage(kind, adapter, provider, input, signal);
|
|
757
|
+
if (typeof adapter.execute === 'function') {
|
|
758
|
+
const out = await adapter.execute(kind, provider, input, signal);
|
|
759
|
+
return { fitted: input.fitted, bytes: out.bytes, contentType: out.contentType };
|
|
760
|
+
}
|
|
761
|
+
const fieldNames = (adapter.editFields && adapter.editFields.length) ? adapter.editFields : ['image'];
|
|
762
|
+
const drops = new Set();
|
|
763
|
+
let fitted = input.fitted;
|
|
764
|
+
let fieldIndex = 0;
|
|
765
|
+
let sizeRetries = 0;
|
|
766
|
+
let retries = 0;
|
|
767
|
+
let lastFailure = null;
|
|
768
|
+
|
|
769
|
+
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
770
|
+
const built = kind === 'edit'
|
|
771
|
+
? prepareEdit(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops, fieldNames[fieldIndex])
|
|
772
|
+
: prepareGenerate(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops);
|
|
773
|
+
const response = await request(adapterBase(provider) + built.path, {
|
|
774
|
+
method: 'POST', headers: built.headers, body: built.body, signal: signal
|
|
775
|
+
});
|
|
776
|
+
const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
777
|
+
|
|
778
|
+
if (response.ok) {
|
|
779
|
+
const parsed = safeJson(buffer);
|
|
780
|
+
const decoded = parsed ? decodeImagePayload(parsed, null) : decodeImagePayload(null, buffer);
|
|
781
|
+
const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
|
|
782
|
+
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType };
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
786
|
+
lastFailure = failure;
|
|
787
|
+
logHost(kind + ' upstream ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
|
|
788
|
+
|
|
789
|
+
const capability = unsupportedModelMessage(kind, failure);
|
|
790
|
+
if (capability) throw new Error(capability);
|
|
791
|
+
|
|
792
|
+
if (failure.kind === 'param' && failure.drop && !drops.has(failure.drop)) {
|
|
793
|
+
drops.add(failure.drop);
|
|
794
|
+
logHost(kind + ' drop param "' + failure.drop + '" for adapter ' + adapter.id);
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
if (kind === 'edit' && response.status === 400 && /image/i.test(failure.message) && fieldIndex + 1 < fieldNames.length) {
|
|
798
|
+
fieldIndex++;
|
|
799
|
+
logHost(kind + ' retry with form field "' + fieldNames[fieldIndex] + '"');
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
if (failure.kind === 'size' && sizeRetries < 2) {
|
|
803
|
+
const next = escalateSize(adapter, fitted);
|
|
804
|
+
if (next.size !== fitted.size) {
|
|
805
|
+
fitted = next;
|
|
806
|
+
sizeRetries++;
|
|
807
|
+
logHost(kind + ' size escalate → ' + next.size + '(' + next.reason + ')');
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
if (failure.retryable && retries < 2) {
|
|
812
|
+
retries++;
|
|
813
|
+
await sleep(600 * retries);
|
|
814
|
+
continue;
|
|
815
|
+
}
|
|
816
|
+
throw new Error(imageErrorText(failure));
|
|
817
|
+
}
|
|
818
|
+
throw new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '重试次数用尽' }));
|
|
819
|
+
}
|
|
820
|
+
/** 尺寸被抬大过,就尽量缩回用户要的尺寸。 */
|
|
821
|
+
export function finalizeImage(result) {
|
|
822
|
+
let bytes = result.bytes;
|
|
823
|
+
let contentType = result.contentType;
|
|
824
|
+
let fitted = result.fitted;
|
|
825
|
+
let note = '';
|
|
826
|
+
const wanted = fitted && fitted.requested;
|
|
827
|
+
const wantedPixels = wanted ? wanted.width * wanted.height : 0;
|
|
828
|
+
const fittedPixels = fitted ? (fitted.width || 0) * (fitted.height || 0) : 0;
|
|
829
|
+
// 只有用户要的尺寸比模型实际生成的小才缩回去。用户要的更大时,
|
|
830
|
+
// 上游已经按上限生成,不能再放大冒充用户尺寸(会损失画质)。
|
|
831
|
+
if (fitted && fitted.adjusted && wanted && wanted.width && wanted.height
|
|
832
|
+
&& wanted.text !== fitted.size && fittedPixels > wantedPixels) {
|
|
833
|
+
const resized = resizeTo(bytes, wanted.width, wanted.height);
|
|
834
|
+
if (resized) {
|
|
835
|
+
bytes = resized.bytes;
|
|
836
|
+
contentType = resized.contentType;
|
|
837
|
+
logHost('resize ' + fitted.size + ' → ' + wanted.text);
|
|
838
|
+
fitted = Object.assign({}, fitted, { size: wanted.text, width: wanted.width, height: wanted.height, adjusted: false });
|
|
839
|
+
} else {
|
|
840
|
+
logHost('resize unavailable, keep ' + fitted.size + '(用户要 ' + wanted.text + ')');
|
|
841
|
+
}
|
|
842
|
+
} else if (fitted && fitted.adjusted && wanted && fittedPixels < wantedPixels) {
|
|
843
|
+
note = '该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + wanted.text + ',未放大)。';
|
|
844
|
+
logHost('keep model max ' + fitted.size + '(用户要 ' + wanted.text + ',不放大)');
|
|
845
|
+
}
|
|
846
|
+
return { bytes: bytes, contentType: contentType, fitted: fitted, note: note };
|
|
847
|
+
}
|
|
848
|
+
async function saveImage(bytes, contentType, provider, model, size, exec) {
|
|
849
|
+
ensureDirs();
|
|
850
|
+
const dir = generatedImageDir(exec);
|
|
851
|
+
mkdirSync(dir, { recursive: true });
|
|
852
|
+
const ext = safeExt(contentType);
|
|
853
|
+
const filename = 'mo-' + Date.now() + '-' + randomUUID().slice(0, 8) + '.' + ext;
|
|
854
|
+
const file = path.join(dir, filename);
|
|
855
|
+
await writeFile(file, bytes);
|
|
856
|
+
return { file, filename, provider: provider.name || provider.id, model, size, bytes: bytes.length, contentType };
|
|
857
|
+
}
|
|
858
|
+
async function generate(args, exec, store) {
|
|
859
|
+
const prompt = String(args.prompt || '').trim();
|
|
860
|
+
if (!prompt) throw new Error('prompt 不能为空:先按当前模型的提示词公式写好完整提示词。');
|
|
861
|
+
const negativePrompt = String(args.negative_prompt || '').trim();
|
|
862
|
+
const config = await readConfig(store);
|
|
863
|
+
const picked = pickProvider(config, 'generate', args);
|
|
864
|
+
const model = picked.model;
|
|
865
|
+
const provider = await resolveProviderCredential(store, picked.provider);
|
|
866
|
+
const adapter = resolveAdapter(provider, model);
|
|
867
|
+
const profile = resolvePromptProfile(model, adapter);
|
|
868
|
+
const defaults = (config && config.defaults) || {};
|
|
869
|
+
const quality = qualityForAdapter(adapter, resolveQuality(defaults));
|
|
870
|
+
const fitted = fitSize(adapter, resolveSizeArg(defaults));
|
|
871
|
+
if (fitted.rejected) throw new Error(fitted.reason);
|
|
872
|
+
logHost('generate adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + (fitted.adjusted ? '(' + fitted.reason + ')' : ''));
|
|
873
|
+
const signal = makeSignal(exec, 360000);
|
|
874
|
+
const result = await callImageApi('generate', adapter, provider, {
|
|
875
|
+
model: model, prompt: prompt, negativePrompt: negativePrompt || undefined,
|
|
876
|
+
fitted: fitted, quality: quality
|
|
877
|
+
}, signal);
|
|
878
|
+
const final = finalizeImage(result);
|
|
879
|
+
const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
|
|
880
|
+
if (final.note) saved.note = final.note;
|
|
881
|
+
return saved;
|
|
882
|
+
}
|
|
883
|
+
const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
|
|
884
|
+
function isPrivateIpv4(address) {
|
|
885
|
+
const parts = String(address).split('.').map(Number);
|
|
886
|
+
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true;
|
|
887
|
+
const [a, b] = parts;
|
|
888
|
+
return a === 0 || a === 10 || a === 127
|
|
889
|
+
|| (a === 100 && b >= 64 && b <= 127)
|
|
890
|
+
|| (a === 169 && b === 254)
|
|
891
|
+
|| (a === 172 && b >= 16 && b <= 31)
|
|
892
|
+
|| (a === 192 && b === 168)
|
|
893
|
+
|| (a === 198 && (b === 18 || b === 19))
|
|
894
|
+
|| a >= 224;
|
|
895
|
+
}
|
|
896
|
+
function isPrivateAddress(address) {
|
|
897
|
+
const ip = String(address || '').trim().toLowerCase();
|
|
898
|
+
if (!ip) return true;
|
|
899
|
+
if (isIP(ip) === 4) return isPrivateIpv4(ip);
|
|
900
|
+
if (isIP(ip) !== 6) return true;
|
|
901
|
+
if (ip === '::' || ip === '::1') return true;
|
|
902
|
+
if (/^f[cd][0-9a-f]{2}:/.test(ip)) return true; // fc00::/7
|
|
903
|
+
if (/^fe[89ab][0-9a-f]:/.test(ip)) return true; // fe80::/10
|
|
904
|
+
if (/^ff[0-9a-f]{2}:/.test(ip)) return true; // multicast
|
|
905
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(ip);
|
|
906
|
+
if (mapped) return isPrivateIpv4(mapped[1]);
|
|
907
|
+
if (ip.startsWith('::ffff:')) return true; // 十六进制写法的 IPv4-mapped,保守拒绝
|
|
908
|
+
return false;
|
|
909
|
+
}
|
|
910
|
+
async function assertReferenceUrl(raw) {
|
|
911
|
+
if (ALLOW_PRIVATE_REFS) return;
|
|
912
|
+
let parsed;
|
|
913
|
+
try { parsed = new URL(raw); } catch (_error) { throw new Error('参考图 URL 无效:' + raw); }
|
|
914
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') throw new Error('参考图只支持 http/https URL:' + raw);
|
|
915
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, '');
|
|
916
|
+
if (!host || host === 'localhost' || host.endsWith('.localhost')) {
|
|
917
|
+
throw new Error('参考图 URL 不能指向本机地址:' + raw + '(如确需使用,请设置 MO_IMAGE_ALLOW_PRIVATE_REFS=1)');
|
|
918
|
+
}
|
|
919
|
+
let addresses;
|
|
920
|
+
if (isIP(host)) {
|
|
921
|
+
addresses = [host];
|
|
922
|
+
} else {
|
|
923
|
+
try {
|
|
924
|
+
addresses = (await lookup(host, { all: true, verbatim: true })).map((item) => item.address);
|
|
925
|
+
} catch (_error) {
|
|
926
|
+
throw new Error('无法解析参考图域名:' + host);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
if (addresses.some(isPrivateAddress)) {
|
|
930
|
+
throw new Error('参考图 URL 不能指向内网地址:' + host + '(如确需使用,请设置 MO_IMAGE_ALLOW_PRIVATE_REFS=1)');
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
/** 手动跟重定向,每一跳都重新做内网检查。 */
|
|
934
|
+
async function fetchReferenceResponse(raw, signal) {
|
|
935
|
+
let current = raw;
|
|
936
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
937
|
+
await assertReferenceUrl(current);
|
|
938
|
+
const response = await request(current, { signal: signal, redirect: 'manual' });
|
|
939
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
940
|
+
const location = response.headers.get('location');
|
|
941
|
+
try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
|
|
942
|
+
if (!location) throw new Error('参考图重定向缺少 Location');
|
|
943
|
+
current = new URL(location, current).href;
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
946
|
+
return response;
|
|
947
|
+
}
|
|
948
|
+
throw new Error('参考图重定向次数过多');
|
|
949
|
+
}
|
|
950
|
+
async function readReference(src, signal, index) {
|
|
951
|
+
const raw = String(src || '').trim();
|
|
952
|
+
if (!raw) throw new Error('第 ' + (index + 1) + ' 张参考图为空');
|
|
953
|
+
if (/^https?:\/\//i.test(raw)) {
|
|
954
|
+
const response = await fetchReferenceResponse(raw, signal);
|
|
955
|
+
if (!response.ok) throw new Error('下载参考图失败(第 ' + (index + 1) + ' 张):HTTP ' + response.status);
|
|
956
|
+
let buffer;
|
|
957
|
+
try {
|
|
958
|
+
buffer = await readResponseBytes(response, MAX_REF_BYTES);
|
|
959
|
+
} catch (error) {
|
|
960
|
+
throw new Error('下载参考图失败(第 ' + (index + 1) + ' 张):' + String(error && error.message ? error.message : error));
|
|
961
|
+
}
|
|
962
|
+
if (!looksLikeImage(buffer)) throw new Error('参考图不是有效图片(第 ' + (index + 1) + ' 张):' + raw);
|
|
963
|
+
return { buffer, contentType: sniffType(buffer), filename: 'ref-' + (index + 1) + (/\.(png|jpe?g|webp|gif)$/i.exec(raw) || ['.png'])[0] };
|
|
964
|
+
}
|
|
965
|
+
const file = path.resolve(raw);
|
|
966
|
+
if (!existsSync(file)) throw new Error('找不到参考图:' + raw);
|
|
967
|
+
const info = await stat(file);
|
|
968
|
+
if (!info.isFile()) throw new Error('参考图不是文件:' + raw);
|
|
969
|
+
if (info.size > MAX_REF_BYTES) throw new Error('参考图超过 15MB:' + raw);
|
|
970
|
+
const ext = path.extname(file).toLowerCase();
|
|
971
|
+
if (!IMAGE_MIME[ext]) throw new Error('参考图只支持 png / jpg / jpeg / webp / gif:' + raw);
|
|
972
|
+
const buffer = await readFile(file);
|
|
973
|
+
if (!looksLikeImage(buffer)) throw new Error('参考图不是有效图片:' + raw);
|
|
974
|
+
return { buffer, contentType: sniffType(buffer), filename: path.basename(file) };
|
|
975
|
+
}
|
|
976
|
+
export function referenceLimitFor(adapter) {
|
|
977
|
+
return adapter && adapter.transport && adapter.transport.edit === 'multipart' ? MAX_REF_TOTAL : MAX_JSON_EDIT_TOTAL;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/** 有界并发读取参考图;结果按输入顺序返回。 */
|
|
981
|
+
export async function readReferences(sources, signal, totalLimit = MAX_REF_TOTAL, concurrency = MAX_REF_CONCURRENCY) {
|
|
982
|
+
const list = Array.isArray(sources) ? sources : [];
|
|
983
|
+
const images = new Array(list.length);
|
|
984
|
+
let totalBytes = 0;
|
|
985
|
+
let failure = null;
|
|
986
|
+
let nextIndex = 0;
|
|
987
|
+
const worker = async () => {
|
|
988
|
+
while (!failure) {
|
|
989
|
+
const index = nextIndex++;
|
|
990
|
+
if (index >= list.length) return;
|
|
991
|
+
try {
|
|
992
|
+
const image = await readReference(list[index], signal, index);
|
|
993
|
+
if (failure) return;
|
|
994
|
+
totalBytes += image.buffer.length;
|
|
995
|
+
if (totalBytes > totalLimit) throw new Error('参考图总大小超过 ' + Math.round(totalLimit / 1024 / 1024) + 'MB,请减少图片数量或压缩后再试。');
|
|
996
|
+
images[index] = image;
|
|
997
|
+
} catch (error) {
|
|
998
|
+
failure = failure || error;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
};
|
|
1002
|
+
const workers = Math.max(1, Math.min(concurrency || 1, list.length));
|
|
1003
|
+
await Promise.all(Array.from({ length: workers }, worker));
|
|
1004
|
+
if (failure) throw failure;
|
|
1005
|
+
return images;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
async function edit(args, exec, store) {
|
|
1009
|
+
const prompt = String(args.prompt || '').trim();
|
|
1010
|
+
if (!prompt) throw new Error('prompt 不能为空:图片编辑需要写清保留什么、只改什么。');
|
|
1011
|
+
const negativePrompt = String(args.negative_prompt || '').trim();
|
|
1012
|
+
const sources = Array.isArray(args.images) ? args.images.filter((item) => String(item || '').trim()) : [];
|
|
1013
|
+
if (!sources.length) throw new Error('图片编辑至少需要 1 张参考图。');
|
|
1014
|
+
if (sources.length > MAX_REF_COUNT) throw new Error('参考图最多 ' + MAX_REF_COUNT + ' 张,当前 ' + sources.length + ' 张。');
|
|
1015
|
+
const config = await readConfig(store);
|
|
1016
|
+
const defaults = (config && config.defaults) || {};
|
|
1017
|
+
const picked = pickProvider(config, 'edit', args);
|
|
1018
|
+
const model = picked.model;
|
|
1019
|
+
const provider = await resolveProviderCredential(store, picked.provider);
|
|
1020
|
+
const adapter = resolveAdapter(provider, model);
|
|
1021
|
+
const profile = resolvePromptProfile(model, adapter);
|
|
1022
|
+
const quality = qualityForAdapter(adapter, resolveQuality(defaults));
|
|
1023
|
+
const fitted = fitSize(adapter, resolveSizeArg(defaults));
|
|
1024
|
+
if (fitted.rejected) throw new Error(fitted.reason);
|
|
1025
|
+
const signal = makeSignal(exec, 360000);
|
|
1026
|
+
const totalLimit = referenceLimitFor(adapter);
|
|
1027
|
+
const images = await readReferences(sources, signal, totalLimit);
|
|
1028
|
+
logHost('edit adapter=' + describeAdapter(adapter) + ' model=' + model + ' promptProfile=' + profile.id + ' quality=' + (quality || 'none') + ' size=' + sizeLabel(fitted) + ' refs=' + images.length);
|
|
1029
|
+
const result = await callImageApi('edit', adapter, provider, {
|
|
1030
|
+
model: model, prompt: prompt, negativePrompt: negativePrompt || undefined,
|
|
1031
|
+
fitted: fitted, quality: quality, images: images
|
|
1032
|
+
}, signal);
|
|
1033
|
+
const final = finalizeImage(result);
|
|
1034
|
+
const saved = await saveImage(final.bytes, final.contentType, provider, model, sizeLabel(final.fitted), exec);
|
|
1035
|
+
if (final.note) saved.note = final.note;
|
|
1036
|
+
return saved;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
|
|
1040
|
+
const SKILL_FILES = [
|
|
1041
|
+
{
|
|
1042
|
+
name: 'mo-image-generation',
|
|
1043
|
+
file: fileURLToPath(new URL('../skills/mo-image-generation/SKILL.md', import.meta.url)),
|
|
1044
|
+
description: '生成或重做图片时加载,包含按模型区分的提示词公式、模板和自检清单。'
|
|
1045
|
+
},
|
|
1046
|
+
{
|
|
1047
|
+
name: 'mo-image-editing',
|
|
1048
|
+
file: fileURLToPath(new URL('../skills/mo-image-editing/SKILL.md', import.meta.url)),
|
|
1049
|
+
description: '局部修改、参考图融合和版本迭代时加载,包含编辑公式、约束词和按模型写法。'
|
|
1050
|
+
}
|
|
1051
|
+
];
|
|
1052
|
+
|
|
1053
|
+
/** 只解析 SKILL.md 顶部那几个简单字段,不引入 YAML 依赖。 */
|
|
1054
|
+
function parseSkillMarkdown(raw) {
|
|
1055
|
+
const text = String(raw || '');
|
|
1056
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
|
1057
|
+
if (!match) return { meta: {}, body: text };
|
|
1058
|
+
const meta = {};
|
|
1059
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
1060
|
+
const hit = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line);
|
|
1061
|
+
if (!hit) continue;
|
|
1062
|
+
let value = hit[2].trim();
|
|
1063
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
|
|
1064
|
+
meta[hit[1]] = value;
|
|
1065
|
+
}
|
|
1066
|
+
return { meta, body: text.slice(match[0].length) };
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
/** 把当前模型对应的提示词方言注入系统提示词;模型切换后下一次组装自动更新。 */
|
|
1070
|
+
function installPromptRecipe(ctx, store) {
|
|
1071
|
+
const register = (target) => {
|
|
1072
|
+
if (!target.systemPrompt || typeof target.systemPrompt.section !== 'function') return;
|
|
1073
|
+
target.effect(() => target.systemPrompt.section({
|
|
1074
|
+
name: 'mo-image:prompt-recipe',
|
|
1075
|
+
order: 2950,
|
|
1076
|
+
text: () => {
|
|
1077
|
+
try {
|
|
1078
|
+
const state = activeImageState(store);
|
|
1079
|
+
return state ? promptSectionText(state) : '';
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
logHost('prompt recipe error: ' + String(error && error.message ? error.message : error));
|
|
1082
|
+
return '';
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
}), 'mo-image: prompt recipe');
|
|
1086
|
+
logHost('prompt recipe registered (mo-image:prompt-recipe)');
|
|
1087
|
+
};
|
|
1088
|
+
try {
|
|
1089
|
+
if (typeof ctx.inject === 'function') ctx.inject(['systemPrompt'], register);
|
|
1090
|
+
else register(ctx);
|
|
1091
|
+
} catch (error) { logHost('prompt recipe install error: ' + String(error && error.message ? error.message : error)); }
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
/** 把插件自带的两个 SKILL.md 注册成运行时技能,模型可按需加载。 */
|
|
1095
|
+
function installBundledSkills(ctx) {
|
|
1096
|
+
const register = (target) => {
|
|
1097
|
+
if (!target.skills || typeof target.skills.register !== 'function') return;
|
|
1098
|
+
for (const item of SKILL_FILES) {
|
|
1099
|
+
try {
|
|
1100
|
+
const parsed = parseSkillMarkdown(readFileSync(item.file, 'utf8'));
|
|
1101
|
+
target.effect(() => target.skills.register({
|
|
1102
|
+
name: parsed.meta.name || item.name,
|
|
1103
|
+
description: parsed.meta.description || item.description,
|
|
1104
|
+
whenToUse: parsed.meta.whenToUse,
|
|
1105
|
+
source: 'runtime',
|
|
1106
|
+
content: parsed.body,
|
|
1107
|
+
resourceBase: { kind: 'directory', path: path.dirname(item.file) }
|
|
1108
|
+
}), 'mo-image: skill ' + item.name);
|
|
1109
|
+
logHost('skill registered: ' + item.name);
|
|
1110
|
+
} catch (error) { logHost('skill register error ' + item.name + ': ' + String(error && error.message ? error.message : error)); }
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
try {
|
|
1114
|
+
if (typeof ctx.inject === 'function') ctx.inject(['skills'], register);
|
|
1115
|
+
else register(ctx);
|
|
1116
|
+
} catch (error) { logHost('skill install error: ' + String(error && error.message ? error.message : error)); }
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
export const name = PLUGIN;
|
|
1120
|
+
export const inject = ['webServer', 'tools'];
|
|
1121
|
+
|
|
1122
|
+
async function modelsForRequest(store, body) {
|
|
1123
|
+
const providerId = String(body.providerId || '').trim();
|
|
1124
|
+
let provider;
|
|
1125
|
+
if (providerId) {
|
|
1126
|
+
const config = await readConfig(store);
|
|
1127
|
+
provider = (config.providers || []).find((item) => item.id === providerId);
|
|
1128
|
+
if (!provider) throw localizedError(new Error('找不到指定的生图提供商'), 'provider.notFound');
|
|
1129
|
+
provider = Object.assign({}, provider);
|
|
1130
|
+
if (body.baseUrl) provider.baseUrl = String(body.baseUrl).trim().replace(/\/+$/, '');
|
|
1131
|
+
if (body.adapter) provider.adapter = String(body.adapter).trim();
|
|
1132
|
+
if (body.protocol) provider.protocol = String(body.protocol).trim();
|
|
1133
|
+
if (body.optionalKey !== undefined) provider.optionalKey = !!body.optionalKey;
|
|
1134
|
+
const supplied = String(body.key || '').trim();
|
|
1135
|
+
if (supplied) {
|
|
1136
|
+
provider.key = supplied;
|
|
1137
|
+
delete provider.apiKeyEnv;
|
|
1138
|
+
}
|
|
1139
|
+
} else {
|
|
1140
|
+
const supplied = String(body.key || '').trim();
|
|
1141
|
+
provider = normalizeConfig({
|
|
1142
|
+
providers: [{
|
|
1143
|
+
id: 'model-list',
|
|
1144
|
+
baseUrl: String(body.baseUrl || '').trim(),
|
|
1145
|
+
adapter: String(body.adapter || '').trim(),
|
|
1146
|
+
protocol: String(body.protocol || 'openai-images').trim(),
|
|
1147
|
+
optionalKey: !!body.optionalKey,
|
|
1148
|
+
key: supplied
|
|
1149
|
+
}]
|
|
1150
|
+
}).providers[0];
|
|
1151
|
+
}
|
|
1152
|
+
if (!provider || !provider.baseUrl) throw localizedError(new Error('请先填写 API 地址'), 'provider.missingBaseUrl');
|
|
1153
|
+
try {
|
|
1154
|
+
provider = await resolveProviderCredential(store, provider);
|
|
1155
|
+
} catch (_error) {
|
|
1156
|
+
// 模型列表接口本身可能不需要鉴权;没 key 也让它试一次,真 401 会由上游报出来。
|
|
1157
|
+
}
|
|
1158
|
+
let adapter = resolveAdapter(provider, '');
|
|
1159
|
+
if ((!adapter || typeof adapter.listModels !== 'function') && !String(provider.adapter || '').trim()) {
|
|
1160
|
+
// 没有显式适配器的第三方/兼容网关,退回 OpenAI 兼容的 /models 探测。
|
|
1161
|
+
try { adapter = resolveAdapter(Object.assign({}, provider, { adapter: 'openai-images' }), ''); } catch (_error) { /* keep original */ }
|
|
1162
|
+
}
|
|
1163
|
+
if (!adapter || typeof adapter.listModels !== 'function') throw localizedError(new Error('该部署方式不支持获取模型列表'), 'models.unsupported');
|
|
1164
|
+
const entries = await listProviderModelEntries(adapter, provider, AbortSignal.timeout(20000));
|
|
1165
|
+
const seen = new Set();
|
|
1166
|
+
const allModels = [];
|
|
1167
|
+
const names = {};
|
|
1168
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
1169
|
+
const id = String((entry && entry.id) || '').trim();
|
|
1170
|
+
if (!id || seen.has(id)) continue;
|
|
1171
|
+
seen.add(id);
|
|
1172
|
+
allModels.push(id);
|
|
1173
|
+
const name = String((entry && entry.name) || '').trim();
|
|
1174
|
+
if (name && name !== id) names[id] = name;
|
|
1175
|
+
if (allModels.length >= 500) break;
|
|
1176
|
+
}
|
|
1177
|
+
const models = adapter.id === 'openai-images' ? filterImageModels(allModels) : allModels;
|
|
1178
|
+
return { models: models, allModels: allModels, filteredCount: allModels.length - models.length, names: names };
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
export function apply(ctx, options = {}) {
|
|
1182
|
+
ensureDirs();
|
|
1183
|
+
logHost('apply');
|
|
1184
|
+
setNetworkLogger(logHost);
|
|
1185
|
+
// 配置写入是权限问题,不是提示词问题:任何工具调用只要指向插件配置就拒绝。
|
|
1186
|
+
try {
|
|
1187
|
+
if (ctx.tools && typeof ctx.tools.guard === 'function') {
|
|
1188
|
+
ctx.effect(() => ctx.tools.guard((execution) => configWriteReason(execution && execution.arguments, execution && execution.name)), 'mo-image: config guard');
|
|
1189
|
+
logHost('config write guard installed');
|
|
1190
|
+
}
|
|
1191
|
+
} catch (error) { logHost('config guard install error: ' + String(error && error.message ? error.message : error)); }
|
|
1192
|
+
const store = createConfigStore({
|
|
1193
|
+
configFile: configFile(),
|
|
1194
|
+
ensureDirs: ensureDirs,
|
|
1195
|
+
logHost: logHost,
|
|
1196
|
+
credentialsAccessor: () => (typeof ctx.get === 'function' ? ctx.get('credentials') : undefined)
|
|
1197
|
+
});
|
|
1198
|
+
try { store.webOriginHost = new URL(ctx.webServer.getOrigin()).hostname; } catch (_error) { store.webOriginHost = ''; }
|
|
1199
|
+
readConfigSync(store);
|
|
1200
|
+
if (canUseCredentials(store)) {
|
|
1201
|
+
readConfig(store).catch((error) => logHost('config key migration failed: ' + String(error && error.message ? error.message : error)));
|
|
1202
|
+
}
|
|
1203
|
+
installPromptRecipe(ctx, store);
|
|
1204
|
+
installBundledSkills(ctx);
|
|
1205
|
+
|
|
1206
|
+
// 更新检查:宿主启动后预热一次,路由再按 12 小时的新鲜度补查。
|
|
1207
|
+
// pluginManager 只有桌面版有;没有它时检查照做,只是点"更新"会退化成命令行提示。
|
|
1208
|
+
const updateOptions = options.update && typeof options.update === 'object' ? options.update : {};
|
|
1209
|
+
const updateService = createUpdateService({
|
|
1210
|
+
currentVersion: pluginVersion(),
|
|
1211
|
+
markerFile: path.join(stateDir(), 'update.json'),
|
|
1212
|
+
request: typeof updateOptions.request === 'function' ? updateOptions.request : request,
|
|
1213
|
+
pluginManager: () => (typeof ctx.get === 'function' ? ctx.get('pluginManager') : undefined),
|
|
1214
|
+
log: logHost,
|
|
1215
|
+
installDelayMs: Number.isFinite(updateOptions.installDelayMs) ? updateOptions.installDelayMs : 800,
|
|
1216
|
+
registryBase: updateOptions.registryBase,
|
|
1217
|
+
mirrorBase: updateOptions.mirrorBase,
|
|
1218
|
+
cdnSources: updateOptions.cdnSources
|
|
1219
|
+
});
|
|
1220
|
+
// 上次更新成没成,先看标记文件——这一步不能等网络,否则重启后的
|
|
1221
|
+
// 完成气泡要晚好几秒才可能被问到。
|
|
1222
|
+
Promise.resolve(updateService.hydrate())
|
|
1223
|
+
.catch((error) => logHost('update hydrate failed: ' + String(error && error.message ? error.message : error)));
|
|
1224
|
+
if (updateOptions.skipCheck !== true) {
|
|
1225
|
+
ctx.effect(() => {
|
|
1226
|
+
const delay = Number.isFinite(updateOptions.startupDelayMs) ? updateOptions.startupDelayMs : 5000;
|
|
1227
|
+
const timer = setTimeout(() => {
|
|
1228
|
+
Promise.resolve(updateService.refresh())
|
|
1229
|
+
.catch((error) => logHost('update warmup failed: ' + String(error && error.message ? error.message : error)));
|
|
1230
|
+
}, delay);
|
|
1231
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
1232
|
+
return () => {
|
|
1233
|
+
clearTimeout(timer);
|
|
1234
|
+
updateService.dispose();
|
|
1235
|
+
};
|
|
1236
|
+
}, 'mo-image: update check');
|
|
1237
|
+
}
|
|
1238
|
+
const publicOrigin = () => {
|
|
1239
|
+
// DSH_WEB_URL 是宿主对外公布的地址(远程/反代场景也能用);getOrigin 只是
|
|
1240
|
+
// 本地监听地址,不能直接给远端浏览器用。
|
|
1241
|
+
try {
|
|
1242
|
+
const advertised = String(process.env.DSH_WEB_URL || '').trim();
|
|
1243
|
+
if (/^https?:\/\//i.test(advertised)) return advertised.replace(/\/+$/, '');
|
|
1244
|
+
} catch (_error) { /* ignore */ }
|
|
1245
|
+
try { if (ctx.webServer && typeof ctx.webServer.getOrigin === 'function') return String(ctx.webServer.getOrigin()).replace(/\/+$/, ''); } catch (_error) { /* ignore */ }
|
|
1246
|
+
try { const port = ctx.webServer && ctx.webServer.port; if (port) return 'http://127.0.0.1:' + port; } catch (_error) { /* ignore */ }
|
|
1247
|
+
return '';
|
|
1248
|
+
};
|
|
1249
|
+
|
|
1250
|
+
ctx.effect(() => {
|
|
1251
|
+
try {
|
|
1252
|
+
return ctx.webServer.register({
|
|
1253
|
+
kind: 'exact', path: '/api/mo-image/config',
|
|
1254
|
+
handler: async (req, res) => {
|
|
1255
|
+
try {
|
|
1256
|
+
assertLocalRequest(store, req, req.method === 'POST');
|
|
1257
|
+
if (req.method === 'GET') {
|
|
1258
|
+
const config = await readConfig(store);
|
|
1259
|
+
return sendJson(res, 200, { ok: true, config: await publicConfig(store, config), adapters: adapterManifest(), providerPresets: providerPresetManifest(), localPresets: localPresetManifest(), capabilities: capabilityManifest(config) });
|
|
1260
|
+
}
|
|
1261
|
+
if (req.method === 'POST') {
|
|
1262
|
+
const body = await readBody(req);
|
|
1263
|
+
const saved = await saveConfigWithCredentials(store, body.config || body);
|
|
1264
|
+
return sendJson(res, 200, { ok: true, config: await publicConfig(store, saved), adapters: adapterManifest(), providerPresets: providerPresetManifest(), localPresets: localPresetManifest(), capabilities: capabilityManifest(saved) });
|
|
1265
|
+
}
|
|
1266
|
+
return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
|
|
1267
|
+
} catch (error) {
|
|
1268
|
+
return sendJson(res, Number(error && error.status) || 500, errorBody(error));
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
});
|
|
1272
|
+
} catch (error) { logHost('config route error: ' + String(error)); return () => {}; }
|
|
1273
|
+
}, 'mo-image: config route');
|
|
1274
|
+
|
|
1275
|
+
ctx.effect(() => {
|
|
1276
|
+
try {
|
|
1277
|
+
return ctx.webServer.register({
|
|
1278
|
+
kind: 'exact', path: '/api/mo-image/models',
|
|
1279
|
+
handler: async (req, res) => {
|
|
1280
|
+
try {
|
|
1281
|
+
assertLocalRequest(store, req, true);
|
|
1282
|
+
if (req.method !== 'POST') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
|
|
1283
|
+
const body = await readBody(req);
|
|
1284
|
+
const result = await modelsForRequest(store, body || {});
|
|
1285
|
+
return sendJson(res, 200, { ok: true, models: result.models, allModels: result.allModels, filteredCount: result.filteredCount, names: result.names || {} });
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
return sendJson(res, Number(error && error.status) || 502, errorBody(error));
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
});
|
|
1291
|
+
} catch (error) { logHost('models route error: ' + String(error)); return () => {}; }
|
|
1292
|
+
}, 'mo-image: models route');
|
|
1293
|
+
|
|
1294
|
+
ctx.effect(() => {
|
|
1295
|
+
try {
|
|
1296
|
+
return ctx.webServer.register({
|
|
1297
|
+
kind: 'prefix', path: '/api/mo-image/preview',
|
|
1298
|
+
handler: async (req, res) => {
|
|
1299
|
+
try {
|
|
1300
|
+
const url = new URL(req.url, 'http://127.0.0.1');
|
|
1301
|
+
if (req.method !== 'GET') return sendJson(res, 405, errorBody(localizedError(new Error('method not allowed'), 'request.methodNotAllowed')));
|
|
1302
|
+
const raw = decodeURIComponent(url.pathname.slice('/api/mo-image/preview/'.length));
|
|
1303
|
+
let file = resolvePreviewToken(raw);
|
|
1304
|
+
if (!file) {
|
|
1305
|
+
// 兼容旧版 /preview/<basename>:旧图仍在 DSH 状态目录 out/ 下。
|
|
1306
|
+
const name = path.basename(raw);
|
|
1307
|
+
if (!/^[a-zA-Z0-9._-]+$/.test(name)) return sendJson(res, 400, { ok: false, error: 'bad filename' });
|
|
1308
|
+
file = path.join(outputDir(), name);
|
|
1309
|
+
}
|
|
1310
|
+
if (!existsSync(file)) return sendJson(res, 404, { ok: false, error: 'not found' });
|
|
1311
|
+
const info = await stat(file);
|
|
1312
|
+
if (!info.isFile()) return sendJson(res, 404, { ok: false, error: 'not found' });
|
|
1313
|
+
const ext = path.extname(file).toLowerCase();
|
|
1314
|
+
const type = ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : ext === '.webp' ? 'image/webp' : ext === '.gif' ? 'image/gif' : 'image/png';
|
|
1315
|
+
res.writeHead(200, { 'Content-Type': type, 'Content-Length': info.size, 'Cache-Control': 'private, max-age=3600' });
|
|
1316
|
+
res.end(await readFile(file));
|
|
1317
|
+
} catch (error) {
|
|
1318
|
+
return sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) });
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
});
|
|
1322
|
+
} catch (error) { logHost('preview route error: ' + String(error)); return () => {}; }
|
|
1323
|
+
}, 'mo-image: preview route');
|
|
1324
|
+
|
|
1325
|
+
ctx.effect(() => {
|
|
1326
|
+
try {
|
|
1327
|
+
return ctx.webServer.register({
|
|
1328
|
+
kind: 'exact', path: '/api/mo-image/update',
|
|
1329
|
+
handler: async (req, res) => {
|
|
1330
|
+
try {
|
|
1331
|
+
if (req.method === 'GET') {
|
|
1332
|
+
assertLocalRequest(store, req, false);
|
|
1333
|
+
const status = updateService.status();
|
|
1334
|
+
if (!status.checkedAt || Date.now() - Date.parse(status.checkedAt) > UPDATE_CHECK_TTL_MS) {
|
|
1335
|
+
Promise.resolve(updateService.refresh()).catch((error) => logHost('update refresh failed: ' + String(error && error.message ? error.message : error)));
|
|
1336
|
+
}
|
|
1337
|
+
return sendJson(res, 200, { ok: true, ...status });
|
|
1338
|
+
}
|
|
1339
|
+
if (req.method === 'POST') {
|
|
1340
|
+
assertLocalRequest(store, req, true);
|
|
1341
|
+
const body = await readBody(req);
|
|
1342
|
+
const action = body && typeof body.action === 'string' ? body.action : '';
|
|
1343
|
+
if (action === 'ack') {
|
|
1344
|
+
await updateService.ack();
|
|
1345
|
+
return sendJson(res, 200, { ok: true });
|
|
1346
|
+
}
|
|
1347
|
+
if (action === 'apply') {
|
|
1348
|
+
// 只装服务端自己查到的最新版;请求体里的版本号不可信。
|
|
1349
|
+
const outcome = await updateService.apply();
|
|
1350
|
+
if (outcome.ok === false) return sendJson(res, 200, { ok: false, code: outcome.code });
|
|
1351
|
+
return sendJson(res, 200, { ok: true });
|
|
1352
|
+
}
|
|
1353
|
+
return sendJson(res, 400, { ok: false, error: 'unknown action' });
|
|
1354
|
+
}
|
|
1355
|
+
return sendJson(res, 405, { ok: false, error: 'method not allowed' });
|
|
1356
|
+
} catch (error) {
|
|
1357
|
+
return sendJson(res, Number(error && error.status) || 500, errorBody(error));
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
});
|
|
1361
|
+
} catch (error) { logHost('update route error: ' + String(error)); return () => {}; }
|
|
1362
|
+
}, 'mo-image: update route');
|
|
1363
|
+
|
|
1364
|
+
const renderImage = (_args, value) => {
|
|
1365
|
+
let ref = '';
|
|
1366
|
+
try { ref = value && value.path ? signPreview(value.path) : ''; } catch (error) { logHost('preview sign error: ' + String(error && error.message ? error.message : error)); }
|
|
1367
|
+
if (!ref) ref = path.basename((value && value.path) || '');
|
|
1368
|
+
const blocks = [{
|
|
1369
|
+
type: 'text',
|
|
1370
|
+
text: ' + '/api/mo-image/preview/' + encodeURIComponent(ref) + ')'
|
|
1371
|
+
}];
|
|
1372
|
+
if (value && value.note) blocks.push({ type: 'text', text: value.note });
|
|
1373
|
+
return blocks;
|
|
1374
|
+
};
|
|
1375
|
+
const pendingPresentations = new Map();
|
|
1376
|
+
const presentImage = (exec, result) => {
|
|
1377
|
+
try {
|
|
1378
|
+
const projections = ctx.get && ctx.get('sessionProjections');
|
|
1379
|
+
const boundary = projections && exec.agent ? projections.stateOf(exec.agent.session, 'turnBoundary') : undefined;
|
|
1380
|
+
if (boundary && boundary.openTurnStartSeq !== null && boundary.lastTurn !== undefined) {
|
|
1381
|
+
pendingPresentations.set(exec, {
|
|
1382
|
+
session: exec.agent.session, turn: boundary.lastTurn,
|
|
1383
|
+
callId: exec.callId, file: result.file
|
|
1384
|
+
});
|
|
1385
|
+
}
|
|
1386
|
+
} catch (error) { logHost('present error: ' + String(error && error.message ? error.message : error)); }
|
|
1387
|
+
};
|
|
1388
|
+
const flushPresentation = (exec, result) => {
|
|
1389
|
+
const item = pendingPresentations.get(exec);
|
|
1390
|
+
if (!item) return;
|
|
1391
|
+
pendingPresentations.delete(exec);
|
|
1392
|
+
if (result && result.isError) return;
|
|
1393
|
+
try {
|
|
1394
|
+
item.session.append('deliverables/presented', {
|
|
1395
|
+
turn: item.turn, callId: item.callId,
|
|
1396
|
+
files: [{ path: item.file, description: 'AI 生成图片' }]
|
|
1397
|
+
});
|
|
1398
|
+
} catch (error) { logHost('present append error: ' + String(error && error.message ? error.message : error)); }
|
|
1399
|
+
};
|
|
1400
|
+
if (typeof ctx.on === 'function') ctx.on('tools/result', flushPresentation);
|
|
1401
|
+
const output = {
|
|
1402
|
+
schema: {
|
|
1403
|
+
type: 'object', additionalProperties: false, required: ['path'],
|
|
1404
|
+
properties: {
|
|
1405
|
+
path: { type: 'string' },
|
|
1406
|
+
note: { type: 'string' }
|
|
1407
|
+
}
|
|
1408
|
+
},
|
|
1409
|
+
render: renderImage
|
|
1410
|
+
};
|
|
1411
|
+
|
|
1412
|
+
try {
|
|
1413
|
+
ctx.tools.register({
|
|
1414
|
+
name: 'mo_image_list_models',
|
|
1415
|
+
description: 'List the image models configured in this plugin: every provider, its models with display names, the model the user currently picked, and whether Auto mode is on. Call this first whenever you need to know which image models exist, for example to choose the model argument or to answer which models are available. Reading the plugin config file also works, but this returns the same picture without parsing it.',
|
|
1416
|
+
parameters: { type: 'object', additionalProperties: false, properties: {} },
|
|
1417
|
+
timeoutMs: 15000,
|
|
1418
|
+
async execute() {
|
|
1419
|
+
return modelListSnapshot(await readConfig(store));
|
|
1420
|
+
}
|
|
1421
|
+
});
|
|
1422
|
+
ctx.tools.register({
|
|
1423
|
+
name: 'mo_image_generate',
|
|
1424
|
+
description: 'Generate a new image with the active image model. Follow the active mo-image prompt section: when prompt optimization is On, write the final prompt in the active model\'s dialect; when Off, pass the user\'s original wording unchanged. Model, size, and quality come from the picker, not this tool; the only exception is Auto mode, where the model argument selects one entry from the active provider list. Load the mo-image-generation skill whenever you generate or redo an image; when optimization is Off, use only its invocation and output guidance, not its prompt formulas. The tool returns a Markdown image line and a file card; reply with that Markdown line and nothing else. Output is final: never judge or describe the image, never switch provider, model or tool (local image models, Blender, scripting) on your own, and do not open or read the image unless the user explicitly asks to look at it. On failure report the error verbatim and at most ask the user whether to switch.',
|
|
1425
|
+
parameters: {
|
|
1426
|
+
type: 'object', additionalProperties: false, required: ['prompt', 'model'],
|
|
1427
|
+
properties: {
|
|
1428
|
+
prompt: { type: 'string', description: 'Final prompt adapted to the active model when optimization is On; otherwise the user\'s original wording. Cover subject, action, environment, style, lighting, composition, and constraints; quote in-image text exactly.' },
|
|
1429
|
+
negative_prompt: { type: 'string', description: 'Optional prompt content. Only for models that support negative prompts; list artifacts and undesired elements. Omit otherwise.' },
|
|
1430
|
+
model: { type: 'string', description: 'Always required. Outside Auto mode pass the model the user selected in the picker (the prompt section names it); in Auto mode pick one id from the active provider list.' },
|
|
1431
|
+
provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' }
|
|
1432
|
+
}
|
|
1433
|
+
},
|
|
1434
|
+
output, timeoutMs: 360000,
|
|
1435
|
+
async execute(args, exec) {
|
|
1436
|
+
const result = await generate(args, exec, store);
|
|
1437
|
+
presentImage(exec, result);
|
|
1438
|
+
return result.note ? { path: result.file, note: result.note } : { path: result.file };
|
|
1439
|
+
}
|
|
1440
|
+
});
|
|
1441
|
+
} catch (error) { logHost('generate tool register error: ' + String(error)); }
|
|
1442
|
+
|
|
1443
|
+
try {
|
|
1444
|
+
ctx.tools.register({
|
|
1445
|
+
name: 'mo_image_edit',
|
|
1446
|
+
description: 'Edit or refine an existing image with one or more reference images. Follow the active mo-image prompt section: when prompt optimization is Off, use the user\'s original edit wording and do not expand it. Model, size, and quality come from the picker, not this tool; the only exception is Auto mode, where the model argument selects one entry from the active provider list. Name each reference as 图1/图2 in the prompt. For a full redo that must not copy the current image, use mo_image_generate instead. Load the mo-image-editing skill whenever you edit an image; when optimization is Off, use only its invocation and output guidance, not its edit formula. Output is final: never judge or describe the image, never switch provider, model or tool (local image models, Blender, scripting) on your own, and do not open or read the image unless the user explicitly asks to look at it. On failure report the error verbatim and at most ask the user whether to switch.',
|
|
1447
|
+
parameters: {
|
|
1448
|
+
type: 'object', additionalProperties: false, required: ['prompt', 'images', 'model'],
|
|
1449
|
+
properties: {
|
|
1450
|
+
prompt: { type: 'string', description: 'Final edit prompt. Name each reference image (图1/图2), state exactly what to change, and state that everything else must stay unchanged.' },
|
|
1451
|
+
images: { type: 'array', items: { type: 'string' }, description: '1–16 absolute local paths or http(s) URLs; order matters and corresponds to 图1/图2.' },
|
|
1452
|
+
negative_prompt: { type: 'string', description: 'Optional prompt content. Only for models that support negative prompts; list artifacts and undesired elements. Omit otherwise.' },
|
|
1453
|
+
model: { type: 'string', description: 'Always required. Outside Auto mode pass the model the user selected in the picker (the prompt section names it); in Auto mode pick one id from the active provider list.' },
|
|
1454
|
+
provider: { type: 'string', description: 'Optional. The provider the user selected; it is validated against the picker and never switches providers. Omit when unsure.' }
|
|
1455
|
+
}
|
|
1456
|
+
},
|
|
1457
|
+
output, timeoutMs: 360000,
|
|
1458
|
+
async execute(args, exec) {
|
|
1459
|
+
const result = await edit(args, exec, store);
|
|
1460
|
+
presentImage(exec, result);
|
|
1461
|
+
return result.note ? { path: result.file, note: result.note } : { path: result.file };
|
|
1462
|
+
}
|
|
1463
|
+
});
|
|
1464
|
+
} catch (error) { logHost('edit tool register error: ' + String(error)); }
|
|
1465
|
+
}
|