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.
@@ -0,0 +1,1225 @@
1
+ /**
2
+ * 输出格式描述符:响应侧「图在哪、怎么落地」的唯一词汇表。
3
+ *
4
+ * 描述符只回答一个问题:**从响应里的哪里读图**。它不碰请求、不碰凭据:
5
+ * - 请求体仍由字段模板 / 参数表 / 常量规则产出,改描述符不会改请求
6
+ * (test/fixtures/adapter-bodies.baseline.json 就是这条的守门人);
7
+ * - 结果图只产出 `{ url }` 或 `{ bytes, contentType }`。下载永远由执行器调
8
+ * fetchResultImage()(同源带凭据、跨源默认不带),见 lib/request-auth.js。
9
+ *
10
+ * 三条铁律写进 validateOutputProfile(),不靠约定:
11
+ * 1. `kind` 只认 json / task / binary;
12
+ * 2. `maxBytes` / `emptyMessage` 必填——各协议体积上限不同、报错文案是行为的一部分。
13
+ * 两者的默认值分别来自 readJsonResponse(10MB)与 decodeImagePayload,但每个协议
14
+ * 都要显式写出它今天的值,否则迁移就是静默行为变更;
15
+ * 3. 描述符里出现 headers / 凭据字段直接拒绝:一旦允许,就是给「裸下载」开一扇门。
16
+ *
17
+ * 迁移期两套写法并存:新写法是 `adapter.output`,老写法是 `adapter.poll`
18
+ * (迁移到一半的适配器与自定义适配器都可能还是后者)。taskSpecOf() 把两者收敛成
19
+ * 同一个读取面,所以执行器只认字段、不认来源。
20
+ *
21
+ * 词汇表按批次长大,每个字段都有唯一的真实消费方:
22
+ * 第一批(ideogram / wanx / 四条异步): kind + pick + scan + task 扁平字段 + via;
23
+ * 第二批(stability / openai-chat): kind:binary、from 级联、text 正则;
24
+ * 第三批(gemini / swarmui / recraft / 其余三条同步): select:last、where、any 交错、
25
+ * contentTypePath、emptyDetail、as:relative、纯 scan 兜底;
26
+ * 第四批(openai-images 通用网关 / comfyui): `output` 可以是**有序候选数组**、task 的路径字段
27
+ * 可以是**有序路径列表**、`path` 支持 `{submitUrl}` 与多模板、`pollUrlFrom:'location'`、
28
+ * `dynamicKey` / `completeWhen:'key'` / `thenUrl` / `backoff`(见各字段旁的注释)。
29
+ *
30
+ * 一条仍然是硬规则:**候选数组的顺序就是行为**。谁先谁后不是审美,是「同一份响应选出哪张图」。
31
+ */
32
+ import {
33
+ base64ToImage, baseUrlOf, decodeImagePayload, errorTextOf, getPath, joinEndpoint, looksLikeImage,
34
+ resolveHttpUrl, sniffType
35
+ } from './adapter-kit.js';
36
+
37
+ /** 与 decodeImagePayload() 的「没有图片」文案一致。 */
38
+ export const DEFAULT_EMPTY_MESSAGE = '生图接口没有返回图片';
39
+
40
+ const KINDS = new Set(['json', 'task', 'binary']);
41
+ const PICK_AS = new Set(['base64', 'url', 'auto', 'dataUrl', 'relative']);
42
+ // 正则扒出来的片段没有「相对谁」的上下文,relative 只对路径取值有意义。
43
+ const TEXT_AS = new Set(['base64', 'url', 'auto', 'dataUrl']);
44
+ const JSON_KEYS = new Set(['kind', 'pick', 'from', 'scan', 'maxBytes', 'emptyMessage', 'emptyDetail']);
45
+ const BINARY_KEYS = new Set(['kind', 'maxBytes', 'emptyMessage']);
46
+ const TASK_KEYS = new Set([
47
+ 'kind', 'path', 'pollUrlPath', 'pollUrlFrom', 'idPath', 'statusPath', 'resultPath',
48
+ 'success', 'failure', 'failureMessagePath', 'errorPath',
49
+ 'intervalMs', 'backoff', 'timeoutMs', 'maxBytes', 'emptyMessage', 'via', 'scan',
50
+ 'dynamicKey', 'completeWhen', 'thenUrl', 'resultAs', 'pollOutput'
51
+ ]);
52
+ const VIA_KEYS = new Set(['kind', 'urlPath', 'maxBytes']);
53
+ const PICK_KEYS = new Set(['path', 'as', 'select', 'any', 'text', 'where', 'contentTypePath']);
54
+ const TEXT_KEYS = new Set(['regex', 'as', 'flags']);
55
+ const WHERE_KEYS = new Set(['path', 'equals', 'notEquals']);
56
+ const EMPTY_DETAIL_KEYS = new Set(['path', 'label']);
57
+ const BACKOFF_KEYS = new Set(['startMs', 'maxMs', 'jitter']);
58
+ const DYNAMIC_KEY_KEYS = new Set(['from']);
59
+ const THEN_URL_KEYS = new Set(['template', 'defaults']);
60
+
61
+ /* ------------------------------------------------------------------ 校验 */
62
+
63
+ /** header / 凭据类键名:命中就拒绝,递归检查。 */
64
+ function isCredentialKey(key) {
65
+ const text = String(key || '').toLowerCase().replace(/[-_\s]/g, '');
66
+ if (!text) return false;
67
+ if (text === 'header' || text === 'headers') return true;
68
+ if (text.endsWith('header') || text.endsWith('headers')) return true;
69
+ return ['authorization', 'auth', 'key', 'apikey', 'token', 'secret', 'credential', 'credentials'].includes(text);
70
+ }
71
+
72
+ function assertNoCredentials(node, trail, label) {
73
+ if (!node || typeof node !== 'object') return;
74
+ for (const key of Object.keys(node)) {
75
+ if (isCredentialKey(key)) {
76
+ throw new Error('输出描述符里不许出现凭据字段' + label + ':' + trail + key
77
+ + '(只产出 { url },下载统一走 fetchResultImage)');
78
+ }
79
+ assertNoCredentials(node[key], trail + key + '.', label);
80
+ }
81
+ }
82
+
83
+ function positiveNumber(value, key, label) {
84
+ const number = Number(value);
85
+ if (!Number.isFinite(number) || number <= 0) {
86
+ throw new Error('输出描述符缺少有效的 ' + key + '(必填)' + label);
87
+ }
88
+ return number;
89
+ }
90
+
91
+ function nonEmptyText(value, key, label) {
92
+ const text = value === undefined || value === null ? '' : String(value).trim();
93
+ if (!text) throw new Error('输出描述符缺少 ' + key + '(必填)' + label);
94
+ return text;
95
+ }
96
+
97
+ function pathText(profile, key, label) {
98
+ return nonEmptyText(profile[key], key, label);
99
+ }
100
+
101
+ function optionalText(value) {
102
+ return value === undefined || value === null ? '' : String(value).trim();
103
+ }
104
+
105
+ /**
106
+ * 有序路径字段:可以写一条,也可以写一列(**顺序即优先级**,第一个有值的赢)。
107
+ *
108
+ * 为什么是列表:通用网关认任务 id / 轮询地址 / 状态词时,**键的优先序高于层级**
109
+ * (嵌套的 `task_id` 要压过顶层的 `id`,`polling_url` 要压过 `status_url`),
110
+ * 一条路径表达不了这张表;顺序写错就是「同一份响应认成另一个任务」。
111
+ */
112
+ function pathList(value, key, label) {
113
+ const raw = Array.isArray(value) ? value : [value];
114
+ if (!raw.length) throw new Error('输出描述符的 ' + key + ' 必须是非空字符串或数组' + label);
115
+ return raw.map((item) => {
116
+ const text = optionalText(item);
117
+ if (!text) throw new Error('输出描述符的 ' + key + ' 里有空值' + label);
118
+ return text;
119
+ });
120
+ }
121
+
122
+ /** 有序路径字段存在时才校验(没写=沿用默认值,由各读取器决定)。 */
123
+ function optionalPathList(profile, key, label) {
124
+ if (profile[key] === undefined) return null;
125
+ return pathList(profile[key], key, label);
126
+ }
127
+
128
+ /** 读取面用:没写就是空列表。 */
129
+ function pathsOf(value) {
130
+ if (value === undefined || value === null) return [];
131
+ const raw = Array.isArray(value) ? value : [value];
132
+ return raw.map((item) => optionalText(item)).filter(Boolean);
133
+ }
134
+
135
+ /** 非空字符串数组:状态词表、失败文案路径表都用它。 */
136
+ function textList(value, key, label) {
137
+ if (!Array.isArray(value) || !value.length) {
138
+ throw new Error('输出描述符的 ' + key + ' 必须是非空字符串数组' + label);
139
+ }
140
+ return value.map((item) => {
141
+ const text = optionalText(item);
142
+ if (!text) throw new Error('输出描述符的 ' + key + ' 里有空值' + label);
143
+ return text;
144
+ });
145
+ }
146
+
147
+ /**
148
+ * 结果图路径可以写一条,也可以写一列候选(有序):魔搭先看 output_images,
149
+ * 老网关回的是 data.0.url。第一个「有值」的赢,空数组按没有处理。
150
+ */
151
+ function resultPathList(profile, label) {
152
+ const raw = profile.resultPath;
153
+ const list = Array.isArray(raw) ? raw : [raw];
154
+ if (!list.length) throw new Error('task 描述符需要非空的 resultPath' + label);
155
+ return list.map((item) => {
156
+ const text = optionalText(item);
157
+ if (!text) throw new Error('task 描述符的 resultPath 里有空值' + label);
158
+ return text;
159
+ });
160
+ }
161
+
162
+ /**
163
+ * 字段白名单:拼错的键(`statisPath` / `scanning`)不能静默落到默认值,
164
+ * 否则「写了但没生效」比报错更难查。
165
+ */
166
+ function assertKnownKeys(profile, allowed, label) {
167
+ for (const key of Object.keys(profile)) {
168
+ if (allowed.has(key)) continue;
169
+ throw new Error('输出描述符里有不认识的字段 ' + key + label
170
+ + '(认识的:' + Array.from(allowed).join(' / ') + ')');
171
+ }
172
+ }
173
+
174
+ /**
175
+ * 校验一份输出描述符;不合法直接抛错(在适配器定义时调用,坏描述符进不了运行时)。
176
+ * `where` 只用于把报错定位到某个协议,例如 'ideogram'。
177
+ */
178
+ export function validateOutputProfile(profile, where) {
179
+ const label = where ? '(' + where + ')' : '';
180
+ if (!profile || typeof profile !== 'object' || Array.isArray(profile)) {
181
+ throw new Error('输出描述符必须是一个对象' + label);
182
+ }
183
+ assertNoCredentials(profile, '', label);
184
+ const kind = String(profile.kind || '');
185
+ if (!KINDS.has(kind)) {
186
+ throw new Error('输出描述符的 kind 只认 json / task / binary' + label + ':' + (kind || '(空)'));
187
+ }
188
+ positiveNumber(profile.maxBytes, 'maxBytes', label);
189
+ nonEmptyText(profile.emptyMessage, 'emptyMessage', label);
190
+ if (kind === 'json') validateJson(profile, label);
191
+ else if (kind === 'binary') validateBinary(profile, label);
192
+ else validateTask(profile, label);
193
+ return profile;
194
+ }
195
+
196
+ /**
197
+ * binary:响应体本身就是图片(stability)。没有 pick / from / scan——
198
+ * 但读法仍要吃 JSON `{image:"<base64>"}` 形态(见 readBinaryOutput)。
199
+ */
200
+ function validateBinary(profile, label) {
201
+ assertKnownKeys(profile, BINARY_KEYS, label);
202
+ }
203
+
204
+ /**
205
+ * json:一条 pick 或一个 from 级联。
206
+ *
207
+ * `from` 是有序多来源(openai-chat):每一项本身都是一个 pick,
208
+ * 逐项试,第一项产出图就停;全部落空且 `scan:true` 才兜底扫描。
209
+ * `text` 让 pick 从文本里正则扒图({regex, as, flags?}),
210
+ * 正则按声明顺序**跨全部文本**执行(先所有文本找第一条正则,再第二条)——
211
+ * 这是 openai-chat 迁移前的真实循环顺序,逐段文本依次试会选出不同的图。
212
+ *
213
+ * `scan:true` 也可以单独出现(recraft):今天就是 decodeImagePayload 的任意位置扫描,
214
+ * 收紧成一条路径是行为变化,所以允许「纯兜底」形状。
215
+ */
216
+ function validateJson(profile, label) {
217
+ const picks = profile.pick === undefined ? [] : profile.pick;
218
+ const from = profile.from === undefined ? [] : profile.from;
219
+ if (!Array.isArray(picks)) throw new Error('json 描述符的 pick 必须是数组' + label);
220
+ if (!Array.isArray(from)) throw new Error('json 描述符的 from 必须是数组' + label);
221
+ if (profile.pick !== undefined && !picks.length) {
222
+ throw new Error('json 描述符的 pick 不能是空数组' + label);
223
+ }
224
+ if (profile.from !== undefined && !from.length) {
225
+ throw new Error('json 描述符的 from 不能是空数组' + label);
226
+ }
227
+ if (!picks.length && !from.length && profile.scan !== true) {
228
+ throw new Error('json 描述符需要非空的 pick 或 from(或 scan:true 的纯兜底形状)' + label);
229
+ }
230
+ if (profile.scan !== undefined && typeof profile.scan !== 'boolean') {
231
+ throw new Error('json 描述符的 scan 只能是布尔值' + label);
232
+ }
233
+ if (profile.emptyDetail !== undefined) validateEmptyDetail(profile.emptyDetail, label);
234
+ picks.forEach((pick, index) => validatePick(pick, '(pick[' + index + '])' + label));
235
+ from.forEach((pick, index) => validatePick(pick, '(from[' + index + '])' + label));
236
+ assertKnownKeys(profile, JSON_KEYS, label);
237
+ }
238
+
239
+ /**
240
+ * `emptyDetail`:无图时把上游给的原因拼进报错(Gemini 的 `finishReason=SAFETY`)。
241
+ * 值缺失时**整段括号都不出现**——迁移前就是 `finish ? '(…)' : ''`。
242
+ */
243
+ function validateEmptyDetail(detail, label) {
244
+ const at = '(emptyDetail)' + label;
245
+ if (!detail || typeof detail !== 'object' || Array.isArray(detail)) {
246
+ throw new Error('emptyDetail 必须是对象' + label);
247
+ }
248
+ nonEmptyText(detail.path, 'emptyDetail.path', label);
249
+ nonEmptyText(detail.label, 'emptyDetail.label', label);
250
+ assertKnownKeys(detail, EMPTY_DETAIL_KEYS, at);
251
+ }
252
+
253
+ /** 一个 pick / from 条目:位置(path)+ 动作(as / any / where / text)。 */
254
+ function validatePick(pick, label) {
255
+ if (!pick || typeof pick !== 'object' || Array.isArray(pick)) {
256
+ throw new Error('pick 必须是对象' + label);
257
+ }
258
+ pathText(pick, 'path', label);
259
+ if (pick.text !== undefined) {
260
+ // 文本条目自己带 as,条目级的 as / any / select / where / contentTypePath 没有读取方,直接拒绝。
261
+ for (const key of ['as', 'any', 'select', 'where', 'contentTypePath']) {
262
+ if (pick[key] !== undefined) {
263
+ throw new Error('带 text 的 pick 不能再写 ' + key + '(动作写在 text[].as 里)' + label);
264
+ }
265
+ }
266
+ validateText(pick.text, label);
267
+ } else {
268
+ const as = pick.as === undefined ? 'auto' : String(pick.as);
269
+ if (!PICK_AS.has(as)) {
270
+ throw new Error('pick.as 只认 ' + Array.from(PICK_AS).join(' / ') + label + ':' + as);
271
+ }
272
+ if (pick.select !== undefined && pick.select !== 'first' && pick.select !== 'last') {
273
+ throw new Error('pick.select 只认 first / last(all 还没有消费者)' + label + ':' + pick.select);
274
+ }
275
+ if (pick.any !== undefined) {
276
+ if (!Array.isArray(pick.any) || !pick.any.length) {
277
+ throw new Error('pick.any 必须是非空字符串数组' + label);
278
+ }
279
+ for (const path of pick.any) {
280
+ if (typeof path !== 'string') {
281
+ throw new Error('pick.any 的每一项都必须是字符串("" = 元素本身)' + label);
282
+ }
283
+ }
284
+ }
285
+ if (pick.where !== undefined) validateWhere(pick, label);
286
+ if (pick.contentTypePath !== undefined) validateContentTypePath(pick.contentTypePath, label);
287
+ }
288
+ assertKnownKeys(pick, PICK_KEYS, label);
289
+ }
290
+
291
+ /**
292
+ * `where`:过滤 `[]` 产出的元素。只支持列表路径——单值路径上写它就是静默不生效。
293
+ * 条件必须恰有一个 `equals` 或 `notEquals`(`notEquals` 保留「没有这个字段」的元素,
294
+ * gemini 的 `part.thought === true` 才跳就是这么来的)。
295
+ */
296
+ function validateWhere(pick, label) {
297
+ if (!String(pick.path).includes('[]')) {
298
+ throw new Error('pick.where 只能用在 [] 路径上(单值路径没有候选可过滤)' + label);
299
+ }
300
+ if (!Array.isArray(pick.where) || !pick.where.length) {
301
+ throw new Error('pick.where 必须是非空数组' + label);
302
+ }
303
+ pick.where.forEach((condition, index) => {
304
+ const at = '(where[' + index + '])' + label;
305
+ if (!condition || typeof condition !== 'object' || Array.isArray(condition)) {
306
+ throw new Error('pick.where 的每一项必须是对象' + at);
307
+ }
308
+ pathText(condition, 'path', at);
309
+ // 先把拼错的键(equal / 不等于 …)报出来,再谈「恰有一个」——否则一个拼写错误会变成一句
310
+ // 让人去数条件的报错。
311
+ assertKnownKeys(condition, WHERE_KEYS, at);
312
+ const hasEquals = condition.equals !== undefined;
313
+ const hasNotEquals = condition.notEquals !== undefined;
314
+ if (hasEquals === hasNotEquals) {
315
+ throw new Error('pick.where 的每一项要恰有一个 equals 或 notEquals' + at);
316
+ }
317
+ });
318
+ }
319
+
320
+ /**
321
+ * `contentTypePath`:contentType 覆盖,可写多条候选(驼峰 / 蛇形)。
322
+ * 相对「命中元素」:path 以 `[]` 结尾时就是元素本身(gemini 的 part),
323
+ * 否则是 path 的父对象(openrouter 的 `data.0`)。
324
+ */
325
+ function validateContentTypePath(value, label) {
326
+ const list = Array.isArray(value) ? value : [value];
327
+ if (!list.length) throw new Error('pick.contentTypePath 必须是非空字符串或数组' + label);
328
+ for (const item of list) {
329
+ if (typeof item !== 'string' || !item.trim()) {
330
+ throw new Error('pick.contentTypePath 的每一项都必须是非空字符串' + label);
331
+ }
332
+ }
333
+ }
334
+
335
+ /** 文本正则条目:regex 必须能编译,as 只认四种图片解释方式,flags 缺省 i。 */
336
+ function validateText(rules, label) {
337
+ if (!Array.isArray(rules) || !rules.length) {
338
+ throw new Error('pick.text 必须是非空数组' + label);
339
+ }
340
+ rules.forEach((rule, index) => {
341
+ const at = '(text[' + index + '])' + label;
342
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule)) {
343
+ throw new Error('pick.text 的每一项必须是对象' + at);
344
+ }
345
+ const regex = nonEmptyText(rule.regex, 'regex', at);
346
+ const flags = rule.flags === undefined ? 'i' : String(rule.flags);
347
+ try {
348
+ new RegExp(regex, flags);
349
+ } catch (error) {
350
+ throw new Error('pick.text 的正则编译失败' + at + ':' + error.message);
351
+ }
352
+ const as = rule.as === undefined ? 'auto' : String(rule.as);
353
+ if (!TEXT_AS.has(as)) {
354
+ throw new Error('pick.text.as 只认 ' + Array.from(TEXT_AS).join(' / ') + at + ':' + as);
355
+ }
356
+ assertKnownKeys(rule, TEXT_KEYS, at);
357
+ });
358
+ }
359
+
360
+ /**
361
+ * task 分支:扁平字段(照 dashscope-wanx 现有的 poll 形状搬过来,字段名一字不改)。
362
+ *
363
+ * 轮询地址三种来源,按「先看响应、再按 id 拼、最后看响应头」排:
364
+ * - `pollUrlPath`:地址在**提交响应**里(BFL 的 polling_url、Replicate 的 urls.get、fal 的 status_url);
365
+ * - `path`:按任务 id 拼(`/tasks/{taskId}`;`{root}` = 去掉末尾 /v1 的站点根,
366
+ * `{submitUrl}` = 这次提交用的地址)。写多条就是**有序候选**,前一条 404/405 才换下一条;
367
+ * - `pollUrlFrom:'location'`:地址在 202/302 的 `Location` 响应头里(没有任务体)。
368
+ * 其余字段缺省即保持迁移前的行为,见各字段旁的注释。
369
+ *
370
+ * 路径字段(`idPath` / `statusPath` / `errorPath` / `pollUrlPath`)都可以写**有序列表**:
371
+ * 每项按顺序取第一个有值的——这就是通用网关「键表优先序」的数据化写法。
372
+ */
373
+ function validateTask(profile, label) {
374
+ if (profile.pollOutput !== undefined && !['json', 'binary'].includes(profile.pollOutput)) {
375
+ throw new Error('task 描述符的 pollOutput 只支持 json 或 binary' + label);
376
+ }
377
+ if (profile.resultAs !== undefined && !PICK_AS.has(profile.resultAs)) {
378
+ throw new Error('task 描述符的 resultAs 无效' + label);
379
+ }
380
+ const paths = profile.path === undefined ? [] : pathList(profile.path, 'path', label);
381
+ const pollPaths = optionalPathList(profile, 'pollUrlPath', label) || [];
382
+ const pollFrom = optionalText(profile.pollUrlFrom);
383
+ if (!paths.length && !pollPaths.length && !pollFrom) {
384
+ throw new Error('task 描述符需要 path(按任务 id 拼轮询地址)、pollUrlPath(轮询地址在提交响应里)'
385
+ + '或 pollUrlFrom(轮询地址在响应头里)' + label);
386
+ }
387
+ if (pollFrom && pollFrom !== 'location') {
388
+ throw new Error('task 描述符的 pollUrlFrom 只认 location(唯一有标准含义的任务轮询响应头)' + label + ':' + pollFrom);
389
+ }
390
+ if (pollFrom && (paths.length || pollPaths.length)) {
391
+ throw new Error('task 描述符的 pollUrlFrom 不能和 path / pollUrlPath 同时写(地址到底从哪来只能有一个答案)' + label);
392
+ }
393
+ const idPaths = optionalPathList(profile, 'idPath', label);
394
+ if (!idPaths && paths.some((template) => template.includes('{taskId}'))) pathText(profile, 'idPath', label);
395
+ // statusPath 是「状态词从哪读」;只有 completeWhen:key 这种没有状态词的形状可以省。
396
+ const statusPaths = optionalPathList(profile, 'statusPath', label);
397
+ const binary = profile.pollOutput === 'binary';
398
+ if (!binary && !statusPaths && profile.completeWhen === undefined) pathText(profile, 'statusPath', label);
399
+ optionalPathList(profile, 'errorPath', label);
400
+ if (!binary || profile.resultPath !== undefined) resultPathList(profile, label);
401
+ // `completeWhen:'key'` 的形状没有状态词可等(ComfyUI),success 允许空数组;
402
+ // 其余形状必须有成功词表,否则任务永远不会被认成完成。
403
+ if (!Array.isArray(profile.success)) {
404
+ throw new Error('task 描述符需要 success 数组' + label);
405
+ }
406
+ if (!binary && profile.completeWhen === undefined && !profile.success.length) {
407
+ throw new Error('task 描述符需要非空的 success' + label);
408
+ }
409
+ if (profile.success.length) textList(profile.success, 'success', label);
410
+ if (!Array.isArray(profile.failure)) {
411
+ throw new Error('task 描述符需要 failure 数组' + label);
412
+ }
413
+ // 允许空数组:fal 的失败信号在 error 字段里,不在状态词里(见 errorPath)。
414
+ if (profile.failure.length) textList(profile.failure, 'failure', label);
415
+ if (profile.failureMessagePath !== undefined) {
416
+ textList(profile.failureMessagePath, 'failureMessagePath', label);
417
+ }
418
+ // 轮询间隔:固定间隔(intervalMs)或退避曲线(backoff)二选一,写两个就是两个都生效、
419
+ // 谁也说不清哪个算数,所以直接拒。
420
+ if (profile.backoff !== undefined) validateBackoff(profile, label);
421
+ if (profile.intervalMs !== undefined) positiveNumber(profile.intervalMs, 'intervalMs', label);
422
+ if (profile.backoff === undefined && profile.intervalMs === undefined) {
423
+ throw new Error('task 描述符需要 intervalMs(固定间隔)或 backoff(退避曲线)' + label);
424
+ }
425
+ // timeoutMs 现在没有读取方(超时统一由 TOTAL_BUDGET_MS 决定),保留字段以免预设数据丢值。
426
+ if (profile.timeoutMs !== undefined) positiveNumber(profile.timeoutMs, 'timeoutMs', label);
427
+ if (profile.scan !== undefined && typeof profile.scan !== 'boolean') {
428
+ throw new Error('task 描述符的 scan 只能是布尔值' + label);
429
+ }
430
+ if (profile.dynamicKey !== undefined) validateDynamicKey(profile, label);
431
+ if (profile.completeWhen !== undefined) {
432
+ if (profile.completeWhen !== 'key') {
433
+ throw new Error('task 描述符的 completeWhen 只认 key(键出现即完成)' + label + ':' + profile.completeWhen);
434
+ }
435
+ if (profile.dynamicKey === undefined) {
436
+ throw new Error('task 描述符的 completeWhen:key 需要 dynamicKey 说明是哪一层键' + label);
437
+ }
438
+ }
439
+ if (profile.thenUrl !== undefined) validateThenUrl(profile.thenUrl, label);
440
+ if (profile.via !== undefined) validateVia(profile.via, label);
441
+ for (const key of ['submit', 'poll', 'result']) {
442
+ if (profile[key] !== undefined) {
443
+ throw new Error('task 描述符是扁平字段,不支持嵌套的 ' + key + '(字段名与 wanx 的 poll 一致)' + label);
444
+ }
445
+ }
446
+ assertKnownKeys(profile, TASK_KEYS, label);
447
+ }
448
+
449
+ /**
450
+ * `backoff`:退避曲线。`startMs` 起步、每次乘 1.15(`jitter:true` 时再乘 1.0~1.15 的随机抖动)、
451
+ * `maxMs`(缺省 5000)封顶。消费方是 `nextBackoff()`,与执行器里原来的固定 ×1.15 是同一条曲线,
452
+ * 所以「不写 jitter」就等于今天的行为。
453
+ */
454
+ function validateBackoff(profile, label) {
455
+ const backoff = profile.backoff;
456
+ const at = '(backoff)' + label;
457
+ if (!backoff || typeof backoff !== 'object' || Array.isArray(backoff)) {
458
+ throw new Error('backoff 必须是对象' + label);
459
+ }
460
+ assertKnownKeys(backoff, BACKOFF_KEYS, at);
461
+ positiveNumber(backoff.startMs, 'backoff.startMs', label);
462
+ if (backoff.maxMs !== undefined) positiveNumber(backoff.maxMs, 'backoff.maxMs', label);
463
+ if (backoff.jitter !== undefined && typeof backoff.jitter !== 'boolean') {
464
+ throw new Error('backoff.jitter 只能是布尔值' + label);
465
+ }
466
+ if (profile.intervalMs !== undefined) {
467
+ throw new Error('backoff 与 intervalMs 二选一:两条曲线同时写,读的人不知道哪个算数' + label);
468
+ }
469
+ }
470
+
471
+ /**
472
+ * `dynamicKey`:载荷里有一层**运行时动态键**(ComfyUI 的 `payload[promptId]`)。
473
+ * 声明之后,`statusPath` / `resultPath` / `failureMessagePath` 都相对那一层算,
474
+ * 读取器用 `taskBasisOf()` 取基准;键还没出现就是「任务还没好」。
475
+ */
476
+ function validateDynamicKey(profile, label) {
477
+ const dynamic = profile.dynamicKey;
478
+ const at = '(dynamicKey)' + label;
479
+ if (!dynamic || typeof dynamic !== 'object' || Array.isArray(dynamic)) {
480
+ throw new Error('dynamicKey 必须是对象' + label);
481
+ }
482
+ assertKnownKeys(dynamic, DYNAMIC_KEY_KEYS, at);
483
+ if (optionalText(dynamic.from) !== 'taskId') {
484
+ throw new Error('dynamicKey.from 只认 taskId(运行时只有这一个值可以充当路径段)' + at
485
+ + ':' + (optionalText(dynamic.from) || '(空)'));
486
+ }
487
+ }
488
+
489
+ /**
490
+ * `thenUrl`:结果不是 URL,而是几个字段要拼成**第二跳**的地址(ComfyUI 的
491
+ * `/view?filename={filename}&subfolder={subfolder}&type={type}`)。
492
+ *
493
+ * 占位符从「结果节点」里取同名字段;值缺失时用 `defaults` 兜(`subfolder:''` / `type:'output'`
494
+ * 就是今天 `||` 的默认值)。既没有值也没有默认值的占位符 = 这条结果不能用,换下一条。
495
+ * 查询部分一律走 `URLSearchParams`(空格变 +、空值保留成 `subfolder=`)——迁移前就是这样。
496
+ */
497
+ function validateThenUrl(thenUrl, label) {
498
+ const at = '(thenUrl)' + label;
499
+ if (!thenUrl || typeof thenUrl !== 'object' || Array.isArray(thenUrl)) {
500
+ throw new Error('thenUrl 必须是对象' + label);
501
+ }
502
+ nonEmptyText(thenUrl.template, 'thenUrl.template', label);
503
+ if (!/{[A-Za-z0-9_]+}/.test(String(thenUrl.template))) {
504
+ throw new Error('thenUrl.template 里没有占位符(那就不是模板,直接写 URL 就行)' + at);
505
+ }
506
+ if (thenUrl.defaults !== undefined) {
507
+ const defaults = thenUrl.defaults;
508
+ if (!defaults || typeof defaults !== 'object' || Array.isArray(defaults)) {
509
+ throw new Error('thenUrl.defaults 必须是对象' + at);
510
+ }
511
+ for (const key of Object.keys(defaults)) {
512
+ if (typeof defaults[key] !== 'string') {
513
+ throw new Error('thenUrl.defaults.' + key + ' 必须是字符串(占位符只能落成文本)' + at);
514
+ }
515
+ }
516
+ }
517
+ assertKnownKeys(thenUrl, THEN_URL_KEYS, at);
518
+ }
519
+
520
+ /** fal 那类:轮询结束还要再 GET 一次结果 JSON。描述符只说「GET 哪个地址」,请求头由适配器侧决定。 */
521
+ function validateVia(via, label) {
522
+ if (!via || typeof via !== 'object' || Array.isArray(via)) {
523
+ throw new Error('task 描述符的 via 必须是对象' + label);
524
+ }
525
+ const kind = optionalText(via.kind);
526
+ if (kind !== 'json-get') {
527
+ throw new Error('task 描述符的 via.kind 只认 json-get' + label + ':' + (kind || '(空)'));
528
+ }
529
+ textList(via.urlPath, 'via.urlPath', label);
530
+ // 结果 JSON 的体积上限与轮询响应不同(fal 是 64MB,轮询是 32MB),必须显式写,避免静默落回默认值。
531
+ positiveNumber(via.maxBytes, 'via.maxBytes', label);
532
+ assertKnownKeys(via, VIA_KEYS, '(via)' + label);
533
+ }
534
+
535
+ /** 定义时调用:校验 + 冻结。适配器写 `output: outputProfile({...}, 'ideogram')`。 */
536
+ export function outputProfile(definition, where) {
537
+ validateOutputProfile(definition, where);
538
+ return Object.freeze(definition);
539
+ }
540
+
541
+ /**
542
+ * 定义时调用:**有序候选数组**。每一项各自过一遍铁律(它仍然是「一个描述符」),
543
+ * 数组本身只多一条约束:非空。顺序即优先级,注释里要写清为什么是这个顺序。
544
+ */
545
+ export function outputProfiles(definitions, where) {
546
+ const label = where ? '(' + where + ')' : '';
547
+ if (!Array.isArray(definitions) || !definitions.length) {
548
+ throw new Error('输出描述符候选列表必须是非空数组' + label);
549
+ }
550
+ definitions.forEach((definition, index) => {
551
+ validateOutputProfile(definition, (where ? where + ' ' : '') + '候选[' + index + ']');
552
+ });
553
+ return Object.freeze(definitions.slice());
554
+ }
555
+
556
+ /* ------------------------------------------------------------------ 读取 */
557
+
558
+ function isHttpUrl(value) {
559
+ return typeof value === 'string' && /^https?:\/\//i.test(value);
560
+ }
561
+
562
+ /** 一个 pick 命中的值 → 图;解释不了就返回 null(继续下一个候选)。 */
563
+ function imageOfPick(value, pick, options) {
564
+ if (value === undefined || value === null) return null;
565
+ const as = pick.as === undefined ? 'auto' : String(pick.as);
566
+ if (as === 'url') return isHttpUrl(value) ? { url: value } : null;
567
+ if (as === 'dataUrl') {
568
+ return typeof value === 'string' && /^data:image\//i.test(value) ? base64ToImage(value) : null;
569
+ }
570
+ if (as === 'base64') return base64ToImage(value);
571
+ if (as === 'relative') {
572
+ // 「相对路径」= 既不是 data URL 也不是 http(s):拼到 provider 站点根上再交给 fetchResultImage。
573
+ const text = optionalText(value);
574
+ const base = optionalText(options && options.baseUrl).replace(/\/+$/, '');
575
+ if (!text || !base || /^data:/i.test(text) || isHttpUrl(text)) return null;
576
+ const url = options?.responseUrl ? resolveHttpUrl(text, options.responseUrl) : joinEndpoint(base, text);
577
+ return url ? { url } : null;
578
+ }
579
+ // auto:先当 base64(含 data URL)解,再认 http(s)——与 decodeImagePayload 的扫描顺序一致。
580
+ return base64ToImage(value) || (isHttpUrl(value) ? { url: value } : null);
581
+ }
582
+
583
+ /**
584
+ * 从响应载荷里取图。只产出 `{ bytes, contentType }` 或 `{ url }`,**不发请求**。
585
+ *
586
+ * json:
587
+ * - 按 `pick` → `from` 的顺序逐项试,第一项产出图就停;
588
+ * - 每一项默认是一个位置;`any` 给同一逻辑位置的多种拼写(按元素交错判定),
589
+ * `text` 则把命中的值当文本、按正则扒图;
590
+ * - `path` 里的 `[]` 表示「数组每元素」,产出列表(`images[]` / `parts[].text`);
591
+ * `where` 过滤这些元素,`select:'last'` 把候选列反过来(每个候选仍然试到底);
592
+ * - `contentTypePath` 覆盖 contentType(相对命中元素,见 validateContentTypePath);
593
+ * - 全部落空且 `scan:true` 时交给 decodeImagePayload() 兜底扫描
594
+ * (「先全表 base64 → 再带图片后缀的 URL → 再任意 URL」的顺序与迁移前一致)。
595
+ * 带 `from` 的级联把 scan 当最后一级:它再落空就抛 emptyMessage——openai-chat
596
+ * 迁移前就是吞掉扫描错误再报自己的文案;只有 pick 的描述符保持 decode 的原文案。
597
+ * - `emptyDetail` 在有值时给 emptyMessage 补一句 `(label=值)`(Gemini 的 finishReason)。
598
+ *
599
+ * binary(stability):响应体本身就是图片,但 JSON `{image:"<base64>"}` 形态也要照吃。
600
+ * `options.binary` 是 readResponseBytes() 读回来的 Buffer,`options.contentType` 是响应头;
601
+ * 后者是图片类型就用它,否则按图片签名(sniffType)兜底。
602
+ * `options.baseUrl` 只给 `as:'relative'` 用(按 provider 站点根拼相对路径)。
603
+ */
604
+ export function readOutput(payload, profile, options) {
605
+ // 候选数组:按顺序试,第一个解析出图的赢(见 readOutputCandidates)。
606
+ if (Array.isArray(profile)) return readOutputCandidates(payload, profile, options);
607
+ const output = profile || {};
608
+ const opts = options || {};
609
+ if (output.kind === 'binary') return readBinaryOutput(payload, opts.binary, output, opts);
610
+ if (output.kind !== 'json') {
611
+ throw new Error('readOutput 只处理 kind:json / kind:binary;task 的结果用 readTaskImage()');
612
+ }
613
+ for (const pick of (output.pick || []).concat(output.from || [])) {
614
+ const found = readPick(payload, pick, opts);
615
+ if (found) return found;
616
+ }
617
+ if (output.scan) {
618
+ try {
619
+ // 扫描兜底连响应体一起交给 decodeImagePayload:通用网关的最后一级就是
620
+ // `decodeImagePayload(parsed, buffer)`(非 JSON 的裸图片也要能落地)。
621
+ return decodeImagePayload(payload, opts.binary || null);
622
+ } catch (error) {
623
+ if (!Array.isArray(output.from) || !output.from.length) throw error;
624
+ throw new Error(emptyMessageOf(output, payload));
625
+ }
626
+ }
627
+ throw new Error(emptyMessageOf(output, payload));
628
+ }
629
+
630
+ /** 候选列表归一:一个描述符也可以(迁移期的中间态与单形状协议都吃)。 */
631
+ export function outputCandidatesOf(output) {
632
+ if (Array.isArray(output)) return output;
633
+ return output && typeof output === 'object' ? [output] : [];
634
+ }
635
+
636
+ /**
637
+ * 有序候选数组:**按顺序试,第一个解析出图的赢**;全部落空抛**最后一个候选**自己的错误。
638
+ *
639
+ * 为什么不是统一文案:最后一项通常是 `scan:true` 的兜底,它抛的是 decodeImagePayload 的
640
+ * 「格式不认识」/「没有返回图片」——迁移前通用网关最后一步就是它,换成统一文案就是行为变更。
641
+ *
642
+ * 说明两件事:
643
+ * 1. 这里只读**响应体**,不下载(下载由执行器交给 fetchResultImage);
644
+ * 「URL 下不下来」是执行器那层的判定,所以这个函数返回的图还要过一道 fetch;
645
+ * 2. `task` 候选不在这里读(它要轮询):执行器先用 taskPlanOf() 判断「这份提交响应认不认得出任务」。
646
+ */
647
+ export function readOutputCandidates(payload, output, options) {
648
+ const candidates = outputCandidatesOf(output);
649
+ if (!candidates.length) throw new Error('输出描述符候选列表是空的');
650
+ let lastError = null;
651
+ for (const candidate of candidates) {
652
+ if (candidate && candidate.kind === 'task') continue;
653
+ try {
654
+ return readOutput(payload, candidate, options);
655
+ } catch (error) {
656
+ lastError = error;
657
+ }
658
+ }
659
+ if (lastError) throw lastError;
660
+ throw new Error(candidates[candidates.length - 1].emptyMessage || DEFAULT_EMPTY_MESSAGE);
661
+ }
662
+
663
+ /** 无图文案:`emptyDetail` 有值就补「(label=值)」,缺值整段括号都不出现。 */
664
+ function emptyMessageOf(profile, payload) {
665
+ const base = profile.emptyMessage || DEFAULT_EMPTY_MESSAGE;
666
+ const detail = profile.emptyDetail;
667
+ if (!detail) return base;
668
+ const value = optionalText(getPath(payload, detail.path));
669
+ return value ? base + '(' + detail.label + '=' + value + ')' : base;
670
+ }
671
+
672
+ /** binary:JSON 形态优先(与迁移前 safeJson → decodeImagePayload 的顺序一致),否则认 body 本身。 */
673
+ function readBinaryOutput(payload, binary, profile, options) {
674
+ if (payload) return decodeImagePayload(payload, null);
675
+ if (binary && looksLikeImage(binary)) {
676
+ return { bytes: binary, contentType: imageContentTypeOf(options.contentType) || sniffType(binary) };
677
+ }
678
+ throw new Error(profile.emptyMessage || DEFAULT_EMPTY_MESSAGE);
679
+ }
680
+
681
+ /** 响应头里的 contentType:只认 image/*,参数(; charset=…)丢掉,其余交给签名兜底。 */
682
+ function imageContentTypeOf(value) {
683
+ const type = String(value || '').split(';')[0].trim().toLowerCase();
684
+ return /^image\/[a-z0-9.+-]+$/.test(type) ? type : '';
685
+ }
686
+
687
+ /**
688
+ * 路径取值。两种产生列表的段记号:
689
+ * - `a[].b`:数组每元素(gemini 的 parts[]、modelscope 的 output_images[]);
690
+ * - `a.*.b`:**每一个值**——对象取 values、数组取元素(ComfyUI 的 `outputs.<节点>`
691
+ * 就是它:节点号是运行时生成的)。
692
+ * 没有这两种记号时保留 getPath 的老语义(返回单值)。
693
+ */
694
+ function valuesOfPath(payload, path) {
695
+ const raw = optionalText(path);
696
+ if (!raw) return [];
697
+ if (!raw.includes('[]') && !raw.includes('*')) {
698
+ const value = getPath(payload, raw);
699
+ return value === undefined || value === null ? [] : [value];
700
+ }
701
+ let nodes = [payload];
702
+ for (const segment of raw.split('.')) {
703
+ const list = segment.endsWith('[]');
704
+ const wildcard = segment === '*';
705
+ const key = list ? segment.slice(0, -2) : segment;
706
+ const next = [];
707
+ for (const node of nodes) {
708
+ if (node === null || node === undefined) continue;
709
+ if (wildcard) {
710
+ for (const item of Object.values(node)) {
711
+ if (item !== undefined && item !== null) next.push(item);
712
+ }
713
+ continue;
714
+ }
715
+ const value = node[key];
716
+ if (value === undefined || value === null) continue;
717
+ if (list) {
718
+ if (Array.isArray(value)) for (const item of value) next.push(item);
719
+ } else {
720
+ next.push(value);
721
+ }
722
+ }
723
+ nodes = next;
724
+ }
725
+ return nodes;
726
+ }
727
+
728
+ /** 有序路径字段里「第一个有值的字符串」。今天认任务信封就是这条语义(非字符串一律不算)。 */
729
+ function firstStringOfPaths(node, paths) {
730
+ for (const path of paths) {
731
+ for (const value of valuesOfPath(node, path)) {
732
+ if (typeof value === 'string' && value.trim()) return value.trim();
733
+ }
734
+ }
735
+ return '';
736
+ }
737
+
738
+ /** 有序路径字段里「第一句非空的错误文本」(值可以是对象/数组,按 errorTextOf 深挖)。 */
739
+ function firstErrorTextOfPaths(node, paths) {
740
+ for (const path of paths) {
741
+ for (const value of valuesOfPath(node, path)) {
742
+ const text = errorTextOf(value);
743
+ if (text) return text;
744
+ }
745
+ }
746
+ return '';
747
+ }
748
+
749
+ /**
750
+ * `any`:同一个元素上的多种拼写,返回第一个「有值」的。
751
+ * `''` 表示元素本身(openai-chat 的 images[] 元素可以是字符串)。
752
+ * 与迁移前的 `a || b || string` 一致:空串按没有处理,且不因为解不出图而换下一种拼写。
753
+ */
754
+ function anyValueOf(value, any) {
755
+ if (!Array.isArray(any) || !any.length) return value;
756
+ for (const path of any) {
757
+ if (!path) return value;
758
+ const candidate = getPath(value, path);
759
+ if (candidate === undefined || candidate === null || candidate === '') continue;
760
+ return candidate;
761
+ }
762
+ return null;
763
+ }
764
+
765
+ /** 文本条目:一个值可能是字符串,也可能是 parts[](元素是字符串或 {text})。 */
766
+ function textsOf(value) {
767
+ if (typeof value === 'string') return [value];
768
+ if (!Array.isArray(value)) return [];
769
+ const out = [];
770
+ for (const part of value) {
771
+ if (typeof part === 'string') out.push(part);
772
+ else if (part && typeof part.text === 'string') out.push(part.text);
773
+ }
774
+ return out;
775
+ }
776
+
777
+ /**
778
+ * 一个 pick / from 条目 → 图。
779
+ *
780
+ * `text` 的循环顺序照抄 openai-chat 迁移前的实现:**先拿第一条正则扫全部文本,再第二条**。
781
+ * 反过来(逐段文本依次试所有正则)在同一条 content 里同时存在 http 链接与 data URL 时会选错。
782
+ *
783
+ * `where` 先过滤(只对 `[]` 元素有效,校验里挡住单值路径),`select:'last'` 再把候选列
784
+ * 反过来;反过来之后仍然是「逐个试、第一个解得出图的赢」——迁移前 gemini 的
785
+ * `parts.slice().reverse()` 循环就是这条语义(最后一个坏 base64 会退到前一个)。
786
+ */
787
+ function readPick(payload, pick, options) {
788
+ let values = valuesOfPath(payload, pick.path);
789
+ if (Array.isArray(pick.where) && pick.where.length) {
790
+ values = values.filter((value) => matchesWhere(value, pick.where));
791
+ }
792
+ if (pick.select === 'last') values = values.slice().reverse();
793
+ if (pick.text !== undefined) {
794
+ const texts = [];
795
+ for (const value of values) texts.push(...textsOf(value));
796
+ for (const rule of pick.text) {
797
+ const pattern = new RegExp(rule.regex, rule.flags === undefined ? 'i' : String(rule.flags));
798
+ for (const text of texts) {
799
+ const hit = pattern.exec(text);
800
+ if (!hit) continue;
801
+ const found = imageOfPick(hit[0], { as: rule.as === undefined ? 'auto' : rule.as });
802
+ if (found) return found;
803
+ }
804
+ }
805
+ return null;
806
+ }
807
+ for (const value of values) {
808
+ const found = imageOfPick(anyValueOf(value, pick.any), pick, options);
809
+ if (!found) continue;
810
+ return withContentType(found, value, payload, pick);
811
+ }
812
+ return null;
813
+ }
814
+
815
+ /** 一条 where 条件是否成立;`getPath` 取不到时是 null(不是 undefined),notEquals 因此放行。 */
816
+ function matchesWhere(value, conditions) {
817
+ for (const condition of conditions) {
818
+ const actual = getPath(value, condition.path);
819
+ if (condition.equals !== undefined) {
820
+ if (actual !== condition.equals) return false;
821
+ } else if (actual === condition.notEquals) {
822
+ return false;
823
+ }
824
+ }
825
+ return true;
826
+ }
827
+
828
+ /** `data.0.b64_json` → `data.0`;没有点号的路径返回空串(取不到父对象)。 */
829
+ function parentPathOf(path) {
830
+ const text = optionalText(path);
831
+ const at = text.lastIndexOf('.');
832
+ return at > 0 ? text.slice(0, at) : '';
833
+ }
834
+
835
+ /**
836
+ * contentType 覆盖:相对「命中元素」——值是对象(`[]` 产出的元素)就相对它本身,
837
+ * 否则相对 path 的父对象。多条候选按顺序取第一条非空。
838
+ */
839
+ function withContentType(image, value, payload, pick) {
840
+ if (!pick.contentTypePath || !image.bytes) return image;
841
+ const context = value && typeof value === 'object' ? value : getPath(payload, parentPathOf(pick.path));
842
+ if (!context) return image;
843
+ const candidates = Array.isArray(pick.contentTypePath) ? pick.contentTypePath : [pick.contentTypePath];
844
+ for (const path of candidates) {
845
+ const type = optionalText(getPath(context, path));
846
+ if (type) return { bytes: image.bytes, contentType: type };
847
+ }
848
+ return image;
849
+ }
850
+
851
+ /**
852
+ * 适配器的 task 描述符。新写法 `output:{kind:'task'}` 优先;
853
+ * 老写法 `poll` 原样返回(迁移期两套并存,执行器只认字段不认来源)。
854
+ */
855
+ export function taskSpecOf(adapter) {
856
+ const output = adapter && adapter.output;
857
+ if (output && output.kind === 'task') return output;
858
+ // 候选数组:取第一条 task 候选(轮询间隔、体积上限、恢复任务时都只关心这一条)。
859
+ if (Array.isArray(output)) return output.find((item) => item && item.kind === 'task') || null;
860
+ const legacy = adapter && adapter.poll;
861
+ return legacy && typeof legacy === 'object' ? legacy : null;
862
+ }
863
+
864
+ /**
865
+ * 任务成功载荷里的结果节点 → 图。节点缺失时用描述符的 emptyMessage,
866
+ * 节点存在但读不出图时保留 decodeImagePayload 的「格式不认识」。
867
+ *
868
+ * 铁律(§7.2.6-3):`emptyMessage` 只覆盖「没有结果节点」,**不覆盖** scan/decode
869
+ * 自己的文案——否则一份形状变了的上游响应会变成一句什么也看不出来的报错。
870
+ */
871
+ export function readTaskImage(node, spec) {
872
+ if (node === undefined || node === null) {
873
+ throw new Error((spec && spec.emptyMessage) || DEFAULT_EMPTY_MESSAGE);
874
+ }
875
+ return decodeImagePayload(node, null);
876
+ }
877
+
878
+ /* -------------------------------------------------------------- task 读取 */
879
+
880
+ /** resultPath 的候选列(有序);没写就沿用老 poll 形状的默认值 'output'。 */
881
+ function resultPathsOf(spec) {
882
+ const raw = (spec && spec.resultPath);
883
+ const list = Array.isArray(raw) ? raw : [raw];
884
+ const paths = list.map((item) => optionalText(item)).filter(Boolean);
885
+ return paths.length ? paths : ['output'];
886
+ }
887
+
888
+ /**
889
+ * 动态键那一层:声明了 `dynamicKey` 的描述符,`statusPath` / `resultPath` /
890
+ * `failureMessagePath` 都相对 `payload[taskId]` 算(ComfyUI 的 `payload[promptId]`)。
891
+ *
892
+ * 用**直接取属性**而不是拼进路径:prompt id 是运行时值,拼进点号路径会被它里面的点号拆错。
893
+ * 键还没出现时返回 null —— 对 `completeWhen:'key'` 来说这就是「还没完成」。
894
+ */
895
+ export function taskBasisOf(spec, payload, taskId) {
896
+ const profile = spec || {};
897
+ if (profile.dynamicKey === undefined) return payload;
898
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
899
+ const key = optionalText(taskId);
900
+ if (!key) return null;
901
+ const value = payload[key];
902
+ return value === undefined || value === null ? null : value;
903
+ }
904
+
905
+ /**
906
+ * 成功载荷里「结果图」所在的那个节点:按 resultPath 的顺序取第一个有值的。
907
+ * 空数组按「没有」处理(魔搭的 output_images: [] 要继续退到 data.0.url;
908
+ * Replicate 的 output: [] 则是「任务成功但没有图」,交给 emptyMessage)。
909
+ */
910
+ export function resultNodeOf(payload, spec, taskId) {
911
+ const basis = taskBasisOf(spec, payload, taskId);
912
+ if (basis === undefined || basis === null) return null;
913
+ for (const path of resultPathsOf(spec)) {
914
+ for (const value of valuesOfPath(basis, path)) {
915
+ if (Array.isArray(value) && !value.length) continue;
916
+ if (typeof value === 'string' && !value.trim()) continue;
917
+ return value;
918
+ }
919
+ }
920
+ return null;
921
+ }
922
+
923
+ /**
924
+ * 失败文案:有序路径,取第一个非空值;对象/数组按 errorTextOf 深挖(魔搭的 errors.message)。
925
+ *
926
+ * 只给「有没有人话原因」这一个答案,**不**回落到状态词:回落到状态词是上层格式的一部分
927
+ * (`生图任务失败(FAILED):…`),而 ComfyUI 那种「没 detail 就换一句固定提示」的
928
+ * 文案需要知道「真的没有」,所以导出这一层让调用方自己拼。
929
+ */
930
+ export function taskFailureMessageOf(spec, payload, taskId) {
931
+ const profile = spec || {};
932
+ const declared = Array.isArray(profile.failureMessagePath) && profile.failureMessagePath.length
933
+ ? profile.failureMessagePath
934
+ // 老 poll 形状没有这个字段,那时候的读法就是这两个路径。
935
+ : ['output.message', 'message'];
936
+ const basis = taskBasisOf(profile, payload, taskId);
937
+ if (basis === undefined || basis === null) return '';
938
+ return firstErrorTextOfPaths(basis, declared);
939
+ }
940
+
941
+ /** `errorPath` 的取值(有序):通用网关「没有状态词但有错误字段」也算失败。 */
942
+ function errorTextAt(profile, payload, taskId) {
943
+ const paths = pathsOf(profile.errorPath);
944
+ if (!paths.length) return '';
945
+ const basis = taskBasisOf(profile, payload, taskId);
946
+ if (basis === undefined || basis === null) return '';
947
+ return firstErrorTextOfPaths(basis, paths);
948
+ }
949
+
950
+ /**
951
+ * 轮询载荷 → 三态。状态词比较统一大写(Replicate 是小写状态,描述符照它自己的写法写即可)。
952
+ *
953
+ * 三种「完成信号」都从数据来,不在代码里认厂商:
954
+ * - `success` 里的状态词(今天的主流写法);
955
+ * - `errorPath` 有值 → 失败。fal 是「状态说 COMPLETED 但带 error」,
956
+ * 通用网关是「**没有**状态词但带 errors[]」——两种都由同一条规则覆盖;
957
+ * - `completeWhen:'key'`:没有状态词可等,**那一层动态键出现就算完成**(ComfyUI 的
958
+ * `/history/{id}` 就是它:任务好了才有 `payload[promptId]`,还没好就是 `{}`)。
959
+ */
960
+ export function taskStateOf(spec, payload, taskId) {
961
+ const profile = spec || {};
962
+ const basis = taskBasisOf(profile, payload, taskId);
963
+ const missingKey = profile.dynamicKey !== undefined && (basis === undefined || basis === null);
964
+ const status = missingKey ? '' : firstStringOfPaths(basis, pathsOf(profile.statusPath)).toUpperCase();
965
+ const upper = (list, fallback) => (Array.isArray(list) && list.length ? list : fallback)
966
+ .map((item) => String(item).toUpperCase());
967
+ const success = upper(profile.success, ['SUCCEEDED']);
968
+ const failure = upper(profile.failure, ['FAILED', 'CANCELED']);
969
+ if (profile.completeWhen === 'key') {
970
+ if (missingKey) return { state: 'pending', status: status };
971
+ // 键出现就已经完成了;状态词只用来把「完成了但失败」认出来。
972
+ if (failure.includes(status)) {
973
+ return { state: 'failure', status: status, message: taskFailureMessageOf(profile, payload, taskId) || status };
974
+ }
975
+ return { state: 'success', status: status, node: resultNodeOf(payload, profile, taskId) };
976
+ }
977
+ if (status && success.includes(status)) {
978
+ const message = errorTextAt(profile, payload, taskId);
979
+ if (message) return { state: 'failure', status: status, message: message };
980
+ return { state: 'success', status: status, node: resultNodeOf(payload, profile, taskId) };
981
+ }
982
+ if (status && failure.includes(status)) {
983
+ return { state: 'failure', status: status, message: taskFailureMessageOf(profile, payload, taskId) || status };
984
+ }
985
+ if (!status) {
986
+ const message = errorTextAt(profile, payload, taskId);
987
+ if (message) return { state: 'failure', status: '', message: message };
988
+ return { state: 'pending', status: '' };
989
+ }
990
+ return { state: 'pending', status: status };
991
+ }
992
+
993
+ /** 轮询间隔/退避:`backoff` 优先,否则用固定 `intervalMs`(缺省 2000,与迁移前执行器一致)。 */
994
+ export function backoffOf(spec) {
995
+ const profile = spec || {};
996
+ const backoff = profile.backoff && typeof profile.backoff === 'object' ? profile.backoff : null;
997
+ const start = backoff && Number(backoff.startMs) > 0
998
+ ? Number(backoff.startMs)
999
+ : (Number(profile.intervalMs) > 0 ? Number(profile.intervalMs) : 2000);
1000
+ const maxMs = backoff && Number(backoff.maxMs) > 0 ? Number(backoff.maxMs) : 5000;
1001
+ return { startMs: start, maxMs: maxMs, jitter: Boolean(backoff && backoff.jitter) };
1002
+ }
1003
+
1004
+ /**
1005
+ * 下一次等待时长:×1.15(`jitter` 时再乘 1.0~1.15 的随机抖动),`maxMs` 封顶。
1006
+ * 这就是迁移前两处硬编码的曲线(执行器的 `Math.round(interval * 1.15)` 与
1007
+ * ComfyUI 的 `1.15 + random * 0.15`),现在只剩这一份。
1008
+ */
1009
+ export function nextBackoff(current, spec) {
1010
+ const { maxMs, jitter } = backoffOf(spec);
1011
+ const factor = 1.15 + (jitter ? Math.random() * 0.15 : 0);
1012
+ return Math.min(maxMs, Math.round((Number(current) || 0) * factor));
1013
+ }
1014
+
1015
+ /**
1016
+ * 轮询地址候选列(有序)。三种来源排成今天的顺序:
1017
+ * 1. `pollUrlPath` 的第一个非空值(响应里给的地址最可信);
1018
+ * 2. `path` 的多条模板(`{root}` 站点根 / `{taskId}` 任务 id / `{submitUrl}` 提交地址);
1019
+ * 3. 都没有时是空列表,由执行器报「没有可用的轮询地址」。
1020
+ * 相对地址按 provider 站点根补全;重复的去掉。
1021
+ */
1022
+ export function taskPollTargets(spec, provider, submission, taskId, submitUrl) {
1023
+ const profile = spec || {};
1024
+ const base = baseUrlOf(provider);
1025
+ const targets = [];
1026
+ const push = (value, relativeTo) => {
1027
+ const resolved = resolveHttpUrl(value, relativeTo);
1028
+ if (resolved && !targets.includes(resolved)) targets.push(resolved);
1029
+ };
1030
+ const direct = firstStringOfPaths(submission, pathsOf(profile.pollUrlPath));
1031
+ if (direct) push(direct, submitUrl || base + '/');
1032
+ const rawId = taskIdOf(profile, submission) || optionalText(taskId);
1033
+ if (rawId) {
1034
+ const root = base.replace(/\/v\d+[a-z0-9]*$/i, '');
1035
+ const submitRoot = optionalText(submitUrl).replace(/\/+$/, '');
1036
+ for (const template of pathsOf(profile.path)) {
1037
+ if (template.includes('{submitUrl}') && !submitRoot) continue;
1038
+ const target = template
1039
+ .replace(/\{root\}/g, root)
1040
+ .replace(/\{submitUrl\}/g, submitRoot)
1041
+ .replace(/\{taskId\}/g, encodeURIComponent(rawId));
1042
+ // 模板里带 {root} / {submitUrl} 就已经是绝对地址;否则按「相对 provider 的路径」拼上去。
1043
+ push(joinEndpoint(base, target));
1044
+ }
1045
+ }
1046
+ return targets;
1047
+ }
1048
+
1049
+ /**
1050
+ * 轮询地址(单条,老接口)。`pollUrlPath` 优先(地址在响应里);否则按 `path` 的第一条模板拼。
1051
+ * 拼不出来返回空串,由执行器报「没有拿到轮询地址」。
1052
+ */
1053
+ export function taskPollTarget(spec, provider, submission, taskId, submitUrl) {
1054
+ const profile = spec || {};
1055
+ if (pathsOf(profile.pollUrlPath).length) {
1056
+ const direct = firstStringOfPaths(submission, pathsOf(profile.pollUrlPath));
1057
+ if (direct) return direct;
1058
+ if (!pathsOf(profile.path).length) return '';
1059
+ }
1060
+ const template = pathsOf(profile.path)[0];
1061
+ if (!template) return '';
1062
+ const rawId = pathsOf(profile.idPath).length ? firstStringOfPaths(submission, pathsOf(profile.idPath)) : optionalText(taskId);
1063
+ if (!rawId) return '';
1064
+ const base = baseUrlOf(provider);
1065
+ const target = template
1066
+ .replace(/\{root\}/g, base.replace(/\/v\d+[a-z0-9]*$/i, ''))
1067
+ .replace(/\{submitUrl\}/g, optionalText(submitUrl).replace(/\/+$/, ''))
1068
+ .replace(/\{taskId\}/g, encodeURIComponent(rawId));
1069
+ if (/^https?:\/\//i.test(target)) return target;
1070
+ return base + (target.startsWith('/') ? target : '/' + target);
1071
+ }
1072
+
1073
+ /** 提交响应里的任务 id(有序 idPath,第一个非空字符串)。 */
1074
+ export function taskIdOf(spec, submission) {
1075
+ for (const path of pathsOf(spec?.idPath)) {
1076
+ for (const value of valuesOfPath(submission, path)) {
1077
+ if (typeof value === 'string' && value.trim()) return value.trim();
1078
+ if (Number.isSafeInteger(value)) return String(value);
1079
+ }
1080
+ }
1081
+ return '';
1082
+ }
1083
+
1084
+ /**
1085
+ * 提交响应 → 任务计划。**认不出就返回 null**(交给下一个候选),认出来了就返回
1086
+ * `{spec, taskId, pollTargets}`;轮询由执行器做(描述符不碰请求)。
1087
+ *
1088
+ * 三种形态共用这一段:包络在响应里(id / 地址)、包络是 202+Location(`pollUrlFrom`)。
1089
+ * 「认出来」的判据与迁移前 `readTaskEnvelope` 一致:**拿到 id 或拿到地址**才算任务。
1090
+ */
1091
+ export function taskPlanOf(candidate, submission, options) {
1092
+ const opts = options || {};
1093
+ if (!candidate || candidate.kind !== 'task') return null;
1094
+ if (candidate.pollUrlFrom === 'location') {
1095
+ const location = resolveHttpUrl(opts.location, opts.submitUrl || baseUrlOf(opts.provider) + '/');
1096
+ if (!location) return null;
1097
+ return { spec: candidate, taskId: taskIdOf(candidate, submission), pollTargets: [location] };
1098
+ }
1099
+ const taskId = optionalText(opts.taskId) || taskIdOf(candidate, submission);
1100
+ const pollTargets = taskPollTargets(candidate, opts.provider, submission, taskId, opts.submitUrl);
1101
+ if (!taskId && !pollTargets.length) return null;
1102
+ return { spec: candidate, taskId: taskId, pollTargets: pollTargets };
1103
+ }
1104
+
1105
+ /**
1106
+ * 结果节点里的字段 → 第二跳地址(`thenUrl`)。
1107
+ *
1108
+ * 占位符从节点上取同名标量;缺值用 `defaults`(`subfolder:''` / `type:'output'` 就是迁移前
1109
+ * `||` 的默认值);既没值也没默认值 = 这条结果不能用,返回空串换下一条。
1110
+ * 查询串一律走 `URLSearchParams`(空格 → `+`、空值保留 `subfolder=`),与迁移前逐字节一致。
1111
+ */
1112
+ export function thenUrlOf(spec, node, baseUrl) {
1113
+ const then = (spec || {}).thenUrl;
1114
+ if (!then) return '';
1115
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return '';
1116
+ const template = String(then.template || '');
1117
+ const defaults = then.defaults && typeof then.defaults === 'object' ? then.defaults : {};
1118
+ const values = new Map();
1119
+ for (const match of template.matchAll(/\{([A-Za-z0-9_.]+)\}/g)) {
1120
+ const token = match[1];
1121
+ if (values.has(token)) continue;
1122
+ const own = Object.prototype.hasOwnProperty.call(defaults, token);
1123
+ const raw = node[token];
1124
+ const text = typeof raw === 'string' || typeof raw === 'number' ? String(raw).trim() : '';
1125
+ if (text) values.set(token, text);
1126
+ else if (own) values.set(token, defaults[token]);
1127
+ else return '';
1128
+ }
1129
+ const fill = (segment) => segment.replace(/\{([A-Za-z0-9_.]+)\}/g, (_all, token) => values.get(token));
1130
+ const at = template.indexOf('?');
1131
+ const pathPart = fill(at >= 0 ? template.slice(0, at) : template);
1132
+ const queryPart = at >= 0 ? template.slice(at + 1) : '';
1133
+ let query = '';
1134
+ if (queryPart) {
1135
+ const params = new URLSearchParams();
1136
+ for (const pair of queryPart.split('&')) {
1137
+ if (!pair) continue;
1138
+ const eq = pair.indexOf('=');
1139
+ const key = fill(eq >= 0 ? pair.slice(0, eq) : pair);
1140
+ params.append(key, fill(eq >= 0 ? pair.slice(eq + 1) : ''));
1141
+ }
1142
+ query = params.toString();
1143
+ }
1144
+ const path = query ? pathPart + '?' + query : pathPart;
1145
+ if (/^https?:\/\//i.test(path)) return path;
1146
+ const base = optionalText(baseUrl).replace(/\/+$/, '');
1147
+ if (!base) return '';
1148
+ return base + (path.startsWith('/') ? path : '/' + path);
1149
+ }
1150
+
1151
+ /**
1152
+ * 轮询载荷里**所有**可作为结果图的候选(有序):
1153
+ * - 有 `thenUrl`:结果值是「字段包」,要拼成第二跳地址(ComfyUI 的 `/view?…`);
1154
+ * 缺关键字段的那条跳过(迁移前是「跳过没有 filename 的节点」);
1155
+ * - 否则把每个结果值交给 decodeImagePayload(顺序 = resultPath 的顺序);
1156
+ * - `scan:true` 且 `options.done` 时再用整个基准对象扫一遍:迁移前 tier3 的 looseImageOf
1157
+ * 只在任务**已经成功**时跑(还在跑时扫,会把响应里的状态地址/预览图当结果)。
1158
+ * 只产出 `{url}` / `{bytes, contentType}`,**不下载**。
1159
+ */
1160
+ export function* taskResultCandidates(spec, payload, options) {
1161
+ const opts = options || {};
1162
+ const profile = spec || {};
1163
+ const basis = taskBasisOf(profile, payload, opts.taskId);
1164
+ if (basis === undefined || basis === null) return;
1165
+ const seen = new Set();
1166
+ const fresh = (image) => {
1167
+ if (!image) return false;
1168
+ const key = image.url || (image.bytes && image.bytes.length + ':' + image.bytes.slice(0, 16).toString('hex'));
1169
+ if (key && seen.has(key)) return false;
1170
+ if (key) seen.add(key);
1171
+ return true;
1172
+ };
1173
+ for (const path of resultPathsOf(profile)) {
1174
+ for (const value of valuesOfPath(basis, path)) {
1175
+ if (profile.thenUrl !== undefined) {
1176
+ const url = thenUrlOf(profile, value, opts.baseUrl);
1177
+ if (url && fresh({ url })) yield { url };
1178
+ continue;
1179
+ }
1180
+ try {
1181
+ const image = profile.resultAs
1182
+ ? imageOfPick(value, { as: profile.resultAs }, opts)
1183
+ : decodeImagePayload(value, null);
1184
+ if (fresh(image)) yield image;
1185
+ } catch (_error) {
1186
+ /* 这条读不出图,换下一条 */
1187
+ }
1188
+ }
1189
+ }
1190
+ if (!seen.size && profile.scan === true && opts.done === true) {
1191
+ try {
1192
+ yield decodeImagePayload(basis, null);
1193
+ } catch (_error) {
1194
+ /* 兜底扫描也落空 */
1195
+ }
1196
+ }
1197
+ }
1198
+
1199
+ export function taskResultImagesOf(spec, payload, options) {
1200
+ return [...taskResultCandidates(spec, payload, options)];
1201
+ }
1202
+
1203
+ /** 结果候选里的第一张(提交响应「已经带图」与轮询成功共用同一套读法)。 */
1204
+ export function taskResultImageOf(spec, payload, options) {
1205
+ return taskResultCandidates(spec, payload, options).next().value || null;
1206
+ }
1207
+
1208
+ /**
1209
+ * `via.urlPath` 的取值:条目前缀 `submission.` / `payload.` 指明从哪一侧取,
1210
+ * 没有前缀按轮询载荷算。只产出 URL 字符串,请求由执行器自己发(描述符不碰请求)。
1211
+ */
1212
+ export function viaUrlOf(via, submission, payload) {
1213
+ const paths = Array.isArray(via && via.urlPath) ? via.urlPath : [];
1214
+ for (const entry of paths) {
1215
+ const path = optionalText(entry);
1216
+ if (!path) continue;
1217
+ let value;
1218
+ if (path.startsWith('submission.')) value = getPath(submission, path.slice('submission.'.length));
1219
+ else if (path.startsWith('payload.')) value = getPath(payload, path.slice('payload.'.length));
1220
+ else value = getPath(payload, path);
1221
+ const text = optionalText(value);
1222
+ if (text) return text;
1223
+ }
1224
+ return '';
1225
+ }