dsh-mo-image 0.6.0 → 0.7.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 +11 -0
- package/README.md +57 -17
- package/icon.png +0 -0
- package/lib/adapter-kit.js +363 -11
- package/lib/adapters/async.js +258 -31
- package/lib/adapters/cn.js +13 -0
- package/lib/adapters/openai.js +21 -2
- package/lib/adapters.js +880 -139
- package/lib/client.js +459 -131
- package/lib/comfy-workflow.js +7 -3
- package/lib/config-store.js +692 -0
- package/lib/image-execution.js +835 -0
- package/lib/image-jobs.js +333 -0
- package/lib/image-queue.js +195 -0
- package/lib/image-service.js +226 -0
- package/lib/image-worker.js +195 -0
- package/lib/index.js +439 -858
- package/lib/png-scale.js +103 -28
- package/lib/prompt-profiles.js +139 -68
- package/lib/request-auth.js +143 -0
- package/lib/retry.js +162 -0
- package/lib/settings-memory.js +33 -0
- package/lib/status.js +187 -0
- package/locale/messages.csv +226 -214
- package/package.json +3 -1
- package/skills/mo-image-editing/SKILL.md +34 -72
- package/skills/mo-image-generation/SKILL.md +59 -152
|
@@ -0,0 +1,835 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 生图执行器:请求构造、提交边界、轮询、下载与错误契约。
|
|
3
|
+
*
|
|
4
|
+
* 从 lib/index.js 拆出来以后,执行器只依赖适配器层、net、retry 和 request-auth;
|
|
5
|
+
* 不读配置、不碰工具注册。index.js 负责把 logger 注入进来,测试可以直接调用
|
|
6
|
+
* callImageApi,不必先 apply 整个插件。
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
prepareGenerate, prepareEdit, prepareAsync, preparePhaseAsync, pollUrlFor,
|
|
10
|
+
readTaskId, readTaskState, decodeImagePayload, classifyFailure,
|
|
11
|
+
fetchImageUrl, adapterBase, readResponseBytes, MAX_IMAGE_BYTES,
|
|
12
|
+
adapterSupportsKind, readTaskEnvelope, taskPollUrls, taskStatusOf, taskImageOf, looseImageOf,
|
|
13
|
+
sizeHintText
|
|
14
|
+
} from './adapters.js';
|
|
15
|
+
import { request } from './net.js';
|
|
16
|
+
import { fetchResultImage, pollRequestHeaders } from './request-auth.js';
|
|
17
|
+
import { isAbortError, isTimeoutError, parseRetryAfter, retryDelayMs, sleepWithSignal } from './retry.js';
|
|
18
|
+
|
|
19
|
+
let logHost = () => {};
|
|
20
|
+
/** apply() 注入宿主日志;传 null 关掉。 */
|
|
21
|
+
export function setImageExecutionLogger(fn) {
|
|
22
|
+
logHost = typeof fn === 'function' ? fn : () => {};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/* ------------------------------------ 提交/轮询的时间预算与错误契约(B2/B3/B4) */
|
|
26
|
+
|
|
27
|
+
// 工具超时是 360s;这里留 20s 给落盘、宿主渲染和网络抖动,避免边界上被宿主先杀掉。
|
|
28
|
+
export const TOTAL_BUDGET_MS = 340 * 1000;
|
|
29
|
+
const MAX_SUBMIT_ATTEMPTS = 5;
|
|
30
|
+
const MAX_RATE_LIMIT_RETRIES = 2;
|
|
31
|
+
// 只读阶段(查任务状态)连续瞬时错误的上限;读到一次有效状态就清零。
|
|
32
|
+
const MAX_POLL_ERRORS = 3;
|
|
33
|
+
/**
|
|
34
|
+
* 这些字段就是请求本身:为了「让它过去」而摘掉它们,发出去的已经不是用户要的请求了。
|
|
35
|
+
* 尺寸类字段单独由 size 分类处理,也不允许被当作可选参数摘除。
|
|
36
|
+
*/
|
|
37
|
+
const PROTECTED_DROP_FIELDS = new Set([
|
|
38
|
+
'prompt', 'model', 'images', 'image', 'image_url', 'image_urls', 'input', 'input_image',
|
|
39
|
+
'init_image', 'mask', 'size', 'width', 'height'
|
|
40
|
+
]);
|
|
41
|
+
/** 连接都没建立起来的错误:请求肯定没到上游,重发是安全的。 */
|
|
42
|
+
const NETWORK_NOT_SENT_CODES = new Set([
|
|
43
|
+
'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH',
|
|
44
|
+
'UND_ERR_CONNECT_TIMEOUT', 'CERT_HAS_EXPIRED', 'DEPTH_ZERO_SELF_SIGNED_CERT'
|
|
45
|
+
]);
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 把结构化字段挂到错误上(B2 契约):只加属性,不动 message,也不改工具返回结构。
|
|
49
|
+
* 上层据此判断阶段、是否已受理、能不能重试,而不是去正则匹配错误文案。
|
|
50
|
+
*/
|
|
51
|
+
export function attachFailure(error, fields) {
|
|
52
|
+
const target = error instanceof Error ? error : new Error(String(error));
|
|
53
|
+
const source = fields || {};
|
|
54
|
+
for (const key of ['code', 'phase', 'jobId', 'submissionState', 'retryAfterMs', 'status']) {
|
|
55
|
+
if (source[key] !== undefined) target[key] = source[key];
|
|
56
|
+
}
|
|
57
|
+
if (source.cause !== undefined && target.cause === undefined) target.cause = source.cause;
|
|
58
|
+
return target;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 分类结果 → 稳定的错误类别;rate 单独叫 rate_limit,免得和「参数错误」混在一起。 */
|
|
62
|
+
function failureCode(failure) {
|
|
63
|
+
const kind = String((failure && failure.kind) || 'unknown');
|
|
64
|
+
return kind === 'rate' ? 'rate_limit' : kind;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function cancelledFailure(phase, signal) {
|
|
68
|
+
const reason = signal && signal.reason;
|
|
69
|
+
if (reason instanceof Error) return attachFailure(reason, { code: 'cancelled', phase: phase });
|
|
70
|
+
const error = new Error('操作已取消');
|
|
71
|
+
error.name = 'AbortError';
|
|
72
|
+
return attachFailure(error, { code: 'cancelled', phase: phase });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 预算耗尽:单独的 TimeoutError,和用户取消(AbortError)区分开。 */
|
|
76
|
+
function timeoutFailure(phase, detail, fields) {
|
|
77
|
+
const error = new Error('生图超时:' + (detail || '本次调用已用完全部时间预算')
|
|
78
|
+
+ '。可以稍后用同样的提示词重试;若已拿到任务信息,先查询任务状态更稳妥。');
|
|
79
|
+
error.name = 'TimeoutError';
|
|
80
|
+
return attachFailure(error, Object.assign({ code: 'timeout', phase: phase }, fields || {}));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function ensureBudget(deadline, phase, signal) {
|
|
84
|
+
if (signal && signal.aborted) throw cancelledFailure(phase, signal);
|
|
85
|
+
if (Date.now() >= deadline) throw timeoutFailure(phase);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 本次请求可用的时间 = 总预算剩余时间与阶段超时的较小值;取消信号照样生效。 */
|
|
89
|
+
function budgetSignal(deadline, signal) {
|
|
90
|
+
const remaining = Math.max(1, deadline - Date.now());
|
|
91
|
+
const signals = [];
|
|
92
|
+
if (signal) signals.push(signal);
|
|
93
|
+
try {
|
|
94
|
+
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
|
|
95
|
+
signals.push(AbortSignal.timeout(remaining));
|
|
96
|
+
}
|
|
97
|
+
} catch (_error) { /* 余量非法时不加阶段定时器 */ }
|
|
98
|
+
if (!signals.length) return undefined;
|
|
99
|
+
if (signals.length === 1) return signals[0];
|
|
100
|
+
return typeof AbortSignal.any === 'function' ? AbortSignal.any(signals) : signals[0];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 语义指纹:方法 + URL + body。multipart 的 boundary 只在序列化时生成,天然不进指纹。 */
|
|
104
|
+
function requestFingerprint(method, url, body) {
|
|
105
|
+
let payload = '';
|
|
106
|
+
if (typeof body === 'string') {
|
|
107
|
+
payload = body;
|
|
108
|
+
} else if (body && typeof body.entries === 'function') {
|
|
109
|
+
const parts = [];
|
|
110
|
+
for (const [key, value] of body.entries()) {
|
|
111
|
+
const file = value && typeof value === 'object' && 'size' in value;
|
|
112
|
+
parts.push(key + '=' + (file ? '[file ' + (value.type || '') + '/' + value.size + ']' : String(value)));
|
|
113
|
+
}
|
|
114
|
+
payload = parts.join('&');
|
|
115
|
+
} else if (body && typeof body === 'object') {
|
|
116
|
+
try { payload = JSON.stringify(body); } catch (_error) { payload = ''; }
|
|
117
|
+
}
|
|
118
|
+
return String(method || 'GET').toUpperCase() + ' ' + String(url) + '\n' + payload;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isProtectedDropField(field) {
|
|
122
|
+
const full = String(field || '').trim().toLowerCase();
|
|
123
|
+
if (!full) return true;
|
|
124
|
+
if (PROTECTED_DROP_FIELDS.has(full)) return true;
|
|
125
|
+
return PROTECTED_DROP_FIELDS.has(full.split('.').pop());
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 放弃响应体,把连接还给连接池(切候选地址、非 2xx 时都要做)。 */
|
|
129
|
+
async function cancelBody(response) {
|
|
130
|
+
try { await response.body?.cancel(); } catch (_error) { /* 已读完或没有 body */ }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function networkErrorCode(error) {
|
|
134
|
+
let current = error;
|
|
135
|
+
for (let depth = 0; current && depth < 5; depth++) {
|
|
136
|
+
if (current.code) return String(current.code);
|
|
137
|
+
current = current.cause;
|
|
138
|
+
}
|
|
139
|
+
return '';
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function networkNotSent(error) {
|
|
143
|
+
return NETWORK_NOT_SENT_CODES.has(networkErrorCode(error));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 受理状态未知的提交:文案必须让上层「先查再决定重发」,而不是直接重试。 */
|
|
147
|
+
function submissionUnknownText(detail) {
|
|
148
|
+
return '生图任务提交失败' + (detail ? '(' + detail + ')' : '')
|
|
149
|
+
+ '。这种情况无法确认上游是否已经受理,请不要直接重复提交(可能重复计费);先查询任务状态,确认没有任务后再重试。';
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function submissionUnknownFailure(detail, cause, fields) {
|
|
153
|
+
return attachFailure(new Error(submissionUnknownText(detail)), Object.assign({
|
|
154
|
+
code: 'submission_unknown', phase: 'submit', submissionState: 'unknown', cause: cause
|
|
155
|
+
}, fields || {}));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 下载阶段的失败归类:超时/取消要保留自己的语义,其余归到 download。 */
|
|
159
|
+
function downloadFailureOf(error, signal, deadline, fields) {
|
|
160
|
+
if (signal && signal.aborted) return attachFailure(cancelledFailure('download', signal), fields);
|
|
161
|
+
if (isTimeoutError(error) || (isAbortError(error) && Date.now() >= deadline)) {
|
|
162
|
+
const timeout = timeoutFailure('download', '下载结果图超过本次调用的时间预算',
|
|
163
|
+
Object.assign({ cause: error }, fields || {}));
|
|
164
|
+
return timeout;
|
|
165
|
+
}
|
|
166
|
+
return attachFailure(error, Object.assign({
|
|
167
|
+
code: (error && error.code) || 'download_failed',
|
|
168
|
+
phase: (error && error.phase) || 'download'
|
|
169
|
+
}, fields || {}));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 日志只写脱敏后的结构化字段:不带 prompt、不带完整 URL、不带 Key。 */
|
|
173
|
+
function logFailure(kind, error, fallbackPhase) {
|
|
174
|
+
const fields = ['code=' + String((error && error.code) || 'unknown')];
|
|
175
|
+
fields.push('phase=' + String((error && error.phase) || fallbackPhase || 'unknown'));
|
|
176
|
+
if (error && error.jobId) fields.push('job=' + String(error.jobId).slice(0, 64));
|
|
177
|
+
if (error && error.submissionState) fields.push('submission=' + error.submissionState);
|
|
178
|
+
if (error && error.retryAfterMs !== undefined) fields.push('retryAfter=' + error.retryAfterMs);
|
|
179
|
+
logHost(kind + ' failure ' + fields.join(' '));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function safeJson(buffer) {
|
|
183
|
+
try { return JSON.parse(buffer.toString('utf8')); } catch (_error) { return null; }
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* 顺序稳定的 JSON:对象键排序后再序列化。
|
|
187
|
+
*
|
|
188
|
+
* 调用参数来自宿主,键顺序不保证稳定;如果直接 JSON.stringify,同一份请求
|
|
189
|
+
* 可能算出两个不同指纹,去重就失效了。
|
|
190
|
+
*/
|
|
191
|
+
export function stableStringify(value) {
|
|
192
|
+
if (value === null || value === undefined) return 'null';
|
|
193
|
+
if (typeof value !== 'object') return JSON.stringify(value);
|
|
194
|
+
if (Array.isArray(value)) return '[' + value.map((item) => stableStringify(item)).join(',') + ']';
|
|
195
|
+
const keys = Object.keys(value).sort();
|
|
196
|
+
return '{' + keys.map((key) => JSON.stringify(key) + ':' + stableStringify(value[key])).join(',') + '}';
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* 尺寸被上游拒了:不再偷偷抬档,直接把这次要的尺寸和该模型的合法范围说清楚。
|
|
200
|
+
*/
|
|
201
|
+
function sizeRejectedText(kind, adapter, input, failure, fitted) {
|
|
202
|
+
const wanted = fitted && !fitted.omit ? String(fitted.size || '') : '(自动)';
|
|
203
|
+
const detail = String((failure && failure.message) || '').slice(0, 200);
|
|
204
|
+
const model = String((input && input.model) || '');
|
|
205
|
+
return '上游拒绝尺寸 ' + wanted + (detail ? ':' + detail : '')
|
|
206
|
+
+ '。' + sizeHintText(adapter, model) + '。换一个尺寸,或换一个支持它的模型。';
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function imageErrorText(failure) {
|
|
210
|
+
const text = '生图接口失败:' + failure.message;
|
|
211
|
+
const suffix = '(模型与提供商只能由用户在选择器里切换)';
|
|
212
|
+
if (failure.kind === 'size') return text + '(该模型对尺寸有最小/最大像素限制,换一个尺寸或换支持该尺寸的模型)' + suffix;
|
|
213
|
+
if (failure.kind === 'auth') return text + '(检查 API Key 与地址是否正确)' + suffix;
|
|
214
|
+
if (failure.kind === 'param') return text + '(请求参数与模型不兼容)' + suffix;
|
|
215
|
+
return text + suffix;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* 上游说「这个模型不支持这类操作」时,翻译成统一说法,
|
|
219
|
+
* 免得对话模型把「模型不支持」当成临时故障去换模型重试。
|
|
220
|
+
*/
|
|
221
|
+
function unsupportedModelMessage(kind, failure) {
|
|
222
|
+
const text = String((failure && failure.message) || '');
|
|
223
|
+
if (!/(model|模型)/i.test(text)) return '';
|
|
224
|
+
if (!/(not support|does not support|unsupported|不支持|cannot|无法)/i.test(text)) return '';
|
|
225
|
+
return '该模型不支持' + (kind === 'edit' ? '图生图' : '文生图') + ':' + text;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* 真正发请求的地方:按适配器组装 → 发 → 解码。
|
|
229
|
+
* 上游报错时只在三类情况下自愈:字段不认识(摘掉重试)、尺寸被拒(往上抬一档)、限流/5xx(退避重试)。
|
|
230
|
+
*/
|
|
231
|
+
/**
|
|
232
|
+
* 异步入队型:提交任务 → 轮询到 SUCCEEDED → 下载图片。
|
|
233
|
+
*
|
|
234
|
+
* 提交、轮询、下载共用一份总预算,任何一段都不会把整次工具调用拖过宿主超时;
|
|
235
|
+
* 提交失败时先判断「上游是否可能已受理」,受理状态不明就不重发。
|
|
236
|
+
*/
|
|
237
|
+
export async function callAsyncImage(kind, adapter, provider, input, signal, hooks) {
|
|
238
|
+
const phase = adapter.async && typeof adapter.async === 'object' ? adapter.async : null;
|
|
239
|
+
if (kind === 'edit' && !(phase && phase.edit)) {
|
|
240
|
+
throw new Error('该模型(' + adapter.label + ')暂不支持参考图编辑,请到设置里换一个编辑模型。');
|
|
241
|
+
}
|
|
242
|
+
const deadline = Date.now() + TOTAL_BUDGET_MS;
|
|
243
|
+
const journal = hooks && hooks.journal && typeof hooks.journal.create === 'function' ? hooks.journal : null;
|
|
244
|
+
// 恢复模式:不再提交,直接从已落盘的 submission/taskId/pollTarget 继续轮询。
|
|
245
|
+
const resume = hooks && hooks.resume && typeof hooks.resume === 'object' ? hooks.resume : null;
|
|
246
|
+
const drops = new Set();
|
|
247
|
+
let fitted = (resume && resume.fitted) || input.fitted;
|
|
248
|
+
let submission = resume ? resume.submission : null;
|
|
249
|
+
let lastFailure = null;
|
|
250
|
+
let lastNote = resume && resume.note ? String(resume.note) : '';
|
|
251
|
+
let lastPrint = '';
|
|
252
|
+
let job = resume ? { id: String(resume.jobId || '') } : null;
|
|
253
|
+
// 429 是上游明确说「没有入队」,此时才允许原样重发(而且有次数上限)。
|
|
254
|
+
let allowRepeat = false;
|
|
255
|
+
let rateRetries = 0;
|
|
256
|
+
let pollErrors = 0;
|
|
257
|
+
|
|
258
|
+
// 提交前先落一条记录:进程在提交途中崩掉时,至少能看到「有一次提交状态未知」。
|
|
259
|
+
if (journal && !resume) {
|
|
260
|
+
try {
|
|
261
|
+
job = await journal.create({
|
|
262
|
+
status: 'submitting', kind: kind, providerId: provider.id, providerName: provider.name || '',
|
|
263
|
+
model: input.model, adapterId: adapter.id
|
|
264
|
+
});
|
|
265
|
+
} catch (error) {
|
|
266
|
+
logHost('job journal create failed: ' + String(error && error.message ? error.message : error));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (!resume) {
|
|
271
|
+
for (let attempt = 1; attempt <= MAX_SUBMIT_ATTEMPTS; attempt++) {
|
|
272
|
+
ensureBudget(deadline, 'submit', signal);
|
|
273
|
+
const attemptInput = Object.assign({}, input, { fitted: fitted });
|
|
274
|
+
// 第 5 个参数是「可摘除字段」:适配器还没支持时会被忽略,
|
|
275
|
+
// 这时重发同一份请求会被下面的指纹检查拦下,不会白建第二个任务。
|
|
276
|
+
const built = phase
|
|
277
|
+
? await preparePhaseAsync(adapter, provider, attemptInput, signal, drops)
|
|
278
|
+
: prepareAsync(adapter, provider, attemptInput, drops);
|
|
279
|
+
if (built.note) lastNote = built.note;
|
|
280
|
+
const submitUrl = /^https?:\/\//i.test(built.path) ? built.path : adapterBase(provider) + built.path;
|
|
281
|
+
const fingerprint = requestFingerprint('POST', submitUrl, built.body);
|
|
282
|
+
if (fingerprint === lastPrint && !allowRepeat) {
|
|
283
|
+
// 与上一次完全相同的请求:重发不会得到不同结果,还可能在上游建出第二个任务。
|
|
284
|
+
logHost(kind + ' async submit stop: identical request after [' + failureCode(lastFailure) + ']');
|
|
285
|
+
throw attachFailure(new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '任务提交失败' })
|
|
286
|
+
+ '(重试会原样重发同一个请求,已停止)'), {
|
|
287
|
+
code: 'duplicate_request', phase: 'submit',
|
|
288
|
+
submissionState: lastFailure ? 'rejected' : 'unknown'
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
allowRepeat = false;
|
|
292
|
+
lastPrint = fingerprint;
|
|
293
|
+
|
|
294
|
+
let response;
|
|
295
|
+
try {
|
|
296
|
+
response = await request(submitUrl, {
|
|
297
|
+
method: 'POST', headers: built.headers, body: built.body, signal: budgetSignal(deadline, signal)
|
|
298
|
+
});
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (signal && signal.aborted) {
|
|
301
|
+
// 用户取消:请求可能已经上路,受理状态按未知记,但取消本身要原样抛出。
|
|
302
|
+
throw attachFailure(cancelledFailure('submit', signal), { submissionState: 'unknown', cause: error });
|
|
303
|
+
}
|
|
304
|
+
if (isTimeoutError(error) || Date.now() >= deadline) {
|
|
305
|
+
throw timeoutFailure('submit', '提交请求超过本次调用的时间预算', { submissionState: 'unknown', cause: error });
|
|
306
|
+
}
|
|
307
|
+
logFailure(kind, { code: 'network', phase: 'submit' }, 'submit');
|
|
308
|
+
// 提交阶段断连/超时时无法确认上游是否已受理:不盲目重发,把判断交给上层。
|
|
309
|
+
throw submissionUnknownFailure(networkErrorCode(error) || '网络中断', error);
|
|
310
|
+
}
|
|
311
|
+
const buffer = await readResponseBytes(response, 2 * 1024 * 1024);
|
|
312
|
+
if (response.ok) {
|
|
313
|
+
submission = safeJson(buffer);
|
|
314
|
+
break;
|
|
315
|
+
}
|
|
316
|
+
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
317
|
+
lastFailure = failure;
|
|
318
|
+
logHost(kind + ' async submit ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
|
|
319
|
+
const capability = unsupportedModelMessage(kind, failure);
|
|
320
|
+
if (capability) {
|
|
321
|
+
throw attachFailure(new Error(capability), {
|
|
322
|
+
code: 'unsupported_model', phase: 'submit', submissionState: 'rejected', status: response.status
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// 429:上游明确没有入队,按 Retry-After 等待,最多两次,且受总预算约束。
|
|
327
|
+
if (failure.kind === 'rate') {
|
|
328
|
+
const retryAfterMs = parseRetryAfter(response.headers);
|
|
329
|
+
if (rateRetries >= MAX_RATE_LIMIT_RETRIES) {
|
|
330
|
+
throw attachFailure(new Error(imageErrorText(failure)), {
|
|
331
|
+
code: 'rate_limit', phase: 'submit', submissionState: 'rejected',
|
|
332
|
+
retryAfterMs: retryAfterMs, status: response.status
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
rateRetries++;
|
|
336
|
+
const waitMs = Math.min(retryDelayMs(rateRetries, { retryAfterMs: retryAfterMs }),
|
|
337
|
+
Math.max(0, deadline - Date.now()));
|
|
338
|
+
logHost(kind + ' async submit rate limited, retry #' + rateRetries + ' in ' + waitMs + 'ms');
|
|
339
|
+
await sleepWithSignal(waitMs, signal);
|
|
340
|
+
allowRepeat = true;
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (failure.kind === 'param' && failure.drop) {
|
|
345
|
+
if (isProtectedDropField(failure.drop)) {
|
|
346
|
+
// 必要字段被上游点名:不能摘掉它去「凑」一次成功,保留原来的错误类别。
|
|
347
|
+
logHost(kind + ' async submit refused to drop a protected field');
|
|
348
|
+
throw attachFailure(new Error(imageErrorText(failure)
|
|
349
|
+
+ '(上游要求移除必要字段 ' + failure.drop + ';这属于请求与模型不兼容,不能自动摘除)'), {
|
|
350
|
+
code: 'param', phase: 'submit', submissionState: 'rejected', status: response.status
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
if (!drops.has(failure.drop)) {
|
|
354
|
+
drops.add(failure.drop);
|
|
355
|
+
logHost(kind + ' async drop param "' + failure.drop + '"');
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
// 已经摘过一次还是同一个错误:不发第三次同样的请求。
|
|
359
|
+
throw attachFailure(new Error(imageErrorText(failure)), {
|
|
360
|
+
code: 'param', phase: 'submit', submissionState: 'rejected', status: response.status
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
if (failure.kind === 'size') {
|
|
364
|
+
throw attachFailure(new Error(sizeRejectedText(kind, adapter, input, failure, fitted)), {
|
|
365
|
+
code: 'size', phase: 'submit', submissionState: 'rejected', status: response.status
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
if (failure.retryable) {
|
|
369
|
+
// 5xx 等:网关报错不代表上游没建任务(「已入队但网关 503」很常见),一律按未确认处理。
|
|
370
|
+
logFailure(kind, { code: 'submission_unknown', phase: 'submit', status: response.status }, 'submit');
|
|
371
|
+
throw submissionUnknownFailure('HTTP ' + response.status, Object.assign(
|
|
372
|
+
new Error(failure.message || ('HTTP ' + response.status)), { status: response.status }
|
|
373
|
+
), { status: response.status });
|
|
374
|
+
}
|
|
375
|
+
// 其余 4xx(参数、鉴权、尺寸、限流以外的拒绝)是明确未受理,按现有分类直接报错。
|
|
376
|
+
throw attachFailure(new Error(imageErrorText(failure)), {
|
|
377
|
+
code: failureCode(failure), phase: 'submit', submissionState: 'rejected', status: response.status
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
if (!submission) {
|
|
381
|
+
throw attachFailure(new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '任务提交失败' })), {
|
|
382
|
+
code: failureCode(lastFailure), phase: 'submit',
|
|
383
|
+
submissionState: lastFailure ? 'rejected' : 'unknown'
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// 各家的任务 id 字段不一样:BFL/Replicate 是 id,魔搭是 task_id。
|
|
389
|
+
const taskId = resume
|
|
390
|
+
? String(resume.taskId || '')
|
|
391
|
+
: (phase
|
|
392
|
+
? String((submission && (submission.id || submission.task_id)) || '')
|
|
393
|
+
: readTaskId(adapter, submission));
|
|
394
|
+
if (!phase && !resume && !taskId) throw new Error('任务提交后没有拿到 task_id:' + JSON.stringify(submission).slice(0, 200));
|
|
395
|
+
logHost(kind + ' async task=' + (taskId || 'unknown') + (resume ? ' resumed' : ' submitted'));
|
|
396
|
+
|
|
397
|
+
const poll = adapter.poll || {};
|
|
398
|
+
// 轮询地址只由提交响应和 baseUrl 决定(BFL 的 polling_url、Replicate 的 urls.get、
|
|
399
|
+
// 魔搭的 /v1/tasks/{task_id}),提交后就能算死;算不出来说明提交响应不对,立刻报错。
|
|
400
|
+
const pollTarget = resume
|
|
401
|
+
? String(resume.pollTarget || '')
|
|
402
|
+
: (phase
|
|
403
|
+
? String(phase.pollUrl(submission, provider) || '')
|
|
404
|
+
: pollUrlFor(adapter, provider, taskId));
|
|
405
|
+
if (!pollTarget) throw new Error('任务提交后没有拿到轮询地址:' + JSON.stringify(submission).slice(0, 200));
|
|
406
|
+
// 任务 id / 轮询地址已经拿到:马上落盘,后面进程重启也能从这里继续。
|
|
407
|
+
if (job && !resume) {
|
|
408
|
+
await journal.update(job.id, {
|
|
409
|
+
status: 'submitted', taskId: taskId || '', pollTarget: pollTarget,
|
|
410
|
+
submission: submission, fitted: fitted, note: lastNote
|
|
411
|
+
}).catch((error) => logHost('job journal submit update failed: ' + String(error && error.message ? error.message : error)));
|
|
412
|
+
}
|
|
413
|
+
let interval = phase ? (Number(phase.intervalMs) || 2000) : (Number(poll.intervalMs) || 2000);
|
|
414
|
+
let state = null;
|
|
415
|
+
const pollFields = { jobId: taskId || undefined, submissionState: 'accepted' };
|
|
416
|
+
const pollTimeout = () => timeoutFailure('poll',
|
|
417
|
+
'任务轮询超过本次调用的时间预算' + (state && state.status ? '(最后状态 ' + state.status + ')' : ''),
|
|
418
|
+
pollFields);
|
|
419
|
+
const checkPollBudget = () => {
|
|
420
|
+
if (signal && signal.aborted) throw attachFailure(cancelledFailure('poll', signal), pollFields);
|
|
421
|
+
if (Date.now() >= deadline) throw pollTimeout();
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
while (true) {
|
|
425
|
+
checkPollBudget();
|
|
426
|
+
await sleepWithSignal(Math.min(interval, Math.max(1, deadline - Date.now())), signal);
|
|
427
|
+
checkPollBudget();
|
|
428
|
+
// 每一跳都按目标域重算头:轮询地址可能来自响应,不能默认继承提交用的凭据。
|
|
429
|
+
const headers = pollRequestHeaders(adapter, provider, pollTarget);
|
|
430
|
+
const hopSignal = budgetSignal(deadline, signal);
|
|
431
|
+
let response;
|
|
432
|
+
try {
|
|
433
|
+
response = await request(pollTarget, { method: 'GET', headers: headers, signal: hopSignal });
|
|
434
|
+
} catch (error) {
|
|
435
|
+
if (signal && signal.aborted) throw attachFailure(cancelledFailure('poll', signal), pollFields);
|
|
436
|
+
if (isTimeoutError(error) || Date.now() >= deadline) throw attachFailure(pollTimeout(), { cause: error });
|
|
437
|
+
// 读状态是只读操作:瞬时网络错误退避重试几次,读到有效状态后计数清零。
|
|
438
|
+
pollErrors++;
|
|
439
|
+
logFailure(kind, { code: 'network', phase: 'poll' }, 'poll');
|
|
440
|
+
if (pollErrors > MAX_POLL_ERRORS) {
|
|
441
|
+
throw attachFailure(error, Object.assign({ code: 'network', phase: 'poll' }, pollFields));
|
|
442
|
+
}
|
|
443
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
// 状态码优先于「空响应体」:空 401/403/500 不是「还在跑」。
|
|
447
|
+
if (response.status === 404 || response.status === 405) {
|
|
448
|
+
await cancelBody(response);
|
|
449
|
+
throw attachFailure(new Error('生图任务查询地址不可用(HTTP ' + response.status + ')'), Object.assign({
|
|
450
|
+
code: 'endpoint', phase: 'poll', status: response.status
|
|
451
|
+
}, pollFields));
|
|
452
|
+
}
|
|
453
|
+
// fal 用 202 表示「还在跑」,不能当成错误。
|
|
454
|
+
if (phase && response.status === 202) {
|
|
455
|
+
await cancelBody(response);
|
|
456
|
+
pollErrors = 0;
|
|
457
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
if (!response.ok) {
|
|
461
|
+
const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
462
|
+
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
463
|
+
logHost(kind + ' async poll ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
|
|
464
|
+
const fields = Object.assign({
|
|
465
|
+
code: failureCode(failure), phase: 'poll', status: response.status,
|
|
466
|
+
retryAfterMs: parseRetryAfter(response.headers)
|
|
467
|
+
}, pollFields);
|
|
468
|
+
if (failure.retryable && pollErrors < MAX_POLL_ERRORS) {
|
|
469
|
+
pollErrors++;
|
|
470
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
throw attachFailure(new Error(imageErrorText(failure)), fields);
|
|
474
|
+
}
|
|
475
|
+
const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
476
|
+
if (!buffer.length) {
|
|
477
|
+
// 只有空的 2xx(含 202)才是「还在跑」。
|
|
478
|
+
pollErrors = 0;
|
|
479
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
const payload = safeJson(buffer);
|
|
483
|
+
if (!payload) {
|
|
484
|
+
throw attachFailure(new Error('生图任务查询返回的不是 JSON(HTTP ' + response.status + ')'),
|
|
485
|
+
Object.assign({ code: 'protocol_mismatch', phase: 'poll' }, pollFields));
|
|
486
|
+
}
|
|
487
|
+
state = phase ? phase.statusOf(payload) : readTaskState(adapter, payload);
|
|
488
|
+
pollErrors = 0;
|
|
489
|
+
if (state.state === 'success') {
|
|
490
|
+
try {
|
|
491
|
+
if (phase) {
|
|
492
|
+
const resolved = await phase.resolve(payload, provider, signal, submission);
|
|
493
|
+
if (!resolved) throw new Error('生图任务没有返回图片');
|
|
494
|
+
const image = resolved.bytes ? resolved : await fetchResultImage(resolved.url, hopSignal, adapter, provider);
|
|
495
|
+
logHost(kind + ' async task=' + (taskId || 'unknown') + ' done');
|
|
496
|
+
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType, note: lastNote, jobId: job ? job.id : undefined };
|
|
497
|
+
}
|
|
498
|
+
const decoded = decodeImagePayload(state.node, null);
|
|
499
|
+
const image = decoded.bytes ? decoded : await fetchResultImage(decoded.url, hopSignal, adapter, provider);
|
|
500
|
+
logHost(kind + ' async task=' + taskId + ' done');
|
|
501
|
+
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType, jobId: job ? job.id : undefined };
|
|
502
|
+
} catch (error) {
|
|
503
|
+
throw downloadFailureOf(error, signal, deadline, pollFields);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
if (state.state === 'failure') {
|
|
507
|
+
throw attachFailure(new Error('生图任务失败(' + state.status + '):' + state.message),
|
|
508
|
+
Object.assign({ code: 'task_failed', phase: 'poll' }, pollFields));
|
|
509
|
+
}
|
|
510
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/** 试着把候选结果落成图片;取不到就返回 null,交给后续逻辑(例如继续轮询)。 */
|
|
514
|
+
async function imageOrNull(image, signal, adapter, provider) {
|
|
515
|
+
if (!image) return null;
|
|
516
|
+
try {
|
|
517
|
+
return image.bytes ? image : await fetchResultImage(image.url, signal, adapter, provider);
|
|
518
|
+
} catch (error) {
|
|
519
|
+
// 用户取消/工具超时不能被当成「这个地址不是图」,否则会继续轮询到预算耗尽。
|
|
520
|
+
if (signal && signal.aborted) throw error;
|
|
521
|
+
if (isAbortError(error) || isTimeoutError(error)) throw error;
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* 通用异步入队:同步协议收到「任务包络」时,跟着轮询到出图。
|
|
527
|
+
*
|
|
528
|
+
* 轮询地址优先用响应里给的(polling_url / status_url / urls.get / Location),
|
|
529
|
+
* 没给就按常见约定推:/v1/tasks/{id}、/tasks/{id}、提交地址/{id};
|
|
530
|
+
* 前一个 404/405 就换下一个候选,不要求用户配路径。
|
|
531
|
+
* 轮询地址可能指向另一个域,所以每一跳都按目标域重新算凭据(见 pollRequestHeaders)。
|
|
532
|
+
*/
|
|
533
|
+
export async function followTask(kind, adapter, provider, submission, submitUrl, headers, fitted, model, signal, deadlineAt, hooks) {
|
|
534
|
+
const task = readTaskEnvelope(submission);
|
|
535
|
+
const taskId = (task && task.taskId) || '';
|
|
536
|
+
const candidates = taskPollUrls(provider, submission, submitUrl);
|
|
537
|
+
if (!candidates.length) {
|
|
538
|
+
throw new Error('生图接口返回了异步任务,但没有可用的轮询地址:'
|
|
539
|
+
+ JSON.stringify(submission || {}).slice(0, 200));
|
|
540
|
+
}
|
|
541
|
+
logHost(kind + ' auto-task=' + (taskId || 'unknown') + ' submitted; poll=' + candidates.join(' | '));
|
|
542
|
+
// 提交已经花掉的时间也要算进总预算:不能提交用 5 分钟、轮询再给 5 分钟。
|
|
543
|
+
const deadline = Number.isFinite(deadlineAt) ? deadlineAt : Date.now() + TOTAL_BUDGET_MS;
|
|
544
|
+
const resume = hooks && hooks.resume && typeof hooks.resume === 'object' ? hooks.resume : null;
|
|
545
|
+
const journal = hooks && hooks.journal && typeof hooks.journal.create === 'function' ? hooks.journal : null;
|
|
546
|
+
let job = resume ? { id: String(resume.jobId || '') } : null;
|
|
547
|
+
if (journal && !resume) {
|
|
548
|
+
try {
|
|
549
|
+
job = await journal.create({
|
|
550
|
+
status: 'submitted', kind: kind, providerId: provider.id, providerName: provider.name || '',
|
|
551
|
+
model: String(model || ''), adapterId: adapter.id, taskId: taskId || '',
|
|
552
|
+
submitUrl: submitUrl, submission: submission, pollTarget: candidates[0], fitted: fitted
|
|
553
|
+
});
|
|
554
|
+
} catch (error) {
|
|
555
|
+
logHost('job journal auto-task create failed: ' + String(error && error.message ? error.message : error));
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
let interval = 2000;
|
|
559
|
+
let index = 0;
|
|
560
|
+
let lastStatus = '';
|
|
561
|
+
let pollErrors = 0;
|
|
562
|
+
const probed = new Set();
|
|
563
|
+
const pollFields = { jobId: taskId || undefined, submissionState: 'accepted' };
|
|
564
|
+
const pollTimeout = () => timeoutFailure('poll',
|
|
565
|
+
'任务轮询超过本次调用的时间预算' + (lastStatus ? '(最后状态 ' + lastStatus + ')' : ''),
|
|
566
|
+
pollFields);
|
|
567
|
+
const checkPollBudget = () => {
|
|
568
|
+
if (signal && signal.aborted) throw attachFailure(cancelledFailure('poll', signal), pollFields);
|
|
569
|
+
if (Date.now() >= deadline) throw pollTimeout();
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
while (true) {
|
|
573
|
+
checkPollBudget();
|
|
574
|
+
await sleepWithSignal(Math.min(interval, Math.max(1, deadline - Date.now())), signal);
|
|
575
|
+
checkPollBudget();
|
|
576
|
+
const target = candidates[index];
|
|
577
|
+
// 提交头(可能是提交专用的头 + Key)不能直接带到轮询地址上。
|
|
578
|
+
const pollTargetHeaders = pollRequestHeaders(adapter, provider, target);
|
|
579
|
+
const hopSignal = budgetSignal(deadline, signal);
|
|
580
|
+
let response;
|
|
581
|
+
try {
|
|
582
|
+
response = await request(target, { method: 'GET', headers: pollTargetHeaders, signal: hopSignal });
|
|
583
|
+
} catch (error) {
|
|
584
|
+
if (signal && signal.aborted) throw attachFailure(cancelledFailure('poll', signal), pollFields);
|
|
585
|
+
if (isTimeoutError(error) || Date.now() >= deadline) throw attachFailure(pollTimeout(), { cause: error });
|
|
586
|
+
pollErrors++;
|
|
587
|
+
logFailure(kind, { code: 'network', phase: 'poll' }, 'poll');
|
|
588
|
+
if (pollErrors > MAX_POLL_ERRORS) {
|
|
589
|
+
throw attachFailure(error, Object.assign({ code: 'network', phase: 'poll' }, pollFields));
|
|
590
|
+
}
|
|
591
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
if (response.status === 404 || response.status === 405) {
|
|
595
|
+
// 切候选地址前先放掉响应体,否则连接会一直占着。
|
|
596
|
+
await cancelBody(response);
|
|
597
|
+
if (index + 1 < candidates.length) {
|
|
598
|
+
index++;
|
|
599
|
+
logHost(kind + ' auto-task poll 404, next: ' + candidates[index]);
|
|
600
|
+
interval = Math.min(interval, 2000);
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
throw attachFailure(new Error('生图任务查询地址都不可用(最后一个 ' + target + ' 返回 HTTP ' + response.status + ')'),
|
|
604
|
+
Object.assign({ code: 'endpoint', phase: 'poll', status: response.status }, pollFields));
|
|
605
|
+
}
|
|
606
|
+
if (!response.ok) {
|
|
607
|
+
const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
608
|
+
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
609
|
+
logHost(kind + ' auto-task poll ' + response.status + ' [' + failure.kind + ']');
|
|
610
|
+
const fields = Object.assign({
|
|
611
|
+
code: failureCode(failure), phase: 'poll', status: response.status,
|
|
612
|
+
retryAfterMs: parseRetryAfter(response.headers)
|
|
613
|
+
}, pollFields);
|
|
614
|
+
if (failure.retryable && pollErrors < MAX_POLL_ERRORS) {
|
|
615
|
+
pollErrors++;
|
|
616
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
throw attachFailure(new Error(imageErrorText(failure)), fields);
|
|
620
|
+
}
|
|
621
|
+
const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
622
|
+
// 只有空的 2xx(含 202)才是「还在跑」:空 401/403/500 已经在上面按错误处理。
|
|
623
|
+
if (!buffer.length) {
|
|
624
|
+
pollErrors = 0;
|
|
625
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
const payload = safeJson(buffer);
|
|
629
|
+
if (!payload) {
|
|
630
|
+
throw attachFailure(new Error('生图任务查询返回的不是 JSON(HTTP ' + response.status + ')'),
|
|
631
|
+
Object.assign({ code: 'protocol_mismatch', phase: 'poll' }, pollFields));
|
|
632
|
+
}
|
|
633
|
+
const state = taskStatusOf(payload);
|
|
634
|
+
pollErrors = 0;
|
|
635
|
+
lastStatus = state.status || (state.state === 'success' ? 'SUCCEEDED' : lastStatus);
|
|
636
|
+
if (state.state === 'failure') {
|
|
637
|
+
throw attachFailure(new Error('生图任务失败' + (state.status ? '(' + state.status + ')' : '') + ':' + state.message),
|
|
638
|
+
Object.assign({ code: 'task_failed', phase: 'poll' }, pollFields));
|
|
639
|
+
}
|
|
640
|
+
// 结果图:明确的结果字段优先。成功或没有状态词时,顶层 url 也可能就是图,
|
|
641
|
+
// 先探一次(同一个地址只探一次),不是图就继续等。
|
|
642
|
+
let image = null;
|
|
643
|
+
try {
|
|
644
|
+
const container = taskImageOf(payload, { containersOnly: true });
|
|
645
|
+
if (container) image = await imageOrNull(container, hopSignal, adapter, provider);
|
|
646
|
+
if (!image && (state.state === 'success' || !state.status)) {
|
|
647
|
+
const top = taskImageOf(payload);
|
|
648
|
+
if (top && (top.bytes || !probed.has(top.url))) {
|
|
649
|
+
if (!top.bytes) probed.add(top.url);
|
|
650
|
+
image = await imageOrNull(top, hopSignal, adapter, provider);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
if (!image && state.state === 'success') {
|
|
654
|
+
const loose = looseImageOf(payload);
|
|
655
|
+
if (loose && (loose.bytes || !probed.has(loose.url))) {
|
|
656
|
+
if (!loose.bytes) probed.add(loose.url);
|
|
657
|
+
image = await imageOrNull(loose, hopSignal, adapter, provider);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
} catch (error) {
|
|
661
|
+
if (signal && signal.aborted) throw attachFailure(cancelledFailure('poll', signal), pollFields);
|
|
662
|
+
if (isTimeoutError(error) || (isAbortError(error) && Date.now() >= deadline)) {
|
|
663
|
+
throw attachFailure(pollTimeout(), { cause: error });
|
|
664
|
+
}
|
|
665
|
+
throw error;
|
|
666
|
+
}
|
|
667
|
+
if (image) {
|
|
668
|
+
logHost(kind + ' auto-task=' + (taskId || 'unknown') + ' done');
|
|
669
|
+
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType, jobId: job ? job.id : undefined };
|
|
670
|
+
}
|
|
671
|
+
if (state.state === 'success') {
|
|
672
|
+
throw attachFailure(new Error('生图任务完成了但没有返回图片'),
|
|
673
|
+
Object.assign({ code: 'image_invalid', phase: 'download' }, pollFields));
|
|
674
|
+
}
|
|
675
|
+
interval = Math.min(Math.round(interval * 1.15), 5000);
|
|
676
|
+
}
|
|
677
|
+
throw new Error('生图任务超时(' + (taskId || 'job') + ',最后轮询 ' + candidates[index]
|
|
678
|
+
+ (lastStatus ? ',最后状态 ' + lastStatus : '') + ')');
|
|
679
|
+
}
|
|
680
|
+
export async function callImageApi(kind, adapter, provider, input, signal, hooks) {
|
|
681
|
+
if (!adapterSupportsKind(adapter, kind)) {
|
|
682
|
+
throw new Error('该模型不支持' + (kind === 'edit' ? '图生图' : '文生图')
|
|
683
|
+
+ '(' + String(input.model || adapter.label) + ')。请到设置 → 生图模型换一个支持它的模型。');
|
|
684
|
+
}
|
|
685
|
+
if (adapter.async) return callAsyncImage(kind, adapter, provider, input, signal, hooks);
|
|
686
|
+
if (typeof adapter.execute === 'function') {
|
|
687
|
+
const out = await adapter.execute(kind, provider, input, signal);
|
|
688
|
+
return { fitted: input.fitted, bytes: out.bytes, contentType: out.contentType, note: out.note };
|
|
689
|
+
}
|
|
690
|
+
const fieldNames = (adapter.editFields && adapter.editFields.length) ? adapter.editFields : ['image'];
|
|
691
|
+
// 同步入口也有预算:429 的等待与重试同样不能把一次工具调用拖过超时。
|
|
692
|
+
const deadline = Date.now() + TOTAL_BUDGET_MS;
|
|
693
|
+
const drops = new Set();
|
|
694
|
+
let fitted = input.fitted;
|
|
695
|
+
let fieldIndex = 0;
|
|
696
|
+
let retries = 0;
|
|
697
|
+
let rateRetries = 0;
|
|
698
|
+
let lastFailure = null;
|
|
699
|
+
|
|
700
|
+
for (let attempt = 1; attempt <= MAX_SUBMIT_ATTEMPTS; attempt++) {
|
|
701
|
+
ensureBudget(deadline, 'submit', signal);
|
|
702
|
+
const built = kind === 'edit'
|
|
703
|
+
? prepareEdit(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops, fieldNames[fieldIndex])
|
|
704
|
+
: prepareGenerate(adapter, provider, Object.assign({}, input, { fitted: fitted }), drops);
|
|
705
|
+
const submitUrl = adapterBase(provider) + built.path;
|
|
706
|
+
let response;
|
|
707
|
+
try {
|
|
708
|
+
response = await request(submitUrl, {
|
|
709
|
+
method: 'POST', headers: built.headers, body: built.body, signal: budgetSignal(deadline, signal)
|
|
710
|
+
});
|
|
711
|
+
} catch (error) {
|
|
712
|
+
if (signal && signal.aborted) {
|
|
713
|
+
throw attachFailure(cancelledFailure('submit', signal), { submissionState: 'unknown', cause: error });
|
|
714
|
+
}
|
|
715
|
+
if (isTimeoutError(error) || Date.now() >= deadline) {
|
|
716
|
+
throw timeoutFailure('submit', '提交请求超过本次调用的时间预算', { submissionState: 'unknown', cause: error });
|
|
717
|
+
}
|
|
718
|
+
// 连接都没建立起来(DNS/拒连/TLS)时请求肯定没到上游,重发是安全的;
|
|
719
|
+
// 其它网络错误(连接被重置、等响应头超时)可能已经送达,按受理未知处理。
|
|
720
|
+
if (networkNotSent(error) && retries < MAX_RATE_LIMIT_RETRIES) {
|
|
721
|
+
retries++;
|
|
722
|
+
logHost(kind + ' submit network retry #' + retries + ' code=' + (networkErrorCode(error) || 'network'));
|
|
723
|
+
await sleepWithSignal(retryDelayMs(retries), signal);
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
logFailure(kind, { code: 'network', phase: 'submit' }, 'submit');
|
|
727
|
+
// 同步入口不改原有错误文案(上层靠它定位网络问题),只补结构化字段:
|
|
728
|
+
// submission=unknown 表示这次提交可能已经被上游处理,不能直接重发。
|
|
729
|
+
throw attachFailure(error, {
|
|
730
|
+
code: 'submission_unknown', phase: 'submit', submissionState: 'unknown'
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
const buffer = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
734
|
+
|
|
735
|
+
if (response.ok) {
|
|
736
|
+
const parsed = safeJson(buffer);
|
|
737
|
+
// 通用兼容族:响应里已经有图就直接返回;只有任务包络时才转异步轮询。
|
|
738
|
+
if (adapter.autoAsync) {
|
|
739
|
+
const envelope = parsed ? readTaskEnvelope(parsed) : null;
|
|
740
|
+
// 有任务信号时先只认明确的结果字段;顶层 url 可能指向任务详情,
|
|
741
|
+
// 但也可能就是现成图片,所以再试一次,失败才按任务轮询。
|
|
742
|
+
const direct = parsed ? taskImageOf(parsed, envelope ? { containersOnly: true } : undefined) : null;
|
|
743
|
+
const candidate = direct || (parsed && envelope ? taskImageOf(parsed) : null);
|
|
744
|
+
const image = await imageOrNull(candidate, budgetSignal(deadline, signal), adapter, provider);
|
|
745
|
+
if (image) return { fitted: fitted, bytes: image.bytes, contentType: image.contentType };
|
|
746
|
+
if (envelope) {
|
|
747
|
+
return await followTask(kind, adapter, provider, parsed, submitUrl, built.headers, fitted, input.model, signal, deadline, hooks);
|
|
748
|
+
}
|
|
749
|
+
// 202 + Location 也是常见的「任务已受理」形状。
|
|
750
|
+
const headerPoll = String(response.headers.get('location') || '').trim();
|
|
751
|
+
if (headerPoll) {
|
|
752
|
+
return await followTask(kind, adapter, provider, { poll_url: headerPoll }, submitUrl, built.headers, fitted, input.model, signal, deadline, hooks);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
// 同步协议收到异步任务:先说清是协议没对上,别让模型以为是图片格式问题去重试。
|
|
756
|
+
if (parsed && !parsed.data && (parsed.task_id || parsed.task_status)) {
|
|
757
|
+
throw new Error('这个接口返回的是异步任务(task_id='
|
|
758
|
+
+ String(parsed.task_id || '未给出')
|
|
759
|
+
+ '),当前「API 协议」按同步方式调用,拿不到图片。请到设置 → 生图模型把「API 协议」改成「自动识别」,或选对应平台的异步适配器(例如魔搭选 modelscope)。');
|
|
760
|
+
}
|
|
761
|
+
const decoded = parsed ? decodeImagePayload(parsed, null) : decodeImagePayload(null, buffer);
|
|
762
|
+
const image = decoded.bytes ? decoded : await fetchImageUrl(decoded.url, signal);
|
|
763
|
+
return { fitted: fitted, bytes: image.bytes, contentType: image.contentType };
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
const failure = classifyFailure(response.status, buffer.toString('utf8'));
|
|
767
|
+
lastFailure = failure;
|
|
768
|
+
logHost(kind + ' upstream ' + response.status + ' [' + failure.kind + '] ' + failure.message.slice(0, 200));
|
|
769
|
+
|
|
770
|
+
const capability = unsupportedModelMessage(kind, failure);
|
|
771
|
+
if (capability) {
|
|
772
|
+
throw attachFailure(new Error(capability), {
|
|
773
|
+
code: 'unsupported_model', phase: 'submit', submissionState: 'rejected', status: response.status
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
if (failure.kind === 'param' && failure.drop && !drops.has(failure.drop)) {
|
|
778
|
+
if (isProtectedDropField(failure.drop)) {
|
|
779
|
+
logHost(kind + ' refused to drop a protected field');
|
|
780
|
+
throw attachFailure(new Error(imageErrorText(failure)
|
|
781
|
+
+ '(上游要求移除必要字段 ' + failure.drop + ';这属于请求与模型不兼容,不能自动摘除)'), {
|
|
782
|
+
code: 'param', phase: 'submit', submissionState: 'rejected', status: response.status
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
drops.add(failure.drop);
|
|
786
|
+
logHost(kind + ' drop param "' + failure.drop + '" for adapter ' + adapter.id);
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
if (kind === 'edit' && response.status === 400 && /image/i.test(failure.message) && fieldIndex + 1 < fieldNames.length) {
|
|
790
|
+
fieldIndex++;
|
|
791
|
+
logHost(kind + ' retry with form field "' + fieldNames[fieldIndex] + '"');
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
if (failure.kind === 'size') {
|
|
795
|
+
throw attachFailure(new Error(sizeRejectedText(kind, adapter, input, failure, fitted)), {
|
|
796
|
+
code: 'size', phase: 'submit', submissionState: 'rejected', status: response.status
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
// 429:上游明确没有入队,按 Retry-After 等待,最多两次。
|
|
800
|
+
if (failure.kind === 'rate') {
|
|
801
|
+
const retryAfterMs = parseRetryAfter(response.headers);
|
|
802
|
+
if (rateRetries >= MAX_RATE_LIMIT_RETRIES) {
|
|
803
|
+
throw attachFailure(new Error(imageErrorText(failure)), {
|
|
804
|
+
code: 'rate_limit', phase: 'submit', submissionState: 'rejected',
|
|
805
|
+
retryAfterMs: retryAfterMs, status: response.status
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
rateRetries++;
|
|
809
|
+
const waitMs = Math.min(retryDelayMs(rateRetries, { retryAfterMs: retryAfterMs }),
|
|
810
|
+
Math.max(0, deadline - Date.now()));
|
|
811
|
+
logHost(kind + ' rate limited, retry #' + rateRetries + ' in ' + waitMs + 'ms');
|
|
812
|
+
await sleepWithSignal(waitMs, signal);
|
|
813
|
+
continue;
|
|
814
|
+
}
|
|
815
|
+
if (failure.retryable && retries < 2) {
|
|
816
|
+
retries++;
|
|
817
|
+
logHost(kind + ' upstream retry #' + retries + ' after HTTP ' + response.status);
|
|
818
|
+
await sleepWithSignal(retryDelayMs(retries, { retryAfterMs: parseRetryAfter(response.headers) }), signal);
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
// 5xx 重试用尽后「上游是否已受理」仍然不明;4xx 则是明确拒绝。
|
|
822
|
+
throw attachFailure(new Error(imageErrorText(failure)), {
|
|
823
|
+
code: failureCode(failure), phase: 'submit',
|
|
824
|
+
submissionState: failure.retryable ? 'unknown' : 'rejected',
|
|
825
|
+
retryAfterMs: parseRetryAfter(response.headers), status: response.status
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
throw attachFailure(new Error(imageErrorText(lastFailure || { kind: 'unknown', message: '重试次数用尽' })), {
|
|
829
|
+
code: failureCode(lastFailure), phase: 'submit', submissionState: 'unknown'
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* 模型不接收尺寸参数时的降级:把尺寸写进提示词。
|
|
834
|
+
* 生图模型对英文尺寸句最稳,所以这句固定英文。
|
|
835
|
+
*/
|