dsh-mo-image 0.5.1 → 0.6.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.
@@ -0,0 +1,318 @@
1
+ /**
2
+ * 请求、解码与错误处理的公共工具。
3
+ *
4
+ * 原本长在 lib/adapters.js 里;协议变多以后拆出来,供 adapters.js 与
5
+ * lib/adapters/*.js 共用,避免循环依赖。
6
+ */
7
+ import { request } from './net.js';
8
+ import { localizedError } from './localized-error.js';
9
+
10
+ export const ASPECT_CHOICES = ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9'];
11
+
12
+ function gcd(a, b) {
13
+ let x = Math.abs(a);
14
+ let y = Math.abs(b);
15
+ while (y) {
16
+ const t = x % y;
17
+ x = y;
18
+ y = t;
19
+ }
20
+ return x || 1;
21
+ }
22
+
23
+ export function aspectLabel(width, height) {
24
+ const g = gcd(width, height);
25
+ return width / g + ':' + height / g;
26
+ }
27
+
28
+ export function nearestAspect(width, height, choices = ASPECT_CHOICES) {
29
+ const w = Number(width) || 1024;
30
+ const h = Number(height) || 1024;
31
+ const target = Math.log(w / h);
32
+ let best = choices[0];
33
+ let bestScore = Infinity;
34
+ for (const item of choices) {
35
+ const parts = String(item).split(':');
36
+ const a = Number(parts[0]);
37
+ const b = Number(parts[1]);
38
+ if (!a || !b) continue;
39
+ const score = Math.abs(Math.log(a / b) - target);
40
+ if (score < bestScore) { bestScore = score; best = item; }
41
+ }
42
+ return best;
43
+ }
44
+
45
+ export function resolutionFor(width, height) {
46
+ const pixels = (Number(width) || 1024) * (Number(height) || 1024);
47
+ if (pixels >= 2800 * 2800) return '4k';
48
+ if (pixels >= 1800 * 1800) return '2k';
49
+ return '1k';
50
+ }
51
+
52
+ export function baseUrlOf(provider) {
53
+ return String((provider && provider.baseUrl) || '').replace(/\/+$/, '');
54
+ }
55
+
56
+ /** 按适配器声明的鉴权方式生成头;默认 Bearer。 */
57
+ export function authHeaders(provider, adapter) {
58
+ const key = String((provider && provider.key) || '').trim();
59
+ if (!key) return {};
60
+ const type = String((adapter && adapter.authHeader) || 'bearer');
61
+ if (type === 'api-key') return { 'api-key': key };
62
+ if (type === 'x-key') return { 'x-key': key };
63
+ if (type === 'fal-key') return { Authorization: 'Key ' + key };
64
+ return { Authorization: 'Bearer ' + key };
65
+ }
66
+
67
+ export function headersFor(provider, multipart, extra, adapter) {
68
+ const headers = Object.assign({}, extra || {}, authHeaders(provider, adapter));
69
+ if (!multipart && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
70
+ return headers;
71
+ }
72
+
73
+ export function keyedHeaders(provider, name, multipart) {
74
+ const key = String((provider && provider.key) || '').trim();
75
+ return headersFor(Object.assign({}, provider, { key: '' }), multipart, key ? { [name]: key } : {});
76
+ }
77
+
78
+ export function sleep(ms) {
79
+ return new Promise((resolve) => setTimeout(resolve, ms));
80
+ }
81
+
82
+ /** 把 provider 的一张图编码成 data URL(编辑接口通用)。 */
83
+ export function dataUrlOf(image) {
84
+ return 'data:' + image.contentType + ';base64,' + image.buffer.toString('base64');
85
+ }
86
+
87
+ export async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024) {
88
+ const buffer = await readResponseBytes(response, maxBytes);
89
+ const text = buffer.toString('utf8');
90
+ if (!response.ok) {
91
+ let detail = '';
92
+ try {
93
+ const parsed = JSON.parse(text);
94
+ detail = parsed && (parsed.error && (parsed.error.message || parsed.error) || parsed.message || parsed.detail) || '';
95
+ if (typeof detail !== 'string') detail = JSON.stringify(detail);
96
+ } catch (_error) {
97
+ detail = text.slice(0, 300);
98
+ }
99
+ throw localizedError(
100
+ new Error('本地生图服务返回 HTTP ' + response.status + (detail ? ':' + detail : '')),
101
+ detail ? 'upstream.http' : 'upstream.httpNoDetail',
102
+ { status: response.status, detail: detail }
103
+ );
104
+ }
105
+ try {
106
+ return JSON.parse(text);
107
+ } catch (_error) {
108
+ throw localizedError(new Error('本地生图服务返回的不是 JSON'), 'upstream.invalidJson');
109
+ }
110
+ }
111
+
112
+ export function jsonRequest(adapter, provider, requestPath, body) {
113
+ return { path: requestPath, headers: headersFor(provider, false, adapter.headers, adapter), body: JSON.stringify(body) };
114
+ }
115
+
116
+ export function getPath(node, path) {
117
+ if (!path) return node;
118
+ let current = node;
119
+ for (const key of String(path).split('.')) {
120
+ if (current === null || current === undefined) return null;
121
+ current = current[key];
122
+ }
123
+ return current === undefined ? null : current;
124
+ }
125
+
126
+ export function sniffType(buffer) {
127
+ if (!buffer || buffer.length < 12) return 'image/png';
128
+ if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) return 'image/png';
129
+ if (buffer[0] === 0xff && buffer[1] === 0xd8) return 'image/jpeg';
130
+ if (buffer.slice(0, 4).toString('ascii') === 'RIFF' && buffer.slice(8, 12).toString('ascii') === 'WEBP') return 'image/webp';
131
+ if (buffer.slice(0, 3).toString('ascii') === 'GIF') return 'image/gif';
132
+ return 'image/png';
133
+ }
134
+
135
+ export function looksLikeImage(buffer) {
136
+ if (!buffer || buffer.length < 8) return false;
137
+ const type = sniffType(buffer);
138
+ if (type === 'image/png') return buffer[0] === 0x89 && buffer[1] === 0x50;
139
+ if (type === 'image/jpeg') return buffer[0] === 0xff && buffer[1] === 0xd8;
140
+ if (type === 'image/webp') return buffer.slice(0, 4).toString('ascii') === 'RIFF' && buffer.slice(8, 12).toString('ascii') === 'WEBP';
141
+ return buffer.slice(0, 3).toString('ascii') === 'GIF';
142
+ }
143
+
144
+ export function base64ToImage(text) {
145
+ const raw = String(text || '');
146
+ if (!raw || raw.length < 64) return null;
147
+ const dataUrl = /^data:image\/([a-z+]+);base64,(.+)$/i.exec(raw);
148
+ const payload = dataUrl ? dataUrl[2] : raw;
149
+ if (!/^[A-Za-z0-9+/=\r\n]+$/.test(payload)) return null;
150
+ let buffer;
151
+ try {
152
+ buffer = Buffer.from(payload, 'base64');
153
+ } catch (_error) {
154
+ return null;
155
+ }
156
+ if (!looksLikeImage(buffer)) return null;
157
+ return { bytes: buffer, contentType: dataUrl ? 'image/' + dataUrl[1].toLowerCase() : sniffType(buffer) };
158
+ }
159
+
160
+ function collectStrings(node, out, depth) {
161
+ if (!node || depth > 6 || out.length > 80) return;
162
+ if (typeof node === 'string') {
163
+ out.push(node);
164
+ return;
165
+ }
166
+ if (Array.isArray(node)) {
167
+ for (const item of node) collectStrings(item, out, depth + 1);
168
+ return;
169
+ }
170
+ if (typeof node === 'object') {
171
+ for (const key of Object.keys(node)) collectStrings(node[key], out, depth + 1);
172
+ }
173
+ }
174
+
175
+ /**
176
+ * 从任意形状的回应里找出图片:二进制 / b64 / data-url / 外链,全都认。
177
+ */
178
+ export function decodeImagePayload(payload, binary) {
179
+ if (binary && looksLikeImage(binary)) return { bytes: binary, contentType: sniffType(binary) };
180
+ if (!payload) throw new Error('生图接口没有返回图片');
181
+
182
+ const strings = [];
183
+ collectStrings(payload, strings, 0);
184
+
185
+ for (const text of strings) {
186
+ const image = base64ToImage(text);
187
+ if (image) return image;
188
+ }
189
+ for (const text of strings) {
190
+ if (!/^https?:\/\//i.test(text)) continue;
191
+ if (/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(text)) return { url: text };
192
+ }
193
+ for (const text of strings) {
194
+ if (/^https?:\/\//i.test(text)) return { url: text };
195
+ }
196
+ throw new Error('生图接口返回格式不认识');
197
+ }
198
+
199
+ /** 按上限读取响应体;有 Content-Length 时先拒绝明显超限的响应。 */
200
+ export async function readResponseBytes(response, maxBytes) {
201
+ const limit = Number(maxBytes) > 0 ? Number(maxBytes) : Infinity;
202
+ const declared = Number(response.headers.get('content-length'));
203
+ if (Number.isFinite(declared) && declared > limit) {
204
+ try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
205
+ throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
206
+ }
207
+ const body = response.body;
208
+ if (!body) {
209
+ const buffer = Buffer.from(await response.arrayBuffer());
210
+ if (buffer.length > limit) throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
211
+ return buffer;
212
+ }
213
+ // Content-Length 可信时直接写进预分配 buffer,避免 chunks + Buffer.concat 的 2 倍峰值。
214
+ if (Number.isFinite(declared) && declared > 0) {
215
+ const out = Buffer.allocUnsafe(Math.floor(declared));
216
+ let offset = 0;
217
+ let overflow = null;
218
+ for await (const chunk of body) {
219
+ const buffer = Buffer.from(chunk);
220
+ if (offset + buffer.length > limit) {
221
+ try { await body.cancel(); } catch (_error) { /* ignore */ }
222
+ throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
223
+ }
224
+ if (!overflow && offset + buffer.length <= out.length) {
225
+ buffer.copy(out, offset);
226
+ } else {
227
+ if (!overflow) overflow = [out.subarray(0, offset)];
228
+ overflow.push(buffer);
229
+ }
230
+ offset += buffer.length;
231
+ }
232
+ if (overflow) return Buffer.concat(overflow, offset);
233
+ return offset === out.length ? out : Buffer.from(out.subarray(0, offset));
234
+ }
235
+ const chunks = [];
236
+ let total = 0;
237
+ for await (const chunk of body) {
238
+ const buffer = Buffer.from(chunk);
239
+ total += buffer.length;
240
+ if (total > limit) {
241
+ try { await body.cancel(); } catch (_error) { /* ignore */ }
242
+ throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
243
+ }
244
+ chunks.push(buffer);
245
+ }
246
+ return Buffer.concat(chunks);
247
+ }
248
+
249
+ export const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
250
+
251
+ export async function fetchImageUrl(url, signal, maxBytes = MAX_IMAGE_BYTES) {
252
+ const response = await request(url, { signal: signal });
253
+ if (!response.ok) throw new Error('下载生成图失败:HTTP ' + response.status);
254
+ const bytes = await readResponseBytes(response, maxBytes);
255
+ if (!looksLikeImage(bytes)) throw new Error('下载生成图失败:返回内容不是有效图片');
256
+ return { bytes: bytes, contentType: sniffType(bytes) };
257
+ }
258
+
259
+ export function extractMessage(text) {
260
+ const raw = String(text || '').trim();
261
+ if (!raw) return '';
262
+ try {
263
+ const parsed = JSON.parse(raw);
264
+ if (parsed && typeof parsed === 'object') {
265
+ if (parsed.error && typeof parsed.error === 'object' && parsed.error.message) return String(parsed.error.message);
266
+ if (typeof parsed.error === 'string') return parsed.error;
267
+ if (parsed.message) return String(parsed.message);
268
+ if (parsed.msg) return String(parsed.msg);
269
+ }
270
+ } catch (_error) {
271
+ /* 不是 JSON,原样返回 */
272
+ }
273
+ return raw;
274
+ }
275
+
276
+ function detectDroppableField(message) {
277
+ const token = "['\"]?([A-Za-z_][A-Za-z0-9_.-]*)['\"]?";
278
+ const patterns = [
279
+ new RegExp('unknown parameter:\\s*' + token, 'i'),
280
+ new RegExp('unrecognized request argument supplied:\\s*' + token, 'i'),
281
+ new RegExp('unknown (?:field|parameter|property)\\s*' + token, 'i'),
282
+ new RegExp('(?:extra|unexpected|unsupported|not supported) (?:field|parameter|property)[^A-Za-z0-9_]*' + token, 'i')
283
+ ];
284
+ for (const pattern of patterns) {
285
+ const hit = pattern.exec(message);
286
+ if (hit && hit[1]) return hit[1].trim();
287
+ }
288
+ return null;
289
+ }
290
+
291
+ /** 从结构化错误里取 param 字段;不少兼容网关只在 error.param 里给字段名。 */
292
+ function extractErrorParam(text) {
293
+ try {
294
+ const parsed = JSON.parse(String(text || ''));
295
+ const param = (parsed && parsed.error && parsed.error.param) || (parsed && parsed.param);
296
+ return typeof param === 'string' && /^[A-Za-z_][A-Za-z0-9_.-]*$/.test(param) ? param.trim() : null;
297
+ } catch (_error) {
298
+ return null;
299
+ }
300
+ }
301
+
302
+ /**
303
+ * 把各家的错误归结成几类,调用方只按 kind 决策。
304
+ */
305
+ export function classifyFailure(status, text) {
306
+ const message = extractMessage(text) || ('HTTP ' + status);
307
+ const drop = detectDroppableField(message) || extractErrorParam(text);
308
+ if (drop) return { kind: 'param', drop: drop, message: message };
309
+ if (/size/i.test(message) && /(invalid|unsupported|below|minimum|maximum|too small|too large|budget)/i.test(message)) {
310
+ return { kind: 'size', message: message };
311
+ }
312
+ if (status === 401 || status === 403) return { kind: 'auth', message: message };
313
+ if (status === 404) return { kind: 'endpoint', message: message };
314
+ if (status === 413) return { kind: 'payload', message: message };
315
+ if (status === 429) return { kind: 'rate', message: message, retryable: true };
316
+ if (status >= 500) return { kind: 'upstream', message: message, retryable: true };
317
+ return { kind: 'unknown', message: message };
318
+ }
@@ -0,0 +1,351 @@
1
+ /**
2
+ * 异步队列型协议:BFL / fal.ai / Replicate。
3
+ *
4
+ * 三个平台的共同点是「提交 → 轮询 → 拿一个会过期的 URL」,差异全部收敛到
5
+ * async 描述符:build / submitPath / pollUrl / pollHeaders / statusOf / resolve。
6
+ * 拿到 URL 必须立刻下载,不能交给上层。
7
+ */
8
+ import { request } from '../net.js';
9
+ import {
10
+ baseUrlOf, headersFor, authHeaders, readJsonResponse, dataUrlOf, nearestAspect, resolutionFor
11
+ } from '../adapter-kit.js';
12
+
13
+ function hostOf(provider) {
14
+ return String((provider && provider.baseUrl) || '').replace(/^https?:\/\//i, '').split('/')[0].toLowerCase();
15
+ }
16
+
17
+ function promptWithNegative(input) {
18
+ const prompt = String((input && input.prompt) || '');
19
+ const negative = String((input && input.negativePrompt) || '').trim();
20
+ return negative ? prompt + '\n\nAvoid: ' + negative : prompt;
21
+ }
22
+
23
+ function imagesOf(input) {
24
+ return (Array.isArray(input && input.images) ? input.images : [])
25
+ .filter((image) => image && image.buffer && image.contentType);
26
+ }
27
+
28
+ function sizeOf(input) {
29
+ const fitted = input && input.fitted;
30
+ if (!fitted || fitted.omit || fitted.size === 'none' || fitted.size === 'auto') return null;
31
+ if (!fitted.width || !fitted.height) return null;
32
+ return { width: fitted.width, height: fitted.height };
33
+ }
34
+
35
+ /* ------------------------------------------------------------------ BFL */
36
+
37
+ const BFL_SUCCESS = new Set(['READY']);
38
+ const BFL_FAILURE = new Set([
39
+ 'ERROR', 'REQUEST MODERATED', 'CONTENT MODERATED', 'NO CARD GENERATED', 'TASK NOT FOUND'
40
+ ]);
41
+
42
+ function bflBuild(input) {
43
+ const model = String(input.model || '');
44
+ const images = imagesOf(input);
45
+ const body = { prompt: promptWithNegative(input) };
46
+ const size = sizeOf(input) || { width: 1024, height: 1024 };
47
+
48
+ // FLUX 3 只认 aspect_ratio / resolution / images,未知字段直接 422。
49
+ if (/^flux-3/i.test(model)) {
50
+ body.aspect_ratio = nearestAspect(size.width, size.height);
51
+ body.resolution = resolutionFor(size.width, size.height);
52
+ if (images.length) body.images = images.slice(0, 10).map(dataUrlOf);
53
+ return body;
54
+ }
55
+
56
+ // Kontext / Ultra 用 aspect_ratio,没有 width/height。
57
+ if (/kontext|ultra/i.test(model)) {
58
+ body.aspect_ratio = nearestAspect(size.width, size.height);
59
+ body.output_format = 'png';
60
+ if (images.length) {
61
+ body.input_image = dataUrlOf(images[0]);
62
+ for (let index = 1; index < images.length && index < 4; index++) {
63
+ body['input_image_' + (index + 1)] = dataUrlOf(images[index]);
64
+ }
65
+ }
66
+ return body;
67
+ }
68
+
69
+ body.width = size.width;
70
+ body.height = size.height;
71
+ body.output_format = 'png';
72
+ if (input.seed !== undefined && input.seed !== null && input.seed !== '') body.seed = input.seed;
73
+ if (images.length) {
74
+ body.input_image = dataUrlOf(images[0]);
75
+ for (let index = 1; index < images.length && index < 8; index++) {
76
+ body['input_image_' + (index + 1)] = dataUrlOf(images[index]);
77
+ }
78
+ }
79
+ return body;
80
+ }
81
+
82
+ /* ------------------------------------------------------------------ fal */
83
+
84
+ function falModelPath(model) {
85
+ return '/' + String(model || '').trim().replace(/^\/+/, '');
86
+ }
87
+
88
+ function falBuild(input) {
89
+ const body = { prompt: promptWithNegative(input), num_images: 1, output_format: 'jpeg' };
90
+ const size = sizeOf(input);
91
+ if (size) body.image_size = { width: size.width, height: size.height };
92
+ const images = imagesOf(input);
93
+ // fal 的单图端点用 image_url、多图端点用 image_urls,混用会 422。
94
+ if (images.length === 1) body.image_url = dataUrlOf(images[0]);
95
+ else if (images.length > 1) body.image_urls = images.map(dataUrlOf);
96
+ return body;
97
+ }
98
+
99
+ /* -------------------------------------------------------------- Replicate */
100
+
101
+ const schemaCache = new Map();
102
+ const SCHEMA_TTL = 10 * 60 * 1000;
103
+
104
+ /** 测试用:清掉模型 schema 缓存。 */
105
+ export function resetAsyncSchemaCache() {
106
+ schemaCache.clear();
107
+ }
108
+
109
+ function replicateName(model) {
110
+ return String(model || '').trim().replace(/^\/+/, '');
111
+ }
112
+
113
+ const SCHEMA_CACHE_LIMIT = 100;
114
+
115
+ /** 读模型 Input schema;失败就返回 null,且不缓存失败(瞬时 503 不该让后面 10 分钟都退化)。 */
116
+ async function inputSchemaOf(provider, model, signal) {
117
+ const name = replicateName(model);
118
+ if (!name.includes('/')) return null;
119
+ const key = baseUrlOf(provider) + '|' + name;
120
+ const cached = schemaCache.get(key);
121
+ if (cached && Date.now() - cached.at < SCHEMA_TTL) return cached.value;
122
+ try {
123
+ const response = await request(baseUrlOf(provider) + '/models/' + name, {
124
+ headers: headersFor(provider, false), signal: signal
125
+ });
126
+ if (!response.ok) throw new Error('schema ' + response.status);
127
+ const payload = await readJsonResponse(response, 5 * 1024 * 1024);
128
+ const schema = payload
129
+ && payload.latest_version
130
+ && payload.latest_version.openapi_schema
131
+ && payload.latest_version.openapi_schema.components
132
+ && payload.latest_version.openapi_schema.components.schemas
133
+ && payload.latest_version.openapi_schema.components.schemas.Input;
134
+ const properties = schema && schema.properties ? schema.properties : null;
135
+ if (!properties) return null;
136
+ if (schemaCache.size >= SCHEMA_CACHE_LIMIT) {
137
+ const oldest = schemaCache.keys().next().value;
138
+ if (oldest) schemaCache.delete(oldest);
139
+ }
140
+ schemaCache.set(key, { at: Date.now(), value: properties });
141
+ return properties;
142
+ } catch (_error) {
143
+ return null;
144
+ }
145
+ }
146
+
147
+ const SCALAR_IMAGE_FIELDS = ['input_image', 'image', 'image_url'];
148
+ const ARRAY_IMAGE_FIELDS = ['images', 'image_urls'];
149
+
150
+ function isImageString(spec) {
151
+ return !!spec && (spec.type === 'string' || spec.format === 'uri');
152
+ }
153
+
154
+ /**
155
+ * 只认 schema 里声明过的图片字段,并且要求类型对得上。
156
+ * Replicate 对未知字段是静默忽略的,猜错会让参考图被丢掉还照常出图。
157
+ */
158
+ function imageFieldOf(properties) {
159
+ if (!properties) return null;
160
+ for (const name of SCALAR_IMAGE_FIELDS) {
161
+ if (isImageString(properties[name])) return { name: name, array: false };
162
+ }
163
+ for (const name of ARRAY_IMAGE_FIELDS) {
164
+ const spec = properties[name];
165
+ if (!spec) continue;
166
+ if (spec.type === 'array') return { name: name, array: true };
167
+ if (isImageString(spec)) return { name: name, array: false };
168
+ }
169
+ return null;
170
+ }
171
+
172
+ function sizeFieldsOf(properties, size) {
173
+ if (!properties || !size) return null;
174
+ const widthSpec = properties.width;
175
+ const heightSpec = properties.height;
176
+ const numeric = (spec) => !!spec && (spec.type === 'integer' || spec.type === 'number');
177
+ if (numeric(widthSpec) && numeric(heightSpec)) {
178
+ return { width: size.width, height: size.height };
179
+ }
180
+ if (properties.aspect_ratio) {
181
+ const allowed = Array.isArray(properties.aspect_ratio.enum) ? properties.aspect_ratio.enum : undefined;
182
+ return { aspect_ratio: nearestAspect(size.width, size.height, allowed) };
183
+ }
184
+ return null;
185
+ }
186
+
187
+ async function replicateBuild(input, provider, signal) {
188
+ const images = imagesOf(input);
189
+ const properties = await inputSchemaOf(provider, input.model, signal);
190
+ const payload = { prompt: promptWithNegative(input) };
191
+ const notes = [];
192
+
193
+ if (images.length) {
194
+ const field = imageFieldOf(properties);
195
+ if (!field) {
196
+ notes.push('未识别模型输入字段,已省略参考图');
197
+ } else if (field.array) {
198
+ payload[field.name] = images.map(dataUrlOf);
199
+ } else {
200
+ payload[field.name] = dataUrlOf(images[0]);
201
+ if (images.length > 1) notes.push('该模型只接受一张参考图,已只用第一张');
202
+ }
203
+ }
204
+
205
+ const size = sizeOf(input);
206
+ if (size) {
207
+ const sizeFields = sizeFieldsOf(properties, size);
208
+ if (sizeFields) Object.assign(payload, sizeFields);
209
+ else notes.push('未识别模型的尺寸字段,已省略尺寸');
210
+ }
211
+
212
+ return notes.length ? { body: { input: payload }, note: notes.join(';') } : { body: { input: payload } };
213
+ }
214
+
215
+ /* ----------------------------------------------------------------- 描述符 */
216
+
217
+ export const ASYNC_ADAPTERS = [
218
+ {
219
+ id: 'bfl',
220
+ label: 'Black Forest Labs (FLUX)',
221
+ match: (provider) => /(^|\.)bfl\.ai$/i.test(hostOf(provider)),
222
+ authHeader: 'x-key',
223
+ local: false,
224
+ endpoints: { generate: '/v1', edit: '/v1' },
225
+ transport: { generate: 'json', edit: 'json' },
226
+ editFields: [],
227
+ maxN: 1,
228
+ async listModels() {
229
+ return [
230
+ 'flux-2-pro', 'flux-2-max', 'flux-2-flex', 'flux-2-klein-9b', 'flux-2-klein-4b',
231
+ 'flux-3-image', 'flux-3-image-klein', 'flux-kontext-pro', 'flux-kontext-max',
232
+ 'flux-pro-1.1', 'flux-pro-1.1-ultra'
233
+ ];
234
+ },
235
+ async: {
236
+ edit: true,
237
+ build: bflBuild,
238
+ submitPath: (input) => '/' + String(input.model || '').trim().replace(/^\/+/, ''),
239
+ pollUrl: (submission) => String(submission.polling_url || ''),
240
+ pollHeaders: (provider) => ({ 'x-key': String((provider && provider.key) || '') }),
241
+ statusOf: (payload) => {
242
+ const status = String((payload && payload.status) || '').toUpperCase();
243
+ if (BFL_SUCCESS.has(status)) return { state: 'success', status: status };
244
+ if (BFL_FAILURE.has(status)) {
245
+ return { state: 'failure', status: status, message: String((payload && payload.detail) || status) };
246
+ }
247
+ return { state: 'pending', status: status };
248
+ },
249
+ resolve: async (payload) => {
250
+ const sample = payload && payload.result && payload.result.sample;
251
+ if (!sample) throw new Error('BFL 任务完成了但没有返回图片');
252
+ return { url: sample };
253
+ },
254
+ intervalMs: 1000,
255
+ timeoutMs: 300000
256
+ }
257
+ },
258
+ {
259
+ id: 'fal',
260
+ label: 'fal.ai',
261
+ match: (provider) => /(^|\.)(queue\.)?fal(run)?\.(run|com)$/i.test(hostOf(provider)),
262
+ authHeader: 'fal-key',
263
+ local: false,
264
+ endpoints: { generate: '/', edit: '/' },
265
+ transport: { generate: 'json', edit: 'json' },
266
+ editFields: [],
267
+ maxN: 1,
268
+ async listModels(provider, signal) {
269
+ const response = await request('https://api.fal.ai/v1/models?category=text-to-image', {
270
+ headers: headersFor(provider, false), signal: signal
271
+ });
272
+ const payload = await readJsonResponse(response, 5 * 1024 * 1024);
273
+ return (payload && Array.isArray(payload.models) ? payload.models : [])
274
+ .map((item) => String((item && item.endpoint_id) || '').trim())
275
+ .filter(Boolean)
276
+ .slice(0, 200);
277
+ },
278
+ async: {
279
+ edit: true,
280
+ build: falBuild,
281
+ submitPath: (input) => falModelPath(input.model),
282
+ pollUrl: (submission) => String(submission.status_url || ''),
283
+ pollHeaders: (provider) => authHeaders(provider, { authHeader: 'fal-key' }),
284
+ statusOf: (payload) => {
285
+ const status = String((payload && payload.status) || '').toUpperCase();
286
+ if (status === 'COMPLETED') {
287
+ if (payload && payload.error) {
288
+ return { state: 'failure', status: status, message: String(payload.error) };
289
+ }
290
+ return { state: 'success', status: status };
291
+ }
292
+ return { state: 'pending', status: status };
293
+ },
294
+ resolve: async (payload, provider, signal, submission) => {
295
+ const url = (submission && submission.response_url) || (payload && payload.response_url);
296
+ if (!url) throw new Error('fal 任务完成了但没有 response_url');
297
+ const response = await request(url, { headers: authHeaders(provider, { authHeader: 'fal-key' }), signal: signal });
298
+ const result = await readJsonResponse(response, 64 * 1024 * 1024);
299
+ const first = result && Array.isArray(result.images) ? result.images[0] : null;
300
+ if (!first || !first.url) throw new Error('fal 没有返回图片');
301
+ return { url: String(first.url) };
302
+ },
303
+ intervalMs: 1000,
304
+ timeoutMs: 300000
305
+ }
306
+ },
307
+ {
308
+ id: 'replicate',
309
+ label: 'Replicate',
310
+ match: (provider) => hostOf(provider) === 'api.replicate.com',
311
+ authHeader: 'bearer',
312
+ local: false,
313
+ endpoints: { generate: '/', edit: '/' },
314
+ transport: { generate: 'json', edit: 'json' },
315
+ editFields: [],
316
+ maxN: 1,
317
+ async listModels(provider, signal) {
318
+ const response = await request(baseUrlOf(provider) + '/models', {
319
+ headers: headersFor(provider, false), signal: signal
320
+ });
321
+ const payload = await readJsonResponse(response, 5 * 1024 * 1024);
322
+ return (payload && Array.isArray(payload.results) ? payload.results : [])
323
+ .map((item) => (item && item.owner && item.name ? item.owner + '/' + item.name : ''))
324
+ .filter(Boolean)
325
+ .slice(0, 200);
326
+ },
327
+ async: {
328
+ edit: true,
329
+ build: replicateBuild,
330
+ submitPath: (input) => '/models/' + replicateName(input.model) + '/predictions',
331
+ pollUrl: (submission) => String((submission && submission.urls && submission.urls.get) || ''),
332
+ pollHeaders: (provider) => headersFor(provider, false),
333
+ statusOf: (payload) => {
334
+ const status = String((payload && payload.status) || '').toLowerCase();
335
+ if (status === 'succeeded') return { state: 'success', status: status };
336
+ if (['failed', 'canceled', 'aborted'].includes(status)) {
337
+ return { state: 'failure', status: status, message: String((payload && payload.error) || status) };
338
+ }
339
+ return { state: 'pending', status: status };
340
+ },
341
+ resolve: async (payload) => {
342
+ const output = payload && payload.output;
343
+ const url = Array.isArray(output) ? output[0] : output;
344
+ if (!url) throw new Error('Replicate 任务完成了但没有返回图片');
345
+ return { url: String(url) };
346
+ },
347
+ intervalMs: 1000,
348
+ timeoutMs: 300000
349
+ }
350
+ }
351
+ ];