dsh-mo-image 0.6.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +328 -55
- package/icon.png +0 -0
- package/lib/adapter-kit.js +289 -40
- package/lib/adapters/async.js +354 -140
- package/lib/adapters/cn.js +133 -68
- package/lib/adapters/openai.js +193 -143
- package/lib/adapters.js +3579 -695
- package/lib/client.js +6742 -828
- package/lib/comfy-workflow.js +100 -10
- package/lib/config-store.js +1628 -0
- package/lib/field-templates.js +385 -0
- package/lib/image-execution.js +58 -0
- package/lib/image-jobs.js +344 -0
- package/lib/image-queue.js +195 -0
- package/lib/image-request.js +830 -0
- package/lib/image-service.js +189 -0
- package/lib/image-worker.js +208 -0
- package/lib/index.js +1054 -967
- package/lib/localized-error.js +4 -0
- package/lib/model-rules.js +1034 -0
- package/lib/net.js +60 -25
- package/lib/output-profiles.js +1225 -0
- package/lib/png-scale.js +150 -68
- package/lib/prompt-profiles.js +196 -80
- package/lib/provider-operations.js +291 -0
- package/lib/proxy-dispatcher.js +11 -5
- package/lib/proxy.js +10 -8
- package/lib/request-auth.js +198 -0
- package/lib/retry.js +162 -0
- package/lib/settings-memory.js +117 -0
- package/lib/status.js +190 -0
- package/locale/messages.csv +206 -24
- package/package.json +3 -1
- package/scripts/release.mjs +79 -64
- package/skills/mo-image-editing/SKILL.md +36 -80
- package/skills/mo-image-generation/SKILL.md +62 -154
|
@@ -0,0 +1,830 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { classifyFailure, credentialText, decodeImagePayload, joinEndpoint, looksLikeImage, MAX_IMAGE_BYTES,
|
|
3
|
+
readJsonResponse, readResponseBytes, resolveHttpUrl, baseUrlOf, authSpecOf } from './adapter-kit.js';
|
|
4
|
+
import { fetchResultImage, requestProvider, requestResult } from './request-auth.js';
|
|
5
|
+
import {
|
|
6
|
+
DEFAULT_EMPTY_MESSAGE, backoffOf, nextBackoff, outputCandidatesOf, readOutput,
|
|
7
|
+
readTaskImage, resultNodeOf, taskPlanOf, taskResultCandidates, taskSpecOf, taskStateOf, viaUrlOf
|
|
8
|
+
} from './output-profiles.js';
|
|
9
|
+
import { isAbortError, isTimeoutError, parseRetryAfter, retryDelayMs, sleepWithSignal } from './retry.js';
|
|
10
|
+
|
|
11
|
+
let logHost = () => {};
|
|
12
|
+
/** apply() 注入宿主日志;传 null 关掉。 */
|
|
13
|
+
export function setImageExecutionLogger(fn) {
|
|
14
|
+
logHost = typeof fn === 'function' ? fn : () => {};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/* ------------------------------------ 提交/轮询的时间预算与错误契约(B2/B3/B4) */
|
|
18
|
+
|
|
19
|
+
// 工具超时是 360s;这里留 20s 给落盘、宿主渲染和网络抖动,避免边界上被宿主先杀掉。
|
|
20
|
+
export const TOTAL_BUDGET_MS = 340 * 1000;
|
|
21
|
+
const MAX_SUBMIT_ATTEMPTS = 5;
|
|
22
|
+
const MAX_RATE_LIMIT_RETRIES = 2;
|
|
23
|
+
// 只读阶段(查任务状态)连续瞬时错误的上限;读到一次有效状态就清零。
|
|
24
|
+
const MAX_POLL_ERRORS = 3;
|
|
25
|
+
const MAX_UPSTREAM_DETAIL_LENGTH = 512;
|
|
26
|
+
/**
|
|
27
|
+
* 这些字段就是请求本身:为了「让它过去」而摘掉它们,发出去的已经不是用户要的请求了。
|
|
28
|
+
* 尺寸类字段单独由 size 分类处理,也不允许被当作可选参数摘除。
|
|
29
|
+
*/
|
|
30
|
+
const PROTECTED_DROP_FIELDS = new Set([
|
|
31
|
+
'prompt', 'model', 'images', 'image', 'image_url', 'image_urls', 'input', 'input_image',
|
|
32
|
+
'init_image', 'mask', 'size', 'width', 'height'
|
|
33
|
+
]);
|
|
34
|
+
/** 连接都没建立起来的错误:请求肯定没到上游,重发是安全的。 */
|
|
35
|
+
const NETWORK_NOT_SENT_CODES = new Set([
|
|
36
|
+
'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH',
|
|
37
|
+
'UND_ERR_CONNECT_TIMEOUT', 'CERT_HAS_EXPIRED', 'DEPTH_ZERO_SELF_SIGNED_CERT'
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 把结构化字段挂到错误上(B2 契约):只加属性,不动 message,也不改工具返回结构。
|
|
42
|
+
* 上层据此判断阶段、是否已受理、能不能重试,而不是去正则匹配错误文案。
|
|
43
|
+
*/
|
|
44
|
+
export function attachFailure(error, fields) {
|
|
45
|
+
const target = error instanceof Error ? error : new Error(String(error));
|
|
46
|
+
const source = fields || {};
|
|
47
|
+
for (const key of ['code', 'phase', 'jobId', 'submissionState', 'retryAfterMs', 'status', 'resumable']) {
|
|
48
|
+
if (source[key] !== undefined) target[key] = source[key];
|
|
49
|
+
}
|
|
50
|
+
if (source.cause !== undefined && target.cause === undefined) target.cause = source.cause;
|
|
51
|
+
return target;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 分类结果 → 稳定的错误类别;rate 单独叫 rate_limit,免得和「参数错误」混在一起。 */
|
|
55
|
+
function failureCode(failure) {
|
|
56
|
+
const kind = String((failure && failure.kind) || 'unknown');
|
|
57
|
+
return kind === 'rate' ? 'rate_limit' : kind;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function cancelledFailure(phase, signal) {
|
|
61
|
+
const reason = signal && signal.reason;
|
|
62
|
+
if (reason instanceof Error) {
|
|
63
|
+
const error = new Error(reason.message, { cause: reason });
|
|
64
|
+
error.name = reason.name;
|
|
65
|
+
return attachFailure(error, { code: isTimeoutError(reason) ? 'timeout' : 'cancelled', phase });
|
|
66
|
+
}
|
|
67
|
+
const error = new Error('操作已取消');
|
|
68
|
+
error.name = 'AbortError';
|
|
69
|
+
return attachFailure(error, { code: 'cancelled', phase: phase });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 预算耗尽:单独的 TimeoutError,和用户取消(AbortError)区分开。 */
|
|
73
|
+
function timeoutFailure(phase, detail, fields) {
|
|
74
|
+
const error = new Error('生图超时:' + (detail || '本次调用已用完全部时间预算')
|
|
75
|
+
+ '。');
|
|
76
|
+
error.name = 'TimeoutError';
|
|
77
|
+
return attachFailure(error, Object.assign({ code: 'timeout', phase: phase }, fields || {}));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function ensureBudget(deadline, phase, signal) {
|
|
81
|
+
if (signal && signal.aborted) throw cancelledFailure(phase, signal);
|
|
82
|
+
if (Date.now() >= deadline) throw timeoutFailure(phase);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 本次请求可用的时间 = 总预算剩余时间与阶段超时的较小值;取消信号照样生效。 */
|
|
86
|
+
function budgetSignal(deadline, signal) {
|
|
87
|
+
const remaining = Math.max(1, deadline - Date.now());
|
|
88
|
+
const signals = [];
|
|
89
|
+
if (signal) signals.push(signal);
|
|
90
|
+
try {
|
|
91
|
+
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
|
|
92
|
+
signals.push(AbortSignal.timeout(remaining));
|
|
93
|
+
}
|
|
94
|
+
} catch (_error) { /* 余量非法时不加阶段定时器 */ }
|
|
95
|
+
if (!signals.length) return undefined;
|
|
96
|
+
if (signals.length === 1) return signals[0];
|
|
97
|
+
return typeof AbortSignal.any === 'function' ? AbortSignal.any(signals) : signals[0];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Keep only a digest between attempts, including multipart file content and order. */
|
|
101
|
+
async function requestFingerprint(method, url, body) {
|
|
102
|
+
const hash = createHash('sha256').update(method).update('\n').update(url);
|
|
103
|
+
if (typeof body === 'string') hash.update('\n').update(body);
|
|
104
|
+
else if (body && typeof body.entries === 'function') {
|
|
105
|
+
for (const [name, value] of body.entries()) {
|
|
106
|
+
if (typeof value === 'string') hash.update(JSON.stringify([name, value]));
|
|
107
|
+
else {
|
|
108
|
+
hash.update(JSON.stringify([name, value.name, value.type, value.size]));
|
|
109
|
+
hash.update(Buffer.from(await value.arrayBuffer()));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return hash.digest('hex');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function isProtectedDropField(field) {
|
|
117
|
+
const full = String(field || '').trim().toLowerCase();
|
|
118
|
+
if (!full) return true;
|
|
119
|
+
if (PROTECTED_DROP_FIELDS.has(full)) return true;
|
|
120
|
+
return PROTECTED_DROP_FIELDS.has(full.split('.').pop());
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 放弃响应体,把连接还给连接池(切候选地址、非 2xx 时都要做)。 */
|
|
124
|
+
async function cancelBody(response) {
|
|
125
|
+
try { await response.body?.cancel(); } catch (_error) { /* 已读完或没有 body */ }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function networkErrorCode(error) {
|
|
129
|
+
let current = error;
|
|
130
|
+
for (let depth = 0; current && depth < 5; depth++) {
|
|
131
|
+
if (current.code) return String(current.code);
|
|
132
|
+
current = current.cause;
|
|
133
|
+
}
|
|
134
|
+
return '';
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function networkNotSent(error) {
|
|
138
|
+
return NETWORK_NOT_SENT_CODES.has(networkErrorCode(error));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 只限制展示给用户和模型的详情,分类和重试仍使用完整响应。 */
|
|
142
|
+
function displayDetail(value, limit = MAX_UPSTREAM_DETAIL_LENGTH) {
|
|
143
|
+
const text = String(value || '');
|
|
144
|
+
if (text.length <= limit) return text;
|
|
145
|
+
return text.slice(0, limit - 1).replace(/[\uD800-\uDBFF]$/, '') + '…';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 受理状态未知的提交:文案必须让上层「先查再决定重发」,而不是直接重试。
|
|
150
|
+
*
|
|
151
|
+
* 扫到上游的任务标识就直接报出来:这时上游极可能已经建了任务,
|
|
152
|
+
* 让用户拿着 id 去供应商侧核实,比一句「状态未知」有用得多。
|
|
153
|
+
*/
|
|
154
|
+
function submissionUnknownText(detail, taskId) {
|
|
155
|
+
const head = '生图任务提交失败' + (detail ? '(' + displayDetail(detail) + ')' : '') + '。';
|
|
156
|
+
if (taskId) {
|
|
157
|
+
return head + '上游可能已创建任务 ' + taskId
|
|
158
|
+
+ ',请先在供应商侧核实任务或账单,确认未受理后再重新提交。';
|
|
159
|
+
}
|
|
160
|
+
return head + '这种情况无法确认上游是否已经受理,请不要直接重复提交(可能重复计费);先查询任务状态,确认没有任务后再重试。';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function submissionUnknownFailure(detail, cause, fields, taskId) {
|
|
164
|
+
return attachFailure(new Error(submissionUnknownText(detail, taskId)), Object.assign({
|
|
165
|
+
code: 'submission_unknown', phase: 'submit', submissionState: 'unknown', cause: cause
|
|
166
|
+
}, fields || {}));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 下载阶段的失败归类:超时/取消要保留自己的语义,其余归到 download。 */
|
|
170
|
+
function downloadFailureOf(error, signal, deadline, fields) {
|
|
171
|
+
if (signal && signal.aborted) return attachFailure(cancelledFailure('download', signal), fields);
|
|
172
|
+
if (isTimeoutError(error) || (isAbortError(error) && Date.now() >= deadline)) {
|
|
173
|
+
const timeout = timeoutFailure('download', '下载结果图超过本次调用的时间预算',
|
|
174
|
+
Object.assign({ cause: error }, fields || {}));
|
|
175
|
+
return timeout;
|
|
176
|
+
}
|
|
177
|
+
return attachFailure(error, Object.assign({
|
|
178
|
+
code: (error && error.code) || 'download_failed',
|
|
179
|
+
phase: (error && error.phase) || 'download'
|
|
180
|
+
}, fields || {}));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 日志只写脱敏后的结构化字段:不带 prompt、不带完整 URL、不带 Key。 */
|
|
184
|
+
function logFailure(kind, error, fallbackPhase) {
|
|
185
|
+
const fields = ['code=' + String((error && error.code) || 'unknown')];
|
|
186
|
+
fields.push('phase=' + String((error && error.phase) || fallbackPhase || 'unknown'));
|
|
187
|
+
if (error && error.jobId) fields.push('job=' + String(error.jobId).slice(0, 64));
|
|
188
|
+
if (error && error.submissionState) fields.push('submission=' + error.submissionState);
|
|
189
|
+
if (error && error.retryAfterMs !== undefined) fields.push('retryAfter=' + error.retryAfterMs);
|
|
190
|
+
logHost(kind + ' failure ' + fields.join(' '));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function safeJson(buffer) {
|
|
194
|
+
try { return JSON.parse(buffer.toString('utf8')); } catch (_error) { return null; }
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* 顺序稳定的 JSON:对象键排序后再序列化。
|
|
198
|
+
*
|
|
199
|
+
* 调用参数来自宿主,键顺序不保证稳定;如果直接 JSON.stringify,同一份请求
|
|
200
|
+
* 可能算出两个不同指纹,去重就失效了。
|
|
201
|
+
*/
|
|
202
|
+
export function stableStringify(value) {
|
|
203
|
+
if (value === null || value === undefined) return 'null';
|
|
204
|
+
if (typeof value !== 'object') return JSON.stringify(value);
|
|
205
|
+
if (Array.isArray(value)) return '[' + value.map((item) => stableStringify(item)).join(',') + ']';
|
|
206
|
+
const keys = Object.keys(value).sort();
|
|
207
|
+
return '{' + keys.map((key) => JSON.stringify(key) + ':' + stableStringify(value[key])).join(',') + '}';
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* 尺寸被上游拒了:不再偷偷抬档,直接把这次要的尺寸和该模型的合法范围说清楚。
|
|
211
|
+
*/
|
|
212
|
+
function sizeRejectedText(failure, fitted, hint) {
|
|
213
|
+
const wanted = fitted && !fitted.omit ? String(fitted.size || '') : '(自动)';
|
|
214
|
+
const detail = displayDetail(failure?.message, 200);
|
|
215
|
+
return '上游拒绝尺寸 ' + wanted + (detail ? ':' + detail : '')
|
|
216
|
+
+ (hint ? '。' + hint() : '') + '。换一个尺寸,或换一个支持它的模型。';
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function imageErrorText(failure) {
|
|
220
|
+
const text = '生图接口失败:' + displayDetail(failure.message);
|
|
221
|
+
const suffix = '(模型与提供商只能由用户在选择器里切换)';
|
|
222
|
+
if (failure.kind === 'size') return text + '(该模型对尺寸有最小/最大像素限制,换一个尺寸或换支持该尺寸的模型)' + suffix;
|
|
223
|
+
if (failure.kind === 'auth') return text + '(检查 API Key 与地址是否正确)' + suffix;
|
|
224
|
+
if (failure.kind === 'param') return text + '(请求参数与模型不兼容)' + suffix;
|
|
225
|
+
return text + suffix;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* 上游说「这个模型不支持这类操作」时,翻译成统一说法,
|
|
229
|
+
* 免得对话模型把「模型不支持」当成临时故障去换模型重试。
|
|
230
|
+
*/
|
|
231
|
+
function unsupportedModelMessage(kind, failure) {
|
|
232
|
+
const text = String((failure && failure.message) || '');
|
|
233
|
+
if (!/(model|模型)/i.test(text)) return '';
|
|
234
|
+
if (!/(not support|does not support|unsupported|不支持|cannot|无法)/i.test(text)) return '';
|
|
235
|
+
return '该模型不支持' + (kind === 'edit' ? '图生图' : '文生图') + ':' + displayDetail(text);
|
|
236
|
+
}
|
|
237
|
+
const ERROR_BODY_LIMIT = 128 * 1024;
|
|
238
|
+
// 5xx/408 的正文可能是「任务已经建好」的信封,值得多读一点;但只取任务标识,正文一律不进消息。
|
|
239
|
+
const AMBIGUOUS_BODY_LIMIT = 2 * 1024 * 1024;
|
|
240
|
+
const TASK_ID_KEYS = ['task_id', 'taskId', 'id', 'request_id'];
|
|
241
|
+
|
|
242
|
+
function submittedFields(job, resumable = false) {
|
|
243
|
+
return { submissionState: 'accepted', jobId: job?.id, resumable: Boolean(job?.id && resumable) };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function describeOutcome(error, fields) {
|
|
247
|
+
const failure = attachFailure(error, fields);
|
|
248
|
+
if (failure.resumable && failure.jobId) {
|
|
249
|
+
failure.message += '。可用 resume_job_id=' + failure.jobId + ' 继续同一个任务。';
|
|
250
|
+
} else if (failure.jobId && failure.submissionState === 'accepted' && failure.code !== 'task_failed') {
|
|
251
|
+
failure.message += '。上游已受理,请先检查原任务。';
|
|
252
|
+
} else if (failure.submissionState === 'unknown' && failure.code !== 'submission_unknown') {
|
|
253
|
+
failure.message += '。上游受理状态未知,请先查询原任务。';
|
|
254
|
+
}
|
|
255
|
+
return failure;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function sanitizeTaskUrl(url, provider, adapter) {
|
|
259
|
+
const spec = authSpecOf(provider, adapter);
|
|
260
|
+
if (spec.mode !== 'query') return url;
|
|
261
|
+
const target = new URL(url);
|
|
262
|
+
if (provider.key) target.searchParams.delete(spec.name, String(provider.key).trim());
|
|
263
|
+
return target.href;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function readErrorBody(response) {
|
|
267
|
+
try {
|
|
268
|
+
return (await readResponseBytes(response, ERROR_BODY_LIMIT)).toString('utf8');
|
|
269
|
+
} catch (_error) {
|
|
270
|
+
// HTTP status is still available if an error body is truncated, too large, or unreadable.
|
|
271
|
+
return '';
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 从一层对象里挑任务标识;键的顺序就是可信度顺序。 */
|
|
276
|
+
function taskIdOf(node) {
|
|
277
|
+
if (!node || typeof node !== 'object' || Array.isArray(node)) return '';
|
|
278
|
+
for (const key of TASK_ID_KEYS) {
|
|
279
|
+
const value = node[key];
|
|
280
|
+
if (typeof value === 'string' && value.trim()) return value.trim();
|
|
281
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
|
282
|
+
}
|
|
283
|
+
return '';
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* 5xx / 408 的提交响应:上游可能已经受理了,正文里常带着 task_id / id / request_id。
|
|
288
|
+
*
|
|
289
|
+
* 读一次正文,只取顶层或 data / output 下一层的任务标识,供错误消息酌情展示。
|
|
290
|
+
* 正文本身绝不进消息——可能很大,也可能带敏感信息;读不到就返回空串,保持原文案。
|
|
291
|
+
*/
|
|
292
|
+
async function ambiguousServerResponse(response) {
|
|
293
|
+
let buffer;
|
|
294
|
+
try {
|
|
295
|
+
buffer = await readResponseBytes(response, AMBIGUOUS_BODY_LIMIT);
|
|
296
|
+
} catch (_error) {
|
|
297
|
+
return '';
|
|
298
|
+
}
|
|
299
|
+
if (!buffer.length) return '';
|
|
300
|
+
const payload = safeJson(buffer);
|
|
301
|
+
if (!payload || typeof payload !== 'object') return '';
|
|
302
|
+
return taskIdOf(payload) || taskIdOf(payload.data) || taskIdOf(payload.output);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function protectedDrop(path, built, bindings) {
|
|
306
|
+
if (isProtectedDropField(path)) return true;
|
|
307
|
+
const fields = built.protectedFields || bindings?.() || {};
|
|
308
|
+
const paths = Array.isArray(fields) ? fields : ['prompt', 'model', 'image'].flatMap((role) => {
|
|
309
|
+
const field = fields[role];
|
|
310
|
+
return [field?.path, field?.multipart, field?.numbered].filter(Boolean);
|
|
311
|
+
});
|
|
312
|
+
const canonical = (key) => key.replace(/\[(\d*)\]/g, '.$1').replace(/\.$/, '');
|
|
313
|
+
const name = canonical(path);
|
|
314
|
+
return paths.map(canonical).some((key) => key === name || key.startsWith(name + '.')
|
|
315
|
+
|| name.startsWith(key + '.') || key.split('.').pop() === name);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function submissionInit(built, method, deadline, signal) {
|
|
319
|
+
return { method, body: built.body, headers: built.headers, signal: budgetSignal(deadline, signal) };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function submitImage(kind, adapter, provider, input, build, deadline, signal, job, hooks) {
|
|
323
|
+
const editFields = kind === 'edit' && adapter.editFields?.length ? adapter.editFields : ['image'];
|
|
324
|
+
const drops = new Set();
|
|
325
|
+
let fieldIndex = 0;
|
|
326
|
+
let fingerprint = '';
|
|
327
|
+
let lastFailure;
|
|
328
|
+
let rateRetries = 0;
|
|
329
|
+
let networkRetries = 0;
|
|
330
|
+
let built;
|
|
331
|
+
let rebuild = true;
|
|
332
|
+
const jobFields = { jobId: job?.id };
|
|
333
|
+
for (let attempt = 0; attempt < MAX_SUBMIT_ATTEMPTS; attempt++) {
|
|
334
|
+
try { ensureBudget(deadline, 'submit', signal); } catch (error) {
|
|
335
|
+
throw attachFailure(error, { ...jobFields, submissionState: 'rejected' });
|
|
336
|
+
}
|
|
337
|
+
if (rebuild) {
|
|
338
|
+
try {
|
|
339
|
+
built = await build(drops, editFields[fieldIndex], budgetSignal(deadline, signal));
|
|
340
|
+
} catch (error) {
|
|
341
|
+
if (signal?.aborted || isTimeoutError(error)) {
|
|
342
|
+
throw describeOutcome(signal?.aborted ? cancelledFailure('prepare', signal) : timeoutFailure('prepare'), {
|
|
343
|
+
...jobFields, submissionState: 'rejected', cause: error
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
throw attachFailure(error, { ...jobFields, phase: 'prepare', submissionState: 'rejected' });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const target = joinEndpoint(baseUrlOf(provider), built.path);
|
|
350
|
+
if (!built.path || !resolveHttpUrl(target)) {
|
|
351
|
+
throw attachFailure(new Error('提供商提交地址无效'), {
|
|
352
|
+
...jobFields, code: 'invalid_endpoint', phase: 'prepare', submissionState: 'rejected'
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
const method = built.method || 'POST';
|
|
356
|
+
ensureBudget(deadline, 'submit', signal);
|
|
357
|
+
if (rebuild && (editFields.length > 1 || built.allowFieldDrops !== false)) {
|
|
358
|
+
const next = await requestFingerprint(method, target, built.body);
|
|
359
|
+
if (next === fingerprint) {
|
|
360
|
+
throw attachFailure(new Error(imageErrorText(lastFailure) + '(参数调整未改变请求,已停止)'), {
|
|
361
|
+
...jobFields, code: 'duplicate_request', phase: 'submit', submissionState: 'rejected'
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
fingerprint = next;
|
|
365
|
+
}
|
|
366
|
+
rebuild = false;
|
|
367
|
+
|
|
368
|
+
let response;
|
|
369
|
+
try {
|
|
370
|
+
response = await requestProvider(target, submissionInit(built, method, deadline, signal), provider, adapter, false);
|
|
371
|
+
} catch (error) {
|
|
372
|
+
if (signal?.aborted || Date.now() >= deadline || (isTimeoutError(error) && !networkNotSent(error))) {
|
|
373
|
+
throw describeOutcome(signal?.aborted ? cancelledFailure('submit', signal) : timeoutFailure('submit'), {
|
|
374
|
+
...jobFields, submissionState: 'unknown', cause: error
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
if (networkNotSent(error)) {
|
|
378
|
+
if (networkRetries < MAX_RATE_LIMIT_RETRIES && attempt + 1 < MAX_SUBMIT_ATTEMPTS) {
|
|
379
|
+
await sleepWithSignal(retryDelayMs(++networkRetries), budgetSignal(deadline, signal));
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
throw attachFailure(error, { ...jobFields, code: 'network', phase: 'submit', submissionState: 'rejected' });
|
|
383
|
+
}
|
|
384
|
+
throw submissionUnknownFailure(networkErrorCode(error) || '网络中断', error, jobFields);
|
|
385
|
+
}
|
|
386
|
+
const output = built.output || adapter.responseOverrides?.[kind] || adapter.output;
|
|
387
|
+
if (response.ok || ([302, 303].includes(response.status) && response.headers.get('location')
|
|
388
|
+
&& outputCandidatesOf(output).some((profile) => profile.pollUrlFrom === 'location'))) {
|
|
389
|
+
return { response, built, submitUrl: resolveHttpUrl(response.url, target) || target };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// 5xx 与 408 都不等于「上游没执行」:请求可能已经被受理、任务已经建好。
|
|
393
|
+
// 这两种一律只发一次 POST,绝不重试;正文只读一遍,用来找任务标识。
|
|
394
|
+
if (response.status >= 500 || response.status === 408) {
|
|
395
|
+
const status = response.status;
|
|
396
|
+
const taskId = await ambiguousServerResponse(response);
|
|
397
|
+
// 任务标识必须原样展示才可用于查询;超长或需要脱敏时使用「先核实」的通用提示。
|
|
398
|
+
const visibleId = taskId.length <= MAX_UPSTREAM_DETAIL_LENGTH
|
|
399
|
+
&& credentialText(taskId, provider, adapter) === taskId ? taskId : '';
|
|
400
|
+
logFailure(kind, { ...jobFields, code: 'upstream', phase: 'submit', status, submissionState: 'unknown' }, 'submit');
|
|
401
|
+
throw submissionUnknownFailure('HTTP ' + status, undefined, { ...jobFields, status }, visibleId);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const failure = classifyFailure(response.status, credentialText(await readErrorBody(response), provider, adapter));
|
|
405
|
+
const retryAfterMs = parseRetryAfter(response.headers);
|
|
406
|
+
const fields = { ...jobFields, code: failureCode(failure), phase: 'submit', status: response.status, submissionState: 'rejected' };
|
|
407
|
+
lastFailure = failure;
|
|
408
|
+
logFailure(kind, fields, 'submit');
|
|
409
|
+
if (failure.kind === 'rate') {
|
|
410
|
+
const wait = retryDelayMs(rateRetries + 1, { retryAfterMs });
|
|
411
|
+
if (rateRetries >= MAX_RATE_LIMIT_RETRIES || Date.now() + wait >= deadline || attempt + 1 === MAX_SUBMIT_ATTEMPTS) {
|
|
412
|
+
throw attachFailure(new Error(imageErrorText(failure)), { ...fields, retryAfterMs });
|
|
413
|
+
}
|
|
414
|
+
rateRetries++;
|
|
415
|
+
await sleepWithSignal(wait, budgetSignal(deadline, signal));
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
// 兜底:分类器以后若把别的状态标成 retryable(或来了不可跟随的 3xx),
|
|
419
|
+
// 同样按「受理状态未知」处理,绝不因为「可重试」就再发一次 POST。
|
|
420
|
+
if (failure.retryable || (response.status >= 300 && response.status < 400)) {
|
|
421
|
+
throw submissionUnknownFailure('HTTP ' + response.status, new Error(displayDetail(failure.message)), {
|
|
422
|
+
...jobFields, status: response.status
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
const capability = unsupportedModelMessage(kind, failure);
|
|
426
|
+
if (capability) throw attachFailure(new Error(capability), { ...fields, code: 'unsupported_model' });
|
|
427
|
+
if (failure.kind === 'size') {
|
|
428
|
+
throw attachFailure(new Error(sizeRejectedText(failure, input.fitted, hooks.sizeHint)), fields);
|
|
429
|
+
}
|
|
430
|
+
const canAdjust = attempt + 1 < MAX_SUBMIT_ATTEMPTS && [400, 422].includes(response.status);
|
|
431
|
+
if (canAdjust && built.allowFieldDrops !== false && failure.drop && !drops.has(failure.drop)) {
|
|
432
|
+
if (protectedDrop(failure.drop, built, hooks.bindings)) {
|
|
433
|
+
throw attachFailure(new Error(imageErrorText(failure) + '(上游要求移除必要字段 ' + displayDetail(failure.drop) + ')'), fields);
|
|
434
|
+
}
|
|
435
|
+
drops.add(failure.drop);
|
|
436
|
+
rebuild = true;
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (canAdjust && /image/i.test(failure.message) && fieldIndex + 1 < editFields.length) {
|
|
440
|
+
fieldIndex++;
|
|
441
|
+
rebuild = true;
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
throw attachFailure(new Error(imageErrorText(failure)), fields);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async function createJob(journal, kind, adapter, provider, input, strict) {
|
|
449
|
+
if (!journal) return null;
|
|
450
|
+
try {
|
|
451
|
+
return await journal.create({
|
|
452
|
+
status: 'submitting', kind, providerId: provider.id, providerName: provider.name || '',
|
|
453
|
+
model: input.model, adapterId: adapter.id, strict
|
|
454
|
+
});
|
|
455
|
+
} catch (error) {
|
|
456
|
+
logHost('job journal create failed: ' + error.message);
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
async function updateJob(journal, job, patch) {
|
|
462
|
+
if (!journal || !job?.id) return false;
|
|
463
|
+
try {
|
|
464
|
+
return Boolean(await journal.update(job.id, patch));
|
|
465
|
+
} catch (error) {
|
|
466
|
+
logHost('job journal update failed: ' + error.message);
|
|
467
|
+
return false;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** Resolve and fetch each distinct image candidate at most once per completed response. */
|
|
472
|
+
async function downloadCandidate(image, base, tried, adapter, provider, signal) {
|
|
473
|
+
if (image.bytes) return image;
|
|
474
|
+
const url = resolveHttpUrl(image.url, base);
|
|
475
|
+
if (!url) throw new Error('上游返回了无效的图片地址');
|
|
476
|
+
if (tried.has(url)) throw tried.get(url);
|
|
477
|
+
try {
|
|
478
|
+
return await fetchResultImage(url, signal, adapter, provider);
|
|
479
|
+
} catch (error) {
|
|
480
|
+
tried.set(url, error);
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function pollError(adapter, status, failure) {
|
|
486
|
+
if (adapter.id === 'comfyui') return new Error('ComfyUI 查询任务失败:HTTP ' + status);
|
|
487
|
+
return new Error(imageErrorText(failure));
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function taskError(adapter, state, provider) {
|
|
491
|
+
const message = displayDetail(credentialText(state.message, provider, adapter));
|
|
492
|
+
if (adapter.id === 'comfyui') {
|
|
493
|
+
return new Error('ComfyUI 执行失败' + (state.message && state.message !== state.status
|
|
494
|
+
? ':' + message : ',请检查 ComfyUI 控制台'));
|
|
495
|
+
}
|
|
496
|
+
const status = displayDetail(credentialText(state.status, provider, adapter));
|
|
497
|
+
return new Error('生图任务失败' + (status ? '(' + status + ')' : '') + (message ? ':' + message : ''));
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
async function readPollBody(response, maxBytes) {
|
|
501
|
+
const buffer = await readResponseBytes(response, maxBytes);
|
|
502
|
+
if (!buffer.length) return null;
|
|
503
|
+
const json = safeJson(buffer);
|
|
504
|
+
if (json === null) throw attachFailure(new Error('生图任务查询返回的不是 JSON(HTTP ' + response.status + ')'), {
|
|
505
|
+
code: 'protocol_mismatch', phase: 'poll'
|
|
506
|
+
});
|
|
507
|
+
return json;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async function readTaskResult(spec, payload, submission, taskId, state, target, adapter, provider, tried, signal, submitUrl = target) {
|
|
511
|
+
let source = payload;
|
|
512
|
+
if (spec.via) {
|
|
513
|
+
if (state.state !== 'success') return null;
|
|
514
|
+
const url = resolveHttpUrl(viaUrlOf(spec.via, submission, null), submitUrl)
|
|
515
|
+
|| resolveHttpUrl(viaUrlOf(spec.via, {}, payload), target);
|
|
516
|
+
if (!url) throw new Error(spec.emptyMessage || DEFAULT_EMPTY_MESSAGE);
|
|
517
|
+
const response = await requestResult(url, signal, adapter, provider, 'result');
|
|
518
|
+
source = await readJsonResponse(response, spec.via.maxBytes, provider, adapter);
|
|
519
|
+
const actual = resolveHttpUrl(response.url, url) || url;
|
|
520
|
+
const candidate = taskResultCandidates(spec, source, {
|
|
521
|
+
taskId, baseUrl: baseUrlOf(provider), responseUrl: adapter.id === 'custom' ? actual : undefined, done: true
|
|
522
|
+
}).next().value;
|
|
523
|
+
if (candidate) return downloadCandidate(candidate, actual, tried, adapter, provider, signal);
|
|
524
|
+
const node = resultNodeOf(source, spec, taskId);
|
|
525
|
+
if (spec.resultAs) throw new Error(spec.emptyMessage || DEFAULT_EMPTY_MESSAGE);
|
|
526
|
+
return downloadCandidate(readTaskImage(node, spec), actual, tried, adapter, provider, signal);
|
|
527
|
+
}
|
|
528
|
+
let lastError;
|
|
529
|
+
for (const image of taskResultCandidates(spec, source, {
|
|
530
|
+
taskId, baseUrl: baseUrlOf(provider), responseUrl: adapter.id === 'custom' ? target : undefined,
|
|
531
|
+
done: state.state === 'success'
|
|
532
|
+
})) {
|
|
533
|
+
try {
|
|
534
|
+
return await downloadCandidate(image, target, tried, adapter, provider, signal);
|
|
535
|
+
} catch (error) {
|
|
536
|
+
if (signal?.aborted || isAbortError(error) || isTimeoutError(error)) throw error;
|
|
537
|
+
lastError = error;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
if (state.state === 'success' && lastError) throw lastError;
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** The same read-only driver is used by gateways, native task providers and local workflows. */
|
|
545
|
+
async function pollImage(adapter, provider, task, deadline, signal) {
|
|
546
|
+
const { spec, submission, taskId, submitUrl, pollTargets, tried, onTarget } = task;
|
|
547
|
+
const backoff = backoffOf(spec);
|
|
548
|
+
const limit = Math.min(deadline, Date.now() + (Number(spec.timeoutMs) || TOTAL_BUDGET_MS));
|
|
549
|
+
const pollSignal = budgetSignal(limit, signal);
|
|
550
|
+
let delay = backoff.startMs;
|
|
551
|
+
let index = 0;
|
|
552
|
+
let failures = 0;
|
|
553
|
+
while (true) {
|
|
554
|
+
ensureBudget(limit, 'poll', signal);
|
|
555
|
+
await sleepWithSignal(Math.min(delay, Math.max(1, limit - Date.now())), pollSignal);
|
|
556
|
+
ensureBudget(limit, 'poll', signal);
|
|
557
|
+
const target = pollTargets[index];
|
|
558
|
+
let response;
|
|
559
|
+
let payload;
|
|
560
|
+
try {
|
|
561
|
+
response = await requestResult(target, pollSignal, adapter, provider, 'poll');
|
|
562
|
+
if (response.ok && !(response.status === 202 && (adapter.id === 'fal' || spec.pollOutput === 'binary'))) {
|
|
563
|
+
if (spec.pollOutput === 'binary') {
|
|
564
|
+
const bytes = await readResponseBytes(response, spec.maxBytes || MAX_IMAGE_BYTES);
|
|
565
|
+
if (looksLikeImage(bytes)) return readOutput(null, { kind: 'binary' }, {
|
|
566
|
+
binary: bytes, contentType: response.headers.get('content-type')
|
|
567
|
+
});
|
|
568
|
+
if (bytes.length) throw attachFailure(new Error('轮询结果不是有效的二进制图片'), { code: 'protocol_mismatch', phase: 'poll' });
|
|
569
|
+
} else {
|
|
570
|
+
payload = await readPollBody(response, spec.maxBytes || MAX_IMAGE_BYTES);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
} catch (error) {
|
|
574
|
+
if (pollSignal?.aborted || error.code === 'protocol_mismatch') throw error;
|
|
575
|
+
if (error.localized?.code === 'upstream.tooLarge') {
|
|
576
|
+
throw attachFailure(error, { code: 'payload', phase: 'poll' });
|
|
577
|
+
}
|
|
578
|
+
if (++failures > MAX_POLL_ERRORS) throw attachFailure(error, { code: 'network', phase: 'poll' });
|
|
579
|
+
delay = nextBackoff(delay, spec);
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
if ([404, 405].includes(response.status) && index + 1 < pollTargets.length) {
|
|
583
|
+
await cancelBody(response);
|
|
584
|
+
index++;
|
|
585
|
+
if (onTarget) await onTarget(pollTargets.slice(index));
|
|
586
|
+
delay = backoff.startMs;
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
if (response.status === 404 && adapter.pollNotFoundPending) {
|
|
590
|
+
await cancelBody(response);
|
|
591
|
+
delay = nextBackoff(delay, spec);
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
if (!response.ok) {
|
|
595
|
+
const failure = classifyFailure(response.status, credentialText(await readErrorBody(response), provider, adapter));
|
|
596
|
+
const retryAfterMs = parseRetryAfter(response.headers);
|
|
597
|
+
if (failure.retryable && ++failures <= MAX_POLL_ERRORS && !adapter.pollErrorsAreTerminal) {
|
|
598
|
+
delay = Math.max(nextBackoff(delay, spec), retryAfterMs);
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
throw attachFailure(pollError(adapter, response.status, failure), {
|
|
602
|
+
code: failureCode(failure), phase: 'poll', status: response.status, retryAfterMs
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
failures = 0;
|
|
606
|
+
delay = Math.max(nextBackoff(delay, spec), parseRetryAfter(response.headers));
|
|
607
|
+
if (!payload) {
|
|
608
|
+
await cancelBody(response);
|
|
609
|
+
continue;
|
|
610
|
+
}
|
|
611
|
+
const state = typeof adapter.async?.statusOf === 'function' && !spec.statusPath
|
|
612
|
+
? adapter.async.statusOf(payload)
|
|
613
|
+
: taskStateOf(spec, payload, taskId);
|
|
614
|
+
if (state.state === 'failure') throw attachFailure(taskError(adapter, state, provider), { code: 'task_failed', phase: 'poll' });
|
|
615
|
+
if (state.state !== 'success' && !(adapter.autoAsync && !adapter.waitForTaskSuccess)) continue;
|
|
616
|
+
try {
|
|
617
|
+
if (!spec.statusPath && typeof adapter.async?.resolve === 'function') {
|
|
618
|
+
const image = await adapter.async.resolve(payload, provider, pollSignal, submission);
|
|
619
|
+
if (image) return await downloadCandidate(image, target, tried, adapter, provider, pollSignal);
|
|
620
|
+
}
|
|
621
|
+
const image = await readTaskResult(spec, payload, submission, taskId, state,
|
|
622
|
+
resolveHttpUrl(response.url, target) || target, adapter, provider, tried, pollSignal, submitUrl);
|
|
623
|
+
if (image) return image;
|
|
624
|
+
} catch (error) {
|
|
625
|
+
throw downloadFailureOf(error, signal, limit);
|
|
626
|
+
}
|
|
627
|
+
if (state.state === 'success') {
|
|
628
|
+
throw attachFailure(new Error(spec.emptyMessage || DEFAULT_EMPTY_MESSAGE), { code: 'image_invalid', phase: 'download' });
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
export async function followTask(kind, adapter, provider, submission, submitUrl, plan, fitted, model, signal, deadlineAt, hooks = {}) {
|
|
634
|
+
const spec = plan.spec;
|
|
635
|
+
const taskId = plan.taskId || '';
|
|
636
|
+
const pollTargets = [...new Set((plan.pollTargets || []).map((url) => resolveHttpUrl(url, submitUrl)).filter(Boolean))];
|
|
637
|
+
const deadline = Number.isFinite(deadlineAt) ? deadlineAt : Date.now() + TOTAL_BUDGET_MS;
|
|
638
|
+
const job = hooks.job || hooks.resume;
|
|
639
|
+
if (!pollTargets.length) {
|
|
640
|
+
throw describeOutcome(new Error('生图接口返回了任务,但没有可用的轮询地址'), {
|
|
641
|
+
...submittedFields(job), code: 'protocol_mismatch', phase: 'poll'
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
// Only values required to recover a task are persisted. A submission can include full image bytes.
|
|
645
|
+
const viaUrl = spec.via ? resolveHttpUrl(viaUrlOf(spec.via, submission, null), submitUrl) : '';
|
|
646
|
+
const retained = viaUrl ? { response_url: sanitizeTaskUrl(viaUrl, provider, adapter) } : {};
|
|
647
|
+
const resumeSpec = spec.via && retained.response_url
|
|
648
|
+
? { ...spec, via: { ...spec.via, urlPath: ['submission.response_url', ...spec.via.urlPath.filter((path) => !path.startsWith('submission.'))] } }
|
|
649
|
+
: spec;
|
|
650
|
+
const pollRecord = (targets) => ({
|
|
651
|
+
pollTarget: sanitizeTaskUrl(targets[0], provider, adapter),
|
|
652
|
+
pollTargets: targets.map((url) => sanitizeTaskUrl(url, provider, adapter))
|
|
653
|
+
});
|
|
654
|
+
const record = {
|
|
655
|
+
status: 'submitted', taskId, ...pollRecord(pollTargets),
|
|
656
|
+
submitUrl: sanitizeTaskUrl(submitUrl, provider, adapter), taskSpec: resumeSpec,
|
|
657
|
+
submission: retained, fitted, note: hooks.note || '',
|
|
658
|
+
providerOrigin: new URL(submitUrl).origin,
|
|
659
|
+
baseOrigin: resolveHttpUrl(baseUrlOf(provider)) ? new URL(baseUrlOf(provider)).origin : '',
|
|
660
|
+
pollNotFoundPending: Boolean(adapter.pollNotFoundPending),
|
|
661
|
+
waitForTaskSuccess: Boolean(adapter.waitForTaskSuccess),
|
|
662
|
+
pollOrigins: adapter.pollOrigins || [],
|
|
663
|
+
resultAuthOrigins: adapter.resultAuthOrigins || [],
|
|
664
|
+
pollHeaders: adapter.pollHeaders || {}
|
|
665
|
+
};
|
|
666
|
+
const resumable = Boolean(hooks.resume) || await updateJob(hooks.journal, job, record);
|
|
667
|
+
const fields = submittedFields(job, resumable);
|
|
668
|
+
try {
|
|
669
|
+
const image = await pollImage(adapter, provider, {
|
|
670
|
+
spec, submission, taskId, submitUrl, pollTargets, tried: hooks.tried || new Map(),
|
|
671
|
+
onTarget: resumable && hooks.journal ? (targets) => updateJob(hooks.journal, job, pollRecord(targets)) : null
|
|
672
|
+
}, deadline, signal);
|
|
673
|
+
return { ...image, fitted, jobId: job?.id, resumable, note: hooks.note || undefined };
|
|
674
|
+
} catch (cause) {
|
|
675
|
+
const failure = cause.code === 'task_failed';
|
|
676
|
+
const error = signal?.aborted ? cancelledFailure(cause.phase || 'poll', signal)
|
|
677
|
+
: isTimeoutError(cause) || isAbortError(cause) ? timeoutFailure(cause.phase || 'poll') : cause;
|
|
678
|
+
if (failure && hooks.resume) await updateJob(hooks.journal, job, { status: 'failed', failure: error.message });
|
|
679
|
+
throw describeOutcome(error, {
|
|
680
|
+
...fields, resumable: fields.resumable && !failure,
|
|
681
|
+
phase: error.phase || 'poll', code: error.code || 'network', cause: error === cause ? undefined : cause
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function responseLimit(output, asyncOnly) {
|
|
687
|
+
if (asyncOnly) return 2 * 1024 * 1024;
|
|
688
|
+
const candidates = outputCandidatesOf(output);
|
|
689
|
+
return candidates.length ? Math.max(...candidates.map((item) => item.maxBytes || MAX_IMAGE_BYTES)) : MAX_IMAGE_BYTES;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
async function materializeSubmission(kind, adapter, provider, input, submitted, deadline, signal, hooks) {
|
|
693
|
+
const { response, built, submitUrl } = submitted;
|
|
694
|
+
if (built.operation) {
|
|
695
|
+
adapter = {
|
|
696
|
+
...adapter, operationOrigin: new URL(submitUrl).origin,
|
|
697
|
+
pollOrigins: built.operation.pollOrigins, resultAuthOrigins: built.operation.resultOrigins,
|
|
698
|
+
pollHeaders: built.operation.pollHeaders,
|
|
699
|
+
pollNotFoundPending: built.operation.pollNotFoundPending === true,
|
|
700
|
+
waitForTaskSuccess: built.operation.output === adapter.output ? false : true
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
const override = adapter.responseOverrides?.[kind];
|
|
704
|
+
if (override) adapter = { ...adapter, waitForTaskSuccess: true };
|
|
705
|
+
const legacy = adapter.async && !built.output && !override && !adapter.output && !adapter.poll ? adapter.async : null;
|
|
706
|
+
const output = built.output || override || adapter.output || taskSpecOf(adapter) || (legacy ? {
|
|
707
|
+
kind: 'task', intervalMs: legacy.intervalMs, timeoutMs: legacy.timeoutMs, idPath: ['id', 'task_id']
|
|
708
|
+
} : null);
|
|
709
|
+
const fields = submittedFields(hooks.job);
|
|
710
|
+
let buffer;
|
|
711
|
+
const hopSignal = budgetSignal(deadline, signal);
|
|
712
|
+
try {
|
|
713
|
+
buffer = await readResponseBytes(response, responseLimit(output, !override && Boolean(adapter.async || adapter.taskSubmission)));
|
|
714
|
+
} catch (error) {
|
|
715
|
+
throw describeOutcome(downloadFailureOf(error, signal, deadline), fields);
|
|
716
|
+
}
|
|
717
|
+
const contentType = response.headers.get('content-type');
|
|
718
|
+
const payload = buffer.length && !looksLikeImage(buffer) ? safeJson(buffer) : null;
|
|
719
|
+
const tried = new Map();
|
|
720
|
+
let lastError;
|
|
721
|
+
let downloadError;
|
|
722
|
+
const candidates = outputCandidatesOf(output);
|
|
723
|
+
for (const candidate of candidates) {
|
|
724
|
+
if (candidate.kind === 'task' || candidate === taskSpecOf(adapter)) {
|
|
725
|
+
const profile = candidate.kind ? candidate : { ...candidate, kind: 'task' };
|
|
726
|
+
const plan = taskPlanOf(profile, payload, {
|
|
727
|
+
provider, submitUrl, location: response.headers.get('location')
|
|
728
|
+
});
|
|
729
|
+
const task = plan?.pollTargets.length ? plan : (legacy && typeof legacy.pollUrl === 'function' && payload ? {
|
|
730
|
+
spec: profile, taskId: plan?.taskId || '', pollTargets: [legacy.pollUrl(payload, provider)]
|
|
731
|
+
} : plan);
|
|
732
|
+
if (!task) continue;
|
|
733
|
+
if (!task.taskId && adapter.async) task.taskId = String(payload?.id || payload?.task_id || '');
|
|
734
|
+
const state = taskStateOf(profile, payload, task.taskId);
|
|
735
|
+
if (state.state === 'failure') {
|
|
736
|
+
throw describeOutcome(taskError(adapter, state, provider), { ...fields, code: 'task_failed', phase: 'poll' });
|
|
737
|
+
}
|
|
738
|
+
if (!candidate.via && (state.state === 'success' || (adapter.autoAsync && !adapter.waitForTaskSuccess))) {
|
|
739
|
+
try {
|
|
740
|
+
const image = await readTaskResult(candidate, payload, null, task.taskId, state,
|
|
741
|
+
submitUrl, adapter, provider, tried, hopSignal);
|
|
742
|
+
if (image) return { ...image, fitted: input.fitted, note: built.note };
|
|
743
|
+
} catch (error) {
|
|
744
|
+
if (hopSignal?.aborted) throw describeOutcome(downloadFailureOf(error, signal, deadline), fields);
|
|
745
|
+
downloadError = error;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
if (task.pollTargets.length) {
|
|
749
|
+
return followTask(kind, adapter, provider, payload, submitUrl, task, input.fitted, input.model,
|
|
750
|
+
signal, deadline, { ...hooks, note: built.note, tried });
|
|
751
|
+
}
|
|
752
|
+
lastError = new Error('上游返回了任务 ID,但缺少轮询地址');
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
let candidateImage;
|
|
756
|
+
try {
|
|
757
|
+
candidateImage = readOutput(payload, candidate, {
|
|
758
|
+
binary: buffer, contentType, baseUrl: baseUrlOf(provider),
|
|
759
|
+
responseUrl: adapter.id === 'custom' ? submitUrl : undefined
|
|
760
|
+
});
|
|
761
|
+
} catch (error) {
|
|
762
|
+
lastError = error;
|
|
763
|
+
continue;
|
|
764
|
+
}
|
|
765
|
+
try {
|
|
766
|
+
const image = await downloadCandidate(candidateImage, submitUrl, tried, adapter, provider, hopSignal);
|
|
767
|
+
return { ...image, fitted: input.fitted, note: built.note };
|
|
768
|
+
} catch (error) {
|
|
769
|
+
if (hopSignal?.aborted || isTimeoutError(error) || isAbortError(error)) {
|
|
770
|
+
throw describeOutcome(downloadFailureOf(error, signal, deadline), fields);
|
|
771
|
+
}
|
|
772
|
+
downloadError = error;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
if (downloadError) throw describeOutcome(downloadFailureOf(downloadError, signal, deadline), fields);
|
|
776
|
+
if (!adapter.autoAsync && !adapter.async && !adapter.taskSubmission && !payload?.data && (payload?.task_id || payload?.task_status)) {
|
|
777
|
+
lastError = new Error('该接口返回异步任务。请选择可自动识别的协议,或在自定义返回格式中设置任务轮询。');
|
|
778
|
+
}
|
|
779
|
+
if (!candidates.length) {
|
|
780
|
+
let image;
|
|
781
|
+
try {
|
|
782
|
+
image = decodeImagePayload(payload, buffer);
|
|
783
|
+
} catch (error) {
|
|
784
|
+
lastError = error;
|
|
785
|
+
}
|
|
786
|
+
if (image) {
|
|
787
|
+
try {
|
|
788
|
+
const result = await downloadCandidate(image, submitUrl, tried, adapter, provider, hopSignal);
|
|
789
|
+
return { ...result, fitted: input.fitted, note: built.note };
|
|
790
|
+
} catch (error) {
|
|
791
|
+
throw describeOutcome(downloadFailureOf(error, signal, deadline), fields);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
if (!lastError && candidates.some((profile) => profile.kind === 'task')) {
|
|
796
|
+
lastError = new Error(adapter.id === 'comfyui' ? 'ComfyUI 没有返回 prompt_id' : '上游任务响应缺少可识别的任务 ID 或轮询地址');
|
|
797
|
+
}
|
|
798
|
+
const error = lastError || new Error(DEFAULT_EMPTY_MESSAGE);
|
|
799
|
+
error.message = displayDetail(credentialText(error.message, provider, adapter));
|
|
800
|
+
throw describeOutcome(error, {
|
|
801
|
+
...fields, code: 'protocol_mismatch', phase: 'download'
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** Adapter builds may prepare uploads or session data. The submission policy is shared here. */
|
|
806
|
+
export async function executeImageRequest(kind, adapter, provider, input, build, signal, hooks = {}) {
|
|
807
|
+
const deadline = Date.now() + TOTAL_BUDGET_MS;
|
|
808
|
+
const operationOutput = adapter.operations?.[kind]?.output || adapter.responseOverrides?.[kind];
|
|
809
|
+
const mayQueue = adapter.async || adapter.taskSubmission
|
|
810
|
+
|| (operationOutput ? outputCandidatesOf(operationOutput).some((profile) => profile.kind === 'task') : adapter.autoAsync);
|
|
811
|
+
const job = mayQueue ? await createJob(hooks.journal, kind, adapter, provider, input, hooks.strict) : null;
|
|
812
|
+
let outcome;
|
|
813
|
+
try {
|
|
814
|
+
const submitted = await submitImage(kind, adapter, provider, input, build, deadline, signal, job, hooks);
|
|
815
|
+
outcome = await materializeSubmission(kind, adapter, provider, input, submitted, deadline, signal, { ...hooks, job });
|
|
816
|
+
} catch (error) {
|
|
817
|
+
if (provider?.key) error.message = credentialText(error.message, provider, adapter);
|
|
818
|
+
if (job && !error.resumable && ['rejected', 'accepted'].includes(error.submissionState)) {
|
|
819
|
+
await updateJob(hooks.journal, job, {
|
|
820
|
+
status: error.submissionState === 'rejected' ? 'rejected' : 'failed', failure: error.message
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
throw error;
|
|
824
|
+
}
|
|
825
|
+
if (job && !outcome.jobId) {
|
|
826
|
+
await updateJob(hooks.journal, job, { status: 'received' });
|
|
827
|
+
return { ...outcome, jobId: job.id };
|
|
828
|
+
}
|
|
829
|
+
return outcome;
|
|
830
|
+
}
|