dsh-mo-image 0.6.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,106 @@
1
1
  /**
2
- * 异步队列型协议:BFL / fal.ai / Replicate。
2
+ * 异步队列型协议:BFL / fal.ai / Replicate / 魔搭 ModelScope。
3
3
  *
4
- * 三个平台的共同点是「提交 → 轮询 → 拿一个会过期的 URL」,差异全部收敛到
5
- * async 描述符:build / submitPath / pollUrl / pollHeaders / statusOf / resolve。
6
- * 拿到 URL 必须立刻下载,不能交给上层。
4
+ * 这些平台的共同点是「提交 → 轮询 → 拿一个会过期的 URL」。职责已经按四件事拆开:
5
+ * - 请求侧(`build` / `submitPath` / `edit`)还在 `async` 描述符里;
6
+ * - 响应侧(轮询地址 / 状态词 / 结果图 / 轮询间隔)在 `output:{kind:'task'}` 里
7
+ * (lib/output-profiles.js)——描述符不碰请求、不产出 headers;
8
+ * - 轮询要带的头挂在适配器上(`taskPollHeaders`),凭据与跨源判定仍只有
9
+ * lib/request-auth.js 一份;
10
+ * - 拿到 URL 必须立刻下载,不能交给上层。
7
11
  */
8
- import { request } from '../net.js';
12
+ import { requestProvider } from '../request-auth.js';
9
13
  import {
10
- baseUrlOf, headersFor, authHeaders, readJsonResponse, dataUrlOf, nearestAspect, resolutionFor
14
+ baseUrlOf, headersFor, credentialRef, authHeaders, joinEndpoint, readJsonResponse, dataUrlOf, nearestAspect
11
15
  } from '../adapter-kit.js';
16
+ // 结果地址的凭据判定只有一份(request-auth.js):轮询、via 的二次 GET、结果下载都走它。
17
+ import { applyFields, promptParts } from '../field-templates.js';
18
+ import { outputProfile } from '../output-profiles.js';
12
19
 
13
20
  function hostOf(provider) {
14
- return String((provider && provider.baseUrl) || '').replace(/^https?:\/\//i, '').split('/')[0].toLowerCase();
21
+ try { return new URL(baseUrlOf(provider)).hostname.toLowerCase(); } catch (_error) { return ''; }
15
22
  }
16
23
 
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;
24
+ /* --------------------------------------------------------------- 字段模板 */
25
+
26
+ /**
27
+ * 字段名不在协议里:这四条 build 自己拼提交体,prepare* 那套模板不会流经它们
28
+ * (adapters.js 的 ownsOwnBody() 让 composeBody 跳过模板),所以这里按**同一个实现**
29
+ * 取模板(用户覆盖 > 模型规则 > 预设),再用 applyFields / promptParts 写进去。
30
+ * 协议只决定「用哪条模板」和「什么时候写」——张数上限、FLUX 3 换成 images 数组这类
31
+ * 条件分支仍在各自的 build 里(红线见设计文档「字段模板」)。
32
+ *
33
+ * 为什么用动态 import 而不是像 openai.js / cn.js 那样静态反向 import:adapters.js 在模块
34
+ * 顶层就展开 `...ASYNC_ADAPTERS`,反向静态 import 会成环。那两条协议只在 execute() 里调用,
35
+ * 现在能跑,但代价是它们**被当成入口模块 import 时立刻 TDZ 崩**
36
+ * (`Cannot access 'OPENAI_ADAPTERS' before initialization`)。本文件被三个测试直接 import,
37
+ * 不能把测试吊在 import 顺序上;动态取一次(缓存住)就没有这张图上的环。
38
+ */
39
+ let adaptersModule = null;
40
+ function adapters() {
41
+ if (!adaptersModule) adaptersModule = import('../adapters.js');
42
+ return adaptersModule;
43
+ }
44
+
45
+ /**
46
+ * 本条协议自己的描述符:fieldsFor() 要它来反查预设,而本模块清单里的那一份就是
47
+ * resolveAdapter() 交给调用方的同一个对象。
48
+ */
49
+ function asyncAdapterOf(adapterId) {
50
+ return ASYNC_ADAPTERS.find((adapter) => adapter.id === adapterId) || null;
51
+ }
52
+
53
+ /** 三层字段模板,与通用路径同源(adapters.js 的 fieldsFor)。 */
54
+ async function fieldsOf(adapterId, provider, model) {
55
+ const module = await adapters();
56
+ return module.fieldsFor(asyncAdapterOf(adapterId), provider, model);
57
+ }
58
+
59
+ function promptTextOf(input) {
60
+ return String((input && input.prompt) || '');
61
+ }
62
+
63
+ /** 空负面词算「不发」:拼进提示词的模板靠它保持老行为(trim 后为空就不加 Avoid)。 */
64
+ function negativeOf(input) {
65
+ return String((input && input.negativePrompt) || '').trim() || undefined;
66
+ }
67
+
68
+ /**
69
+ * 四个逻辑字段的值(参考图不在这里:每个协议的张数上限不同,由各自的 build 单独喂)。
70
+ * 这四条协议的 maxN 都是 1,所以张数缺省为 1;只在端点接受时写入请求。
71
+ */
72
+ function fieldValuesOf(input) {
73
+ return {
74
+ prompt: promptTextOf(input),
75
+ negative: negativeOf(input),
76
+ model: String((input && input.model) || ''),
77
+ n: 1
78
+ };
79
+ }
80
+
81
+ /**
82
+ * 提示词与负面词按模板落位:负面词可能是独立字段(魔搭的 negative_prompt),
83
+ * 也可能是拼进提示词(BFL / fal / replicate 的 appendToPrompt)。
84
+ * 落点由模板决定,这里只负责把「拼好的提示词」交回去。
85
+ */
86
+ function writePrompt(body, fields, values) {
87
+ const folded = promptParts(fields, values);
88
+ applyFields(body, fields, Object.assign({}, values, { prompt: folded.prompt }));
89
+ return body;
21
90
  }
22
91
 
92
+ /* ------------------------------------------------------- 结果地址的凭据范围 */
93
+
94
+ /*
95
+ * 结果地址不一定是「自己家」的接口:队列服务常常直接给一个对象存储/CDN 的
96
+ * 预签名地址。预签名本来就带授权,不需要我们的 Key;反过来,把 Key 发给
97
+ * 一个没见过的主机就是凭据泄漏。
98
+ *
99
+ * 判定**不在这里**:同源带、跨源默认不带、resultAuthOrigins 声明过的才带,
100
+ * 这套规则只有一份,在 lib/request-auth.js 的 downloadRequestHeaders()。
101
+ * 结果图字节同样只有 fetchResultImage() 一个入口。
102
+ */
103
+
23
104
  function imagesOf(input) {
24
105
  return (Array.isArray(input && input.images) ? input.images : [])
25
106
  .filter((image) => image && image.buffer && image.contentType);
@@ -29,27 +110,28 @@ function sizeOf(input) {
29
110
  const fitted = input && input.fitted;
30
111
  if (!fitted || fitted.omit || fitted.size === 'none' || fitted.size === 'auto') return null;
31
112
  if (!fitted.width || !fitted.height) return null;
32
- return { width: fitted.width, height: fitted.height };
113
+ return { width: fitted.width, height: fitted.height, aspect: fitted.aspect || '', tier: fitted.tier || '' };
33
114
  }
34
115
 
35
116
  /* ------------------------------------------------------------------ BFL */
36
117
 
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) {
118
+ /**
119
+ * 参考图字段由模板给(预设 / 规则里是 `{ numbered: 'input_image' }`,FLUX 3 是
120
+ * `images[]`);这里只决定「用哪条模板」和「最多几张」——张数上限是端点的规矩,
121
+ * 不是字段名。
122
+ */
123
+ async function bflBuild(input, provider) {
43
124
  const model = String(input.model || '');
44
125
  const images = imagesOf(input);
45
- const body = { prompt: promptWithNegative(input) };
126
+ const fields = await fieldsOf('bfl', provider, model);
127
+ const body = writePrompt({}, fields, fieldValuesOf(input));
46
128
  const size = sizeOf(input) || { width: 1024, height: 1024 };
47
129
 
48
130
  // FLUX 3 只认 aspect_ratio / resolution / images,未知字段直接 422。
49
131
  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);
132
+ body.aspect_ratio = size.aspect || nearestAspect(size.width, size.height);
133
+ if (size.tier) body.resolution = String(size.tier);
134
+ if (images.length) applyFields(body, fields, { image: images.slice(0, 10) });
53
135
  return body;
54
136
  }
55
137
 
@@ -57,12 +139,7 @@ function bflBuild(input) {
57
139
  if (/kontext|ultra/i.test(model)) {
58
140
  body.aspect_ratio = nearestAspect(size.width, size.height);
59
141
  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
- }
142
+ if (images.length) applyFields(body, fields, { image: images.slice(0, 4) });
66
143
  return body;
67
144
  }
68
145
 
@@ -70,40 +147,72 @@ function bflBuild(input) {
70
147
  body.height = size.height;
71
148
  body.output_format = 'png';
72
149
  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
- }
150
+ if (images.length) applyFields(body, fields, { image: images.slice(0, 8) });
79
151
  return body;
80
152
  }
81
153
 
82
154
  /* ------------------------------------------------------------------ fal */
83
155
 
84
- function falModelPath(model) {
85
- return '/' + String(model || '').trim().replace(/^\/+/, '');
156
+ const FAL_FLUX_2_PRO = 'fal-ai/flux-2-pro';
157
+ const FAL_KONTEXT_PRO = 'fal-ai/flux-pro/kontext';
158
+ const FAL_KONTEXT_ASPECTS = ['21:9', '16:9', '4:3', '3:2', '1:1', '2:3', '3:4', '9:16', '9:21'];
159
+ const FAL_IMAGE_SINGLE = { path: 'image_url', as: 'dataUrl' };
160
+ const FAL_IMAGE_MULTI = { path: 'image_urls[]', as: 'dataUrl' };
161
+
162
+ /** 预设模型的生成与编辑端点可能有不同的请求形状。 */
163
+ function falRoute(input, imageCount) {
164
+ const model = String(input.model || '').trim().replace(/^\/+/, '');
165
+ if (model === FAL_FLUX_2_PRO || model === FAL_FLUX_2_PRO + '/edit') {
166
+ return {
167
+ path: '/' + FAL_FLUX_2_PRO + (imageCount ? '/edit' : ''),
168
+ image: FAL_IMAGE_MULTI,
169
+ sendsImageCount: false
170
+ };
171
+ }
172
+ if ([FAL_KONTEXT_PRO, FAL_KONTEXT_PRO + '/text-to-image', FAL_KONTEXT_PRO + '/multi'].includes(model)) {
173
+ const multi = imageCount > 1 || model.endsWith('/multi');
174
+ const suffix = imageCount === 0 ? '/text-to-image' : multi ? '/multi' : '';
175
+ return {
176
+ path: '/' + FAL_KONTEXT_PRO + suffix,
177
+ image: multi ? FAL_IMAGE_MULTI : FAL_IMAGE_SINGLE,
178
+ aspects: FAL_KONTEXT_ASPECTS
179
+ };
180
+ }
181
+ return { path: '/' + model, image: imageCount > 1 ? FAL_IMAGE_MULTI : FAL_IMAGE_SINGLE };
86
182
  }
87
183
 
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 };
184
+ async function falBuild(input, provider) {
185
+ const fields = await fieldsOf('fal', provider, String(input.model || ''));
92
186
  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);
187
+ const route = falRoute(input, images.length);
188
+ const values = fieldValuesOf(input);
189
+ if (route.sendsImageCount === false) delete values.n;
190
+ const body = writePrompt({}, fields, values);
191
+ body.output_format = 'jpeg';
192
+ const size = sizeOf(input);
193
+ if (size && route.aspects) body.aspect_ratio = nearestAspect(size.width, size.height, route.aspects);
194
+ else if (size) body.image_size = { width: size.width, height: size.height };
195
+ if (images.length) {
196
+ const declared = fields.image;
197
+ const template = declared && typeof declared === 'object'
198
+ ? declared
199
+ : route.image;
200
+ applyFields(body, { image: template }, { image: images });
201
+ }
96
202
  return body;
97
203
  }
98
204
 
99
205
  /* -------------------------------------------------------------- Replicate */
100
206
 
101
207
  const schemaCache = new Map();
208
+ /** 进行中的 schema 请求:同一模型的并发 build 只发一次,别让参考图和尺寸各查一遍。 */
209
+ const schemaInflight = new Map();
102
210
  const SCHEMA_TTL = 10 * 60 * 1000;
103
211
 
104
- /** 测试用:清掉模型 schema 缓存。 */
212
+ /** 测试用:清掉模型 schema 缓存与进行中的请求占位。 */
105
213
  export function resetAsyncSchemaCache() {
106
214
  schemaCache.clear();
215
+ schemaInflight.clear();
107
216
  }
108
217
 
109
218
  function replicateName(model) {
@@ -112,36 +221,47 @@ function replicateName(model) {
112
221
 
113
222
  const SCHEMA_CACHE_LIMIT = 100;
114
223
 
224
+
115
225
  /** 读模型 Input schema;失败就返回 null,且不缓存失败(瞬时 503 不该让后面 10 分钟都退化)。 */
116
226
  async function inputSchemaOf(provider, model, signal) {
117
227
  const name = replicateName(model);
118
228
  if (!name.includes('/')) return null;
119
- const key = baseUrlOf(provider) + '|' + name;
229
+ const key = baseUrlOf(provider) + '|' + name + '|' + credentialRef(provider);
120
230
  const cached = schemaCache.get(key);
121
231
  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);
232
+ const pending = schemaInflight.get(key);
233
+ if (pending) return pending;
234
+ const task = (async () => {
235
+ try {
236
+ const response = await requestProvider(joinEndpoint(baseUrlOf(provider), '/models/' + name), {
237
+ headers: headersFor(provider, false), signal: signal
238
+ }, provider);
239
+ const payload = await readJsonResponse(response, 5 * 1024 * 1024, provider);
240
+ const schema = payload
241
+ && payload.latest_version
242
+ && payload.latest_version.openapi_schema
243
+ && payload.latest_version.openapi_schema.components
244
+ && payload.latest_version.openapi_schema.components.schemas
245
+ && payload.latest_version.openapi_schema.components.schemas.Input;
246
+ const properties = schema && schema.properties ? schema.properties : null;
247
+ if (!properties) return null;
248
+ if (schemaCache.size >= SCHEMA_CACHE_LIMIT) {
249
+ const oldest = schemaCache.keys().next().value;
250
+ if (oldest) schemaCache.delete(oldest);
251
+ }
252
+ schemaCache.set(key, { at: Date.now(), value: properties });
253
+ return properties;
254
+ } catch (_error) {
255
+ return null;
139
256
  }
140
- schemaCache.set(key, { at: Date.now(), value: properties });
141
- return properties;
142
- } catch (_error) {
143
- return null;
144
- }
257
+ })();
258
+ // 失败同样经过 finally:占位必须清掉,下一次 build 才能重新请求(失败不缓存)。
259
+ let tracked;
260
+ tracked = task.finally(() => {
261
+ if (schemaInflight.get(key) === tracked) schemaInflight.delete(key);
262
+ });
263
+ schemaInflight.set(key, tracked);
264
+ return tracked;
145
265
  }
146
266
 
147
267
  const SCALAR_IMAGE_FIELDS = ['input_image', 'image', 'image_url'];
@@ -187,8 +307,13 @@ function sizeFieldsOf(properties, size) {
187
307
  async function replicateBuild(input, provider, signal) {
188
308
  const images = imagesOf(input);
189
309
  const properties = await inputSchemaOf(provider, input.model, signal);
190
- const payload = { prompt: promptWithNegative(input) };
310
+ const fields = await fieldsOf('replicate', provider, String(input.model || ''));
191
311
  const notes = [];
312
+ // prompt 的落点由模板给(预设是 input.prompt);提交体永远是 { input: {...} }。
313
+ const body = writePrompt({}, fields, fieldValuesOf(input));
314
+ const payload = body.input && typeof body.input === 'object' && !Array.isArray(body.input)
315
+ ? body.input
316
+ : (body.input = {});
192
317
 
193
318
  if (images.length) {
194
319
  const field = imageFieldOf(properties);
@@ -206,22 +331,54 @@ async function replicateBuild(input, provider, signal) {
206
331
  if (size) {
207
332
  const sizeFields = sizeFieldsOf(properties, size);
208
333
  if (sizeFields) Object.assign(payload, sizeFields);
209
- else notes.push('未识别模型的尺寸字段,已省略尺寸');
334
+ else notes.push('未识别模型的尺寸字段,已省略尺寸;要锁定尺寸请开启严格模式');
210
335
  }
211
336
 
212
- return notes.length ? { body: { input: payload }, note: notes.join(';') } : { body: { input: payload } };
337
+ const built = { body: body };
338
+ if (notes.length) built.note = notes.join(';');
339
+ return built;
340
+ }
341
+
342
+ /* ------------------------------------------------------------ ModelScope */
343
+
344
+ /** 魔搭的 OpenAI 兼容地址可能带 /v1,也可能只给站点根;统一到站点根再拼 /v1/...。 */
345
+ function modelscopeRoot(provider) {
346
+ return baseUrlOf(provider).replace(/\/v1$/i, '');
347
+ }
348
+
349
+ async function modelscopeBuild(input, provider) {
350
+ const fields = await fieldsOf('modelscope', provider, String(input.model || ''));
351
+ // 魔搭原生支持 negative_prompt:模板把它写成独立字段({ path: 'negative_prompt' }),
352
+ // 不像不支持的平台那样拼进 prompt。
353
+ const body = writePrompt({}, fields, fieldValuesOf(input));
354
+ const size = sizeOf(input);
355
+ if (size) body.size = size.width + 'x' + size.height;
356
+ const images = imagesOf(input);
357
+ // 图片字段是 image_url:模板的 path 语义正好是「一张发字符串、多张发数组」,网关吃 data URI。
358
+ if (images.length) applyFields(body, fields, { image: images.slice(0, 10) });
359
+ return body;
213
360
  }
214
361
 
215
362
  /* ----------------------------------------------------------------- 描述符 */
216
363
 
364
+ /**
365
+ * fal 的 response_url 正常就是 queue.fal.run 上的接口地址(同源时不需要这里声明),
366
+ * 结果图则落在 v3.fal.media 这类 CDN 上——那是预签名地址,不需要 Key。
367
+ * 这里只列 fal 自家确实要凭据的跨源域名:把 baseUrl 配成 fal.run 时,
368
+ * response_url 仍会落在 queue.fal.run,丢掉 Key 反而会让结果读不出来。
369
+ */
370
+ const FAL_RESULT_AUTH_ORIGINS = ['https://queue.fal.run'];
371
+
217
372
  export const ASYNC_ADAPTERS = [
218
373
  {
219
374
  id: 'bfl',
220
- label: 'Black Forest Labs (FLUX)',
375
+ acceptsHttpParams: true,
376
+ label: 'protocol.bfl',
221
377
  match: (provider) => /(^|\.)bfl\.ai$/i.test(hostOf(provider)),
222
378
  authHeader: 'x-key',
223
379
  local: false,
224
380
  endpoints: { generate: '/v1', edit: '/v1' },
381
+ routes: { generate: '/v1', edit: '/v1', models: '' },
225
382
  transport: { generate: 'json', edit: 'json' },
226
383
  editFields: [],
227
384
  maxN: 1,
@@ -235,41 +392,51 @@ export const ASYNC_ADAPTERS = [
235
392
  async: {
236
393
  edit: true,
237
394
  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
- },
395
+ submitPath: (input) => '/' + String(input.model || '').trim().replace(/^\/+/, '')
396
+ },
397
+ // 轮询头在适配器侧(描述符里不许出现 headers):BFL 默认用 x-key,不是 Bearer;
398
+ // provider.auth 设了就按它来(鉴权是提供商字段,提交与轮询必须是同一套)。
399
+ taskPollHeaders: (provider) => authHeaders(provider, { authHeader: 'x-key' }),
400
+ // 输出格式描述符:轮询地址由提交响应直接给;状态词大写;结果在 result.sample。
401
+ // 迁移前这三个函数在 async 描述符里(pollUrl / statusOf / resolve),字段值一字未改。
402
+ output: outputProfile({
403
+ kind: 'task',
404
+ pollUrlPath: 'polling_url',
405
+ statusPath: 'status',
406
+ success: ['READY'],
407
+ failure: ['ERROR', 'REQUEST MODERATED', 'CONTENT MODERATED', 'NO CARD GENERATED', 'TASK NOT FOUND'],
408
+ // 失败文案来自 payload.detail(迁移前 resolve/statusOf 里就是这么取的)。
409
+ failureMessagePath: ['detail'],
410
+ resultPath: 'result.sample',
254
411
  intervalMs: 1000,
255
- timeoutMs: 300000
256
- }
412
+ // 没有读取方(超时统一由 TOTAL_BUDGET_MS 决定),保留原值,见计划 §7.3-11。
413
+ timeoutMs: 300000,
414
+ maxBytes: 32 * 1024 * 1024,
415
+ emptyMessage: 'BFL 任务完成了但没有返回图片'
416
+ }, 'bfl')
257
417
  },
258
418
  {
259
419
  id: 'fal',
260
- label: 'fal.ai',
420
+ acceptsHttpParams: true,
421
+ label: 'protocol.fal',
261
422
  match: (provider) => /(^|\.)(queue\.)?fal(run)?\.(run|com)$/i.test(hostOf(provider)),
262
423
  authHeader: 'fal-key',
263
424
  local: false,
425
+ // 跨源结果地址的白名单;via 的二次 GET 与结果下载都按同一个声明判断能不能带 Key。
426
+ resultAuthOrigins: FAL_RESULT_AUTH_ORIGINS,
264
427
  endpoints: { generate: '/', edit: '/' },
428
+ routes: { generate: '/', edit: '/', models: '' },
265
429
  transport: { generate: 'json', edit: 'json' },
266
430
  editFields: [],
267
431
  maxN: 1,
268
432
  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);
433
+ const endpoint = /(^|\.)fal\.(run|ai)$/i.test(hostOf(provider))
434
+ ? 'https://api.fal.ai/v1/models?category=text-to-image'
435
+ : joinEndpoint(baseUrlOf(provider), '/models');
436
+ const response = await requestProvider(endpoint, {
437
+ headers: headersFor(provider, false, null, this), signal: signal
438
+ }, provider, this);
439
+ const payload = await readJsonResponse(response, 5 * 1024 * 1024, provider);
273
440
  return (payload && Array.isArray(payload.models) ? payload.models : [])
274
441
  .map((item) => String((item && item.endpoint_id) || '').trim())
275
442
  .filter(Boolean)
@@ -278,47 +445,52 @@ export const ASYNC_ADAPTERS = [
278
445
  async: {
279
446
  edit: true,
280
447
  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) };
448
+ submitPath: (input) => falRoute(input, imagesOf(input).length).path
449
+ },
450
+ // 轮询头在适配器侧:fal 用 `Authorization: Key …`(描述符里不许出现 headers)。
451
+ taskPollHeaders: (provider) => authHeaders(provider, { authHeader: 'fal-key' }),
452
+ // 输出格式描述符:轮询地址在 status_url;结果不在轮询载荷里,要再 GET 一次
453
+ // response_url(提交响应或轮询载荷给)。COMPLETED 却带 error 字段算失败。
454
+ // 迁移前这段逻辑在 async.resolve()/statusOf() 里,URL 来源与判定顺序一字未改。
455
+ output: outputProfile({
456
+ kind: 'task',
457
+ pollUrlPath: 'status_url',
458
+ statusPath: 'status',
459
+ success: ['COMPLETED'],
460
+ // 空数组:迁移前的 statusOf 对 COMPLETED 以外的状态词一律当「还在跑」,
461
+ // 失败信号只看 error 字段(errorPath)。加 'ERROR' 会是行为变更。
462
+ failure: [],
463
+ errorPath: 'error',
464
+ resultPath: 'images.0.url',
465
+ via: {
466
+ kind: 'json-get',
467
+ urlPath: ['submission.response_url', 'payload.response_url'],
468
+ // 迁移前是 readJsonResponse(response, 64MB);不写就会静默变成默认 10MB。
469
+ maxBytes: 64 * 1024 * 1024
302
470
  },
303
471
  intervalMs: 1000,
304
- timeoutMs: 300000
305
- }
472
+ timeoutMs: 300000,
473
+ maxBytes: 32 * 1024 * 1024,
474
+ emptyMessage: 'fal 没有返回图片'
475
+ }, 'fal')
306
476
  },
307
477
  {
308
478
  id: 'replicate',
309
- label: 'Replicate',
479
+ acceptsHttpParams: true,
480
+ label: 'protocol.replicate',
310
481
  match: (provider) => hostOf(provider) === 'api.replicate.com',
311
482
  authHeader: 'bearer',
312
483
  local: false,
313
484
  endpoints: { generate: '/', edit: '/' },
485
+ routes: { generate: '/', edit: '/', models: '' },
314
486
  transport: { generate: 'json', edit: 'json' },
315
487
  editFields: [],
316
488
  maxN: 1,
317
489
  async listModels(provider, signal) {
318
- const response = await request(baseUrlOf(provider) + '/models', {
490
+ const response = await requestProvider(joinEndpoint(baseUrlOf(provider), '/models'), {
319
491
  headers: headersFor(provider, false), signal: signal
320
- });
321
- const payload = await readJsonResponse(response, 5 * 1024 * 1024);
492
+ }, provider, this);
493
+ const payload = await readJsonResponse(response, 5 * 1024 * 1024, provider);
322
494
  return (payload && Array.isArray(payload.results) ? payload.results : [])
323
495
  .map((item) => (item && item.owner && item.name ? item.owner + '/' + item.name : ''))
324
496
  .filter(Boolean)
@@ -327,25 +499,67 @@ export const ASYNC_ADAPTERS = [
327
499
  async: {
328
500
  edit: true,
329
501
  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
- },
502
+ submitPath: (input) => '/models/' + replicateName(input.model) + '/predictions'
503
+ },
504
+ // 轮询头在适配器侧:Replicate 用 Bearer,GET 也带 Content-Type(迁移前就是这个形状)。
505
+ taskPollHeaders: (provider) => headersFor(provider, false),
506
+ // 输出格式描述符:轮询地址在提交响应的 urls.get 里;状态是小写词;结果是 output
507
+ // (可能是字符串,也可能是数组,取第一个)。字段值照搬迁移前的 statusOf / resolve。
508
+ output: outputProfile({
509
+ kind: 'task',
510
+ pollUrlPath: 'urls.get',
511
+ statusPath: 'status',
512
+ success: ['succeeded'],
513
+ failure: ['failed', 'canceled', 'aborted'],
514
+ failureMessagePath: ['error'],
515
+ resultPath: 'output',
347
516
  intervalMs: 1000,
348
- timeoutMs: 300000
349
- }
517
+ timeoutMs: 300000,
518
+ maxBytes: 32 * 1024 * 1024,
519
+ emptyMessage: 'Replicate 任务完成了但没有返回图片'
520
+ }, 'replicate')
521
+ },
522
+ {
523
+ id: 'modelscope',
524
+ acceptsHttpParams: true,
525
+ label: 'protocol.modelscope',
526
+ match: (provider) => /(^|\.)api-inference\.modelscope\.(cn|ai)$/i.test(hostOf(provider)),
527
+ authHeader: 'bearer',
528
+ local: false,
529
+ endpoints: { generate: '/v1/images/generations', edit: '/v1/images/generations' },
530
+ routes: { generate: '/v1/images/generations', edit: '/v1/images/generations', models: '' },
531
+ transport: { generate: 'json', edit: 'json' },
532
+ // 图片生成是任务制:不带这个头拿不到 task_id。
533
+ headers: { 'X-ModelScope-Async-Mode': 'true' },
534
+ editFields: [],
535
+ maxN: 1,
536
+ async: {
537
+ edit: true,
538
+ build: modelscopeBuild,
539
+ submitPath: (input, provider) => modelscopeRoot(provider) + '/v1/images/generations'
540
+ },
541
+ // 轮询头在适配器侧:任务类型是网关要求的**非凭据头**,描述符不开口子放 headers。
542
+ taskPollHeaders: (provider) => Object.assign(
543
+ { 'X-ModelScope-Task-Type': 'image_generation' },
544
+ authHeaders(provider, { authHeader: 'bearer' })
545
+ ),
546
+ // 输出格式描述符:轮询地址按任务 id 自己拼({root} = 去掉末尾 /v1 的站点根,
547
+ // 否则 baseUrl 不带 /v1 时会拼出 /v1/v1/tasks/…);状态是 task_status;
548
+ // 结果先看 output_images(字符串或 {url|image_url}),老网关退 data.0.url。
549
+ output: outputProfile({
550
+ kind: 'task',
551
+ idPath: 'task_id',
552
+ path: '{root}/v1/tasks/{taskId}',
553
+ statusPath: 'task_status',
554
+ success: ['SUCCEED', 'SUCCEEDED', 'SUCCESS'],
555
+ failure: ['FAILED', 'CANCELED', 'CANCELLED', 'ERROR'],
556
+ // 迁移前是 firstMessage() 的递归挖法,键顺序一致;errors:{message} 这类嵌套由深挖覆盖。
557
+ failureMessagePath: ['message', 'msg', 'detail', 'error', 'errors', 'reason', 'logs'],
558
+ resultPath: ['output_images', 'data.0.url'],
559
+ intervalMs: 2000,
560
+ timeoutMs: 300000,
561
+ maxBytes: 32 * 1024 * 1024,
562
+ emptyMessage: 'ModelScope 任务完成了但没有返回图片'
563
+ }, 'modelscope')
350
564
  }
351
565
  ];