dsh-sendcomfy 0.0.0-stage → 0.5.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/lib/comfy.mjs ADDED
@@ -0,0 +1,968 @@
1
+ /**
2
+ * dsh-sendcomfy — ComfyUI HTTP 客户端(契约见 CONTRACT.md §2)
3
+ *
4
+ * 纯函数模块:
5
+ * - 所有网络函数都显式接收 `baseUrl`,不读全局业务状态;
6
+ * - 网络失败抛 `ComfyError`(带 code);健康检查类(ping / listUserdataWorkflows)
7
+ * 自己吞错并返回 `{ ok:false, error }`;
8
+ * - 模块内唯一的状态是 `/object_info` 的 60s 缓存(getObjectInfo / invalidateObjectInfo)。
9
+ *
10
+ * 零第三方依赖:只用 Node 内建 + 全局 fetch / FormData / Blob / AbortSignal.timeout。
11
+ */
12
+
13
+ import { setTimeout as sleep } from 'node:timers/promises'
14
+ import { Buffer } from 'node:buffer'
15
+ import { gunzipSync, createInflateRaw, constants as zlibConstants } from 'node:zlib'
16
+ import { Readable } from 'node:stream'
17
+
18
+ export const DEFAULT_BASE_URL = 'http://127.0.0.1:8188'
19
+ const DEFAULT_COMFY_PORT = '8188'
20
+ const OBJECT_INFO_TTL_MS = 60_000
21
+
22
+ /** ComfyUI 请求错误。code: EINVALID_URL | EHTTP | ENET | ETIMEDOUT | EBAD_RESPONSE | EINVALID_ARG | ... */
23
+ export class ComfyError extends Error {
24
+ constructor(message, options = {}) {
25
+ const opts = typeof options === 'string' ? { code: options } : (options || {})
26
+ super(message == null ? 'ComfyUI 请求失败' : String(message))
27
+ this.name = 'ComfyError'
28
+ this.code = opts.code || 'ECOMFY'
29
+ if (opts.status !== undefined) this.status = opts.status
30
+ if (opts.detail !== undefined) this.detail = opts.detail
31
+ if (opts.cause !== undefined) this.cause = opts.cause
32
+ if (opts.json !== undefined) this.json = opts.json
33
+ }
34
+
35
+ toJSON() {
36
+ return {
37
+ name: this.name,
38
+ code: this.code,
39
+ message: this.message,
40
+ status: this.status,
41
+ detail: this.detail,
42
+ }
43
+ }
44
+ }
45
+
46
+ function invalidUrlError(input) {
47
+ return new ComfyError(`ComfyUI 地址不合法:${JSON.stringify(String(input))}`, {
48
+ code: 'EINVALID_URL',
49
+ detail: String(input),
50
+ })
51
+ }
52
+
53
+ /**
54
+ * 规范化 ComfyUI 地址:
55
+ * '127.0.0.1:8188' | '192.168.1.5' | 'http://host:8188/' -> 'http://127.0.0.1:8188'
56
+ * 规则:去空白;无 scheme 补 http://;无端口补 :8188;去尾部 '/';
57
+ * 非 http/https、含空白、端口非法 -> 抛 ComfyError(code='EINVALID_URL')。
58
+ * undefined / null -> 默认 'http://127.0.0.1:8188';'' -> 抛错。
59
+ */
60
+ export function normalizeBaseUrl(input) {
61
+ if (input === undefined || input === null) return DEFAULT_BASE_URL
62
+ if (typeof input !== 'string') throw invalidUrlError(input)
63
+
64
+ const raw = input.trim()
65
+ if (!raw) throw invalidUrlError(input)
66
+ if (/\s/.test(raw)) throw invalidUrlError(input)
67
+
68
+ // scheme
69
+ let scheme = 'http'
70
+ let rest = raw
71
+ const schemeMatch = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(raw)
72
+ if (schemeMatch) {
73
+ scheme = schemeMatch[1].toLowerCase()
74
+ rest = raw.slice(schemeMatch[0].length)
75
+ }
76
+ if (scheme !== 'http' && scheme !== 'https') throw invalidUrlError(input)
77
+
78
+ // authority + path
79
+ const sepIdx = rest.search(/[/?#]/)
80
+ const authority = sepIdx < 0 ? rest : rest.slice(0, sepIdx)
81
+ let tail = sepIdx < 0 ? '' : rest.slice(sepIdx)
82
+ if (!authority) throw invalidUrlError(input)
83
+
84
+ let hostPart = authority
85
+ let port = ''
86
+ if (hostPart.startsWith('[')) {
87
+ // IPv6 字面量:[::1] / [::1]:8188
88
+ const close = hostPart.indexOf(']')
89
+ if (close < 0) throw invalidUrlError(input)
90
+ const after = hostPart.slice(close + 1)
91
+ hostPart = hostPart.slice(0, close + 1)
92
+ if (after) {
93
+ if (!after.startsWith(':')) throw invalidUrlError(input)
94
+ port = after.slice(1)
95
+ }
96
+ } else {
97
+ const colon = hostPart.lastIndexOf(':')
98
+ if (colon >= 0) {
99
+ port = hostPart.slice(colon + 1)
100
+ hostPart = hostPart.slice(0, colon)
101
+ }
102
+ }
103
+ if (!hostPart) throw invalidUrlError(input)
104
+ if (!port) {
105
+ port = DEFAULT_COMFY_PORT
106
+ } else if (!/^\d{1,5}$/.test(port) || Number(port) < 1 || Number(port) > 65535) {
107
+ throw invalidUrlError(input)
108
+ }
109
+
110
+ // path(丢弃 query/hash,去掉尾部 '/')
111
+ const qIdx = tail.search(/[?#]/)
112
+ if (qIdx >= 0) tail = tail.slice(0, qIdx)
113
+ const pathname = tail.replace(/\/+$/, '')
114
+ return `${scheme}://${hostPart}:${port}${pathname}`
115
+ }
116
+
117
+ /** 错误 -> 给人类看的中文字符串(ping/listUserdataWorkflows 的 error 字段用)。 */
118
+ export function humanError(err) {
119
+ if (err === undefined || err === null) return '未知错误'
120
+ if (typeof err === 'string') return err
121
+ if (err instanceof ComfyError) return err.message
122
+ if (err.name === 'AbortError') return '已取消'
123
+ const message = typeof err.message === 'string' && err.message ? err.message : String(err)
124
+ const causeCode = err.cause && typeof err.cause === 'object' ? err.cause.code : undefined
125
+ if (causeCode && !message.includes(String(causeCode))) return `${message}(${causeCode})`
126
+ return message
127
+ }
128
+
129
+ function normalizeRequestPath(path) {
130
+ const p = path === undefined || path === null ? '' : String(path)
131
+ if (!p) return ''
132
+ return p.startsWith('/') ? p : `/${p}`
133
+ }
134
+
135
+ function isFormDataBody(body) {
136
+ return typeof FormData !== 'undefined' && body instanceof FormData
137
+ }
138
+
139
+ function isBinaryBody(body) {
140
+ return body instanceof ArrayBuffer
141
+ || ArrayBuffer.isView(body)
142
+ || (typeof Blob !== 'undefined' && body instanceof Blob)
143
+ }
144
+
145
+ function hasHeader(headers, name) {
146
+ const lower = name.toLowerCase()
147
+ return Object.keys(headers || {}).some((key) => key.toLowerCase() === lower)
148
+ }
149
+
150
+ function normalizeTimeout(timeoutMs, fallback) {
151
+ const n = Number(timeoutMs)
152
+ if (!Number.isFinite(n) || n <= 0) return fallback
153
+ return Math.max(1, Math.floor(n))
154
+ }
155
+
156
+ function networkError(err, target, timeoutMs) {
157
+ const name = err && err.name
158
+ if (name === 'TimeoutError' || name === 'AbortError') {
159
+ return new ComfyError(`ComfyUI 请求超时(${timeoutMs}ms):${target}`, {
160
+ code: 'ETIMEDOUT',
161
+ detail: `timeout after ${timeoutMs}ms`,
162
+ cause: err,
163
+ })
164
+ }
165
+ const cause = err && err.cause
166
+ const detail = (cause && (cause.code || cause.message)) || (err && err.message) || String(err)
167
+ return new ComfyError(`无法连接 ComfyUI:${target}(${detail})`, {
168
+ code: 'ENET',
169
+ detail: String(detail),
170
+ cause: err,
171
+ })
172
+ }
173
+
174
+ function extractDetail(json, text) {
175
+ if (json && typeof json === 'object') {
176
+ if (typeof json.error === 'string' && json.error) return json.error
177
+ if (json.error && typeof json.error === 'object') {
178
+ if (typeof json.error.message === 'string' && json.error.message) return json.error.message
179
+ if (typeof json.error.detail === 'string' && json.error.detail) return json.error.detail
180
+ }
181
+ if (typeof json.message === 'string' && json.message) return json.message
182
+ if (json.node_errors && typeof json.node_errors === 'object' && Object.keys(json.node_errors).length) {
183
+ return `节点错误:${JSON.stringify(json.node_errors).slice(0, 500)}`
184
+ }
185
+ }
186
+ const trimmed = typeof text === 'string' ? text.trim() : ''
187
+ return trimmed.slice(0, 500)
188
+ }
189
+
190
+ async function rawFetch(target, { method = 'GET', body, timeoutMs = 15000, headers } = {}) {
191
+ const timeout = normalizeTimeout(timeoutMs, 15000)
192
+ const init = { method: method.toUpperCase(), signal: AbortSignal.timeout(timeout) }
193
+ if (headers) init.headers = { ...headers }
194
+ if (body !== undefined && body !== null) init.body = body
195
+ try {
196
+ return await fetch(target, init)
197
+ } catch (err) {
198
+ throw networkError(err, target, timeout)
199
+ }
200
+ }
201
+
202
+ /**
203
+ * 通用请求。
204
+ * -> { status, json }(附带 text;json 为解析后的 JSON,非 JSON 响应为 undefined)
205
+ * 非 2xx -> ComfyError(code='EHTTP', status, detail, json);网络/超时 -> ENET / ETIMEDOUT。
206
+ * body 为普通对象时自动 JSON.stringify + content-type: application/json;
207
+ * body 为 FormData / Uint8Array / Blob 时原样发送。
208
+ */
209
+ export async function request(baseUrl, path, { method = 'GET', body, timeoutMs = 15000, headers } = {}) {
210
+ const base = normalizeBaseUrl(baseUrl)
211
+ const target = `${base}${normalizeRequestPath(path)}`
212
+ const timeout = normalizeTimeout(timeoutMs, 15000)
213
+
214
+ const init = {
215
+ method: String(method || 'GET').toUpperCase(),
216
+ headers: { ...(headers || {}) },
217
+ signal: AbortSignal.timeout(timeout),
218
+ }
219
+ if (body !== undefined && body !== null) {
220
+ if (isFormDataBody(body) || isBinaryBody(body) || typeof body === 'string') {
221
+ init.body = body
222
+ } else {
223
+ init.body = JSON.stringify(body)
224
+ if (!hasHeader(init.headers, 'content-type')) init.headers['content-type'] = 'application/json'
225
+ }
226
+ }
227
+
228
+ let res
229
+ try {
230
+ res = await fetch(target, init)
231
+ } catch (err) {
232
+ throw networkError(err, target, timeout)
233
+ }
234
+
235
+ let buffer
236
+ try {
237
+ buffer = Buffer.from(await res.arrayBuffer())
238
+ } catch {
239
+ buffer = Buffer.alloc(0)
240
+ }
241
+ const text = buffer.toString('utf8')
242
+ let json
243
+ if (text) {
244
+ try {
245
+ json = JSON.parse(text.replace(/^\uFEFF/, ''))
246
+ } catch {
247
+ json = undefined
248
+ }
249
+ }
250
+
251
+ if (!res.ok) {
252
+ const detail = extractDetail(json, text)
253
+ throw new ComfyError(
254
+ `ComfyUI 请求失败:${init.method} ${target} -> HTTP ${res.status}${detail ? `(${detail})` : ''}`,
255
+ { code: 'EHTTP', status: res.status, detail, json },
256
+ )
257
+ }
258
+ return { status: res.status, json, text, buffer }
259
+ }
260
+
261
+ // ---------------------------------------------------------------------------
262
+ // /system_stats
263
+ // ---------------------------------------------------------------------------
264
+
265
+ /**
266
+ * 连通性检查(永远不抛错)。
267
+ * -> { ok:true, baseUrl, latencyMs, comfyuiVersion?, device?, system? }
268
+ * | { ok:false, baseUrl, latencyMs, error }
269
+ */
270
+ export async function ping(baseUrl, { timeoutMs = 5000 } = {}) {
271
+ const started = Date.now()
272
+ let normalized
273
+ try {
274
+ normalized = normalizeBaseUrl(baseUrl)
275
+ } catch (err) {
276
+ return {
277
+ ok: false,
278
+ baseUrl: baseUrl === undefined || baseUrl === null ? '' : String(baseUrl),
279
+ latencyMs: 0,
280
+ error: humanError(err),
281
+ }
282
+ }
283
+ try {
284
+ const timeout = normalizeTimeout(timeoutMs, 5000)
285
+ const res = await request(normalized, '/system_stats', { timeoutMs: timeout })
286
+ const stats = res.json && typeof res.json === 'object' ? res.json : {}
287
+ const system = stats.system && typeof stats.system === 'object' ? stats.system : undefined
288
+ const devices = Array.isArray(stats.devices) ? stats.devices : []
289
+ const firstDevice = devices[0]
290
+ const device = firstDevice && typeof firstDevice === 'object'
291
+ ? (firstDevice.name ?? firstDevice.type ?? undefined)
292
+ : undefined
293
+ return {
294
+ ok: true,
295
+ baseUrl: normalized,
296
+ latencyMs: Math.max(0, Date.now() - started),
297
+ comfyuiVersion: system ? system.comfyui_version : undefined,
298
+ device: device === undefined ? undefined : String(device),
299
+ system,
300
+ }
301
+ } catch (err) {
302
+ return {
303
+ ok: false,
304
+ baseUrl: normalized,
305
+ latencyMs: Math.max(0, Date.now() - started),
306
+ error: humanError(err),
307
+ }
308
+ }
309
+ }
310
+
311
+ // ---------------------------------------------------------------------------
312
+ // /object_info(60s 缓存)
313
+ // ---------------------------------------------------------------------------
314
+
315
+ const objectInfoCache = new Map() // baseUrl -> { data, at } | { promise }
316
+
317
+ /**
318
+ * 原始 object_info 对象。模块内按 baseUrl 缓存 60s;refresh=true 绕过缓存。
319
+ * 失败抛 ComfyError。
320
+ */
321
+ export async function getObjectInfo(baseUrl, { refresh = false, timeoutMs = 30000 } = {}) {
322
+ const base = normalizeBaseUrl(baseUrl)
323
+ const cached = objectInfoCache.get(base)
324
+ if (cached && cached.promise) return cached.promise
325
+ if (!refresh && cached && typeof cached.at === 'number' && Date.now() - cached.at < OBJECT_INFO_TTL_MS) {
326
+ return cached.data
327
+ }
328
+
329
+ const promise = (async () => {
330
+ const res = await request(base, '/object_info', { timeoutMs })
331
+ const data = res.json
332
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
333
+ throw new ComfyError('ComfyUI /object_info 返回格式不正确', { code: 'EBAD_RESPONSE' })
334
+ }
335
+ objectInfoCache.set(base, { data, at: Date.now() })
336
+ return data
337
+ })()
338
+
339
+ objectInfoCache.set(base, { promise })
340
+ try {
341
+ return await promise
342
+ } catch (err) {
343
+ const current = objectInfoCache.get(base)
344
+ if (current && current.promise === promise) objectInfoCache.delete(base)
345
+ throw err
346
+ }
347
+ }
348
+
349
+ /** 清 object_info 缓存;不给 baseUrl 清全部。 */
350
+ export function invalidateObjectInfo(baseUrl) {
351
+ if (baseUrl === undefined || baseUrl === null) {
352
+ objectInfoCache.clear()
353
+ return
354
+ }
355
+ try {
356
+ objectInfoCache.delete(normalizeBaseUrl(baseUrl))
357
+ } catch {
358
+ // 非法 URL 不可能有缓存键,忽略
359
+ }
360
+ }
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // 模型清单(从 object_info 的模型枚举里抽)
364
+ // ---------------------------------------------------------------------------
365
+
366
+ const MODEL_EXT_RE = /\.(safetensors|sft|ckpt|pt|pth|bin|gguf|onnx|yaml)$/i
367
+
368
+ /** 契约 §2 要求的固定类别顺序与展示名。 */
369
+ const MODEL_CATEGORIES = [
370
+ ['checkpoints', 'Checkpoints'],
371
+ ['loras', 'LoRAs'],
372
+ ['vae', 'VAE'],
373
+ ['clip', 'CLIP'],
374
+ ['unet', 'UNET/Diffusion'],
375
+ ['controlnet', 'ControlNet'],
376
+ ['upscale', 'Upscale'],
377
+ ['clip_vision', 'CLIP Vision'],
378
+ ['style_models', 'Style models'],
379
+ ['embeddings', 'Embeddings'],
380
+ ['ipadapter', 'IPAdapter'],
381
+ ['gligen', 'GLIGEN'],
382
+ ['other', 'Other models'],
383
+ ]
384
+
385
+ /**
386
+ * 已知的「模型加载节点类 -> 类别」映射(可识别标准节点与常见自定义节点族)。
387
+ * 未命中的类走兜底:枚举值是模型文件后缀 -> other。
388
+ */
389
+ const KNOWN_CLASS_CATEGORY = [
390
+ [/^CheckpointLoader/i, 'checkpoints'],
391
+ [/LoraLoader|LoraModelLoader|LyCORISLoader|LoRALoader/i, 'loras'],
392
+ [/^VAELoader$|^VAELoader\b/i, 'vae'],
393
+ [/^CLIPVisionLoader$|^CLIPVisionLoader\b/i, 'clip_vision'],
394
+ [/^DualCLIPLoader|^CLIPLoader$|^CLIPLoader\b|^CLIPLoaderGGUF/i, 'clip'],
395
+ [/^UNETLoader$|^UNETLoader\b|^UnetLoaderGGUF/i, 'unet'],
396
+ [/ControlNet/i, 'controlnet'],
397
+ [/UpscaleModel/i, 'upscale'],
398
+ [/StyleModel/i, 'style_models'],
399
+ [/GLIGEN/i, 'gligen'],
400
+ [/IPAdapter/i, 'ipadapter'],
401
+ [/^Embedding/i, 'embeddings'],
402
+ ]
403
+
404
+ function enumOptionValues(def) {
405
+ if (Array.isArray(def)) {
406
+ const type = def[0]
407
+ if (Array.isArray(type)) return type.filter((v) => typeof v === 'string')
408
+ return []
409
+ }
410
+ if (def && typeof def === 'object' && Array.isArray(def.options)) {
411
+ return def.options.filter((v) => typeof v === 'string')
412
+ }
413
+ return []
414
+ }
415
+
416
+ function collectInputDefs(spec) {
417
+ const out = []
418
+ const input = spec && typeof spec === 'object' ? spec.input : undefined
419
+ if (!input || typeof input !== 'object') return out
420
+ const groups = [input.required, input.optional].filter((g) => g && typeof g === 'object')
421
+ if (!groups.length) groups.push(input) // 极旧的格式:input 直接是 map
422
+ for (const group of groups) {
423
+ for (const [inputName, def] of Object.entries(group)) out.push([inputName, def])
424
+ }
425
+ return out
426
+ }
427
+
428
+ function classifyModelInput(classType, inputName) {
429
+ const cls = String(classType || '')
430
+ const name = String(inputName || '')
431
+
432
+ for (const [re, category] of KNOWN_CLASS_CATEGORY) {
433
+ if (re.test(cls)) return category
434
+ }
435
+ // 兜底:输入名/节点类含模型关键词 -> other
436
+ if (/model|ckpt|checkpoint|lora|vae|clip|unet|diffusion|control.?net|upscale|embedding|ip.?adapter|gligen/i.test(`${name} ${cls}`)) {
437
+ return 'other'
438
+ }
439
+ // 仍然是模型文件枚举(带模型后缀)但没关键词:归 other,别丢模型
440
+ return 'other'
441
+ }
442
+
443
+ /**
444
+ * 从 object_info 抽模型文件。
445
+ * -> { ok, baseUrl, total, categories: [{ id, label, count, files }], warnings?, error? }
446
+ * 失败不抛(ok:false + error)。
447
+ */
448
+ export async function listModels(baseUrl, { refresh = false } = {}) {
449
+ let normalized
450
+ try {
451
+ normalized = normalizeBaseUrl(baseUrl)
452
+ } catch (err) {
453
+ return {
454
+ ok: false,
455
+ baseUrl: baseUrl === undefined || baseUrl === null ? '' : String(baseUrl),
456
+ total: 0,
457
+ categories: MODEL_CATEGORIES.map(([id, label]) => ({ id, label, count: 0, files: [] })),
458
+ error: humanError(err),
459
+ }
460
+ }
461
+
462
+ let objectInfo
463
+ try {
464
+ objectInfo = await getObjectInfo(normalized, { refresh })
465
+ } catch (err) {
466
+ return {
467
+ ok: false,
468
+ baseUrl: normalized,
469
+ total: 0,
470
+ categories: MODEL_CATEGORIES.map(([id, label]) => ({ id, label, count: 0, files: [] })),
471
+ error: humanError(err),
472
+ }
473
+ }
474
+
475
+ const buckets = new Map(MODEL_CATEGORIES.map(([id]) => [id, new Set()]))
476
+ const warnings = []
477
+
478
+ try {
479
+ for (const [classType, spec] of Object.entries(objectInfo)) {
480
+ for (const [inputName, def] of collectInputDefs(spec)) {
481
+ const values = enumOptionValues(def)
482
+ if (!values.length) continue
483
+ const files = values.map((v) => v.trim()).filter((v) => v && MODEL_EXT_RE.test(v))
484
+ if (!files.length) continue // 例如 KSampler 的 sampler_name/scheduler、CLIPLoader 的 type
485
+ const categoryId = classifyModelInput(classType, inputName)
486
+ const bucket = buckets.get(categoryId) || buckets.get('other')
487
+ for (const file of files) bucket.add(file)
488
+ }
489
+ }
490
+ } catch (err) {
491
+ warnings.push(`解析 object_info 时出错:${humanError(err)}`)
492
+ }
493
+
494
+ const categories = MODEL_CATEGORIES.map(([id, label]) => {
495
+ const files = [...buckets.get(id)].sort((a, b) => a.localeCompare(b))
496
+ return { id, label, count: files.length, files }
497
+ })
498
+ const total = categories.reduce((sum, category) => sum + category.count, 0)
499
+ if (!total) warnings.push('未能从 object_info 中识别出模型文件;请确认 ComfyUI 已加载模型。')
500
+
501
+ return { ok: true, baseUrl: normalized, total, categories, warnings }
502
+ }
503
+
504
+ // ---------------------------------------------------------------------------
505
+ // /prompt、/history
506
+ // ---------------------------------------------------------------------------
507
+
508
+ /** POST /prompt -> { promptId, number, nodeErrors? };node_errors 非空也照常返回。 */
509
+ export async function queuePrompt(baseUrl, apiGraph, { clientId, timeoutMs = 30000 } = {}) {
510
+ const body = { prompt: apiGraph }
511
+ if (clientId !== undefined && clientId !== null && clientId !== '') body.client_id = String(clientId)
512
+ const res = await request(baseUrl, '/prompt', { method: 'POST', body, timeoutMs })
513
+ const json = res.json && typeof res.json === 'object' ? res.json : {}
514
+ const promptId = json.prompt_id ?? json.promptId
515
+ if (promptId === undefined || promptId === null || promptId === '') {
516
+ throw new ComfyError('ComfyUI /prompt 未返回 prompt_id', {
517
+ code: 'EBAD_RESPONSE',
518
+ detail: JSON.stringify(json).slice(0, 500),
519
+ })
520
+ }
521
+ const out = { promptId: String(promptId) }
522
+ if (json.number !== undefined) out.number = json.number
523
+ const nodeErrors = json.node_errors
524
+ if (nodeErrors && typeof nodeErrors === 'object' && Object.keys(nodeErrors).length) {
525
+ out.nodeErrors = nodeErrors
526
+ }
527
+ return out
528
+ }
529
+
530
+ /** GET /history/{promptId} -> entry | null(没有该 promptId 时 null)。 */
531
+ export async function getHistory(baseUrl, promptId, { timeoutMs = 15000 } = {}) {
532
+ const id = String(promptId)
533
+ const res = await request(baseUrl, `/history/${encodeURIComponent(id)}`, { timeoutMs })
534
+ const json = res.json
535
+ if (!json || typeof json !== 'object' || Array.isArray(json)) return null
536
+ if (json[id] && typeof json[id] === 'object') return json[id]
537
+ // 兼容个别网关直接返回 entry
538
+ if (json.status || json.outputs || json.prompt) return json
539
+ const first = Object.values(json).find((v) => v && typeof v === 'object' && ('status' in v || 'outputs' in v))
540
+ return first || null
541
+ }
542
+
543
+ function extractExecutionError(entry) {
544
+ const status = entry && typeof entry.status === 'object' ? entry.status : {}
545
+ const messages = Array.isArray(status.messages) ? status.messages : (Array.isArray(entry?.messages) ? entry.messages : undefined)
546
+ if (Array.isArray(messages)) {
547
+ for (const item of messages) {
548
+ const type = Array.isArray(item) ? item[0] : (item && item.type)
549
+ const data = Array.isArray(item) ? item[1] : item
550
+ if (type === 'execution_error') {
551
+ const message = data && (data.message ?? data.exception_message ?? data.exception_type)
552
+ if (message) return String(message)
553
+ }
554
+ }
555
+ }
556
+ if (status && typeof status.status_str === 'string' && status.status_str === 'error') {
557
+ return 'ComfyUI 工作流执行出错'
558
+ }
559
+ return undefined
560
+ }
561
+
562
+ function classifyHistoryEntry(entry) {
563
+ const status = entry && typeof entry.status === 'object' && entry.status ? entry.status : {}
564
+ const statusStr = status.status_str ?? (entry && typeof entry.status_str === 'string' ? entry.status_str : undefined)
565
+ if (statusStr === 'error') {
566
+ return { state: 'error', error: extractExecutionError(entry) || 'ComfyUI 工作流执行出错' }
567
+ }
568
+ if (statusStr === 'success' || status.completed === true) return { state: 'done' }
569
+ const outputs = entry && entry.outputs
570
+ if (outputs && typeof outputs === 'object' && Object.keys(outputs).length) return { state: 'done' }
571
+ return { state: 'pending' }
572
+ }
573
+
574
+ function makeAbortError(signal) {
575
+ const err = new Error('已取消')
576
+ err.name = 'AbortError'
577
+ err.code = 'EABORT'
578
+ if (signal && signal.reason !== undefined) err.cause = signal.reason
579
+ return err
580
+ }
581
+
582
+ async function sleepOrAbort(ms, signal) {
583
+ if (!(ms > 0)) return
584
+ try {
585
+ await sleep(ms, undefined, signal ? { signal } : undefined)
586
+ } catch (err) {
587
+ if (err && err.name === 'AbortError') throw makeAbortError(signal)
588
+ throw err
589
+ }
590
+ }
591
+
592
+ /**
593
+ * 轮询 /history 直到完成/出错/超时。
594
+ * -> { state:'done'|'error'|'timeout'|'missing', entry?, error? }(超时不抛)
595
+ * signal aborted -> 抛 AbortError。
596
+ */
597
+ export async function waitForPrompt(baseUrl, promptId, { timeoutMs = 300000, pollMs = 800, signal } = {}) {
598
+ const totalMs = Number.isFinite(Number(timeoutMs)) && Number(timeoutMs) > 0 ? Math.floor(Number(timeoutMs)) : 300000
599
+ const interval = Number.isFinite(Number(pollMs)) && Number(pollMs) > 0 ? Math.max(10, Math.floor(Number(pollMs))) : 800
600
+ const deadline = Date.now() + totalMs
601
+ let lastEntry
602
+ let lastError
603
+
604
+ while (true) {
605
+ if (signal && signal.aborted) throw makeAbortError(signal)
606
+
607
+ const remaining = deadline - Date.now()
608
+ const requestTimeout = Math.max(1000, Math.min(15000, remaining > 0 ? remaining : 1000))
609
+ try {
610
+ const entry = await getHistory(baseUrl, promptId, { timeoutMs: requestTimeout })
611
+ if (entry) {
612
+ lastEntry = entry
613
+ const verdict = classifyHistoryEntry(entry)
614
+ if (verdict.state === 'done') return { state: 'done', entry }
615
+ if (verdict.state === 'error') return { state: 'error', entry, error: verdict.error }
616
+ }
617
+ } catch (err) {
618
+ if (err && err.name === 'AbortError') throw makeAbortError(signal)
619
+ lastError = err
620
+ }
621
+
622
+ if (signal && signal.aborted) throw makeAbortError(signal)
623
+ const left = deadline - Date.now()
624
+ if (left <= 0) {
625
+ const out = { state: 'timeout' }
626
+ if (lastEntry) out.entry = lastEntry
627
+ if (lastError) out.error = humanError(lastError)
628
+ return out
629
+ }
630
+ await sleepOrAbort(Math.min(interval, left), signal)
631
+ }
632
+ }
633
+
634
+ // ---------------------------------------------------------------------------
635
+ // /queue、/interrupt
636
+ // ---------------------------------------------------------------------------
637
+
638
+ function normalizeQueueList(list) {
639
+ if (!Array.isArray(list)) return []
640
+ const out = []
641
+ for (const item of list) {
642
+ let promptId
643
+ let number
644
+ if (Array.isArray(item)) {
645
+ number = item[0]
646
+ promptId = item[1]
647
+ } else if (item && typeof item === 'object') {
648
+ promptId = item.prompt_id ?? item.promptId
649
+ number = item.number
650
+ }
651
+ if (promptId === undefined || promptId === null || promptId === '') continue
652
+ const entry = { prompt_id: String(promptId) }
653
+ if (number !== undefined) entry.number = number
654
+ entry.promptId = entry.prompt_id // 兼容别名(契约 §2 用 snake_case)
655
+ out.push(entry)
656
+ }
657
+ return out
658
+ }
659
+
660
+ /** GET /queue -> { running: [{ prompt_id }], pending: [{ prompt_id }] } */
661
+ export async function getQueue(baseUrl, { timeoutMs = 10000 } = {}) {
662
+ const res = await request(baseUrl, '/queue', { timeoutMs })
663
+ const json = res.json && typeof res.json === 'object' ? res.json : {}
664
+ return {
665
+ running: normalizeQueueList(json.queue_running ?? json.running),
666
+ pending: normalizeQueueList(json.queue_pending ?? json.pending),
667
+ }
668
+ }
669
+
670
+ /** POST /interrupt { prompt_id? } -> { ok:true } */
671
+ export async function interrupt(baseUrl, promptId) {
672
+ const body = promptId === undefined || promptId === null || promptId === ''
673
+ ? {}
674
+ : { prompt_id: String(promptId) }
675
+ await request(baseUrl, '/interrupt', { method: 'POST', body, timeoutMs: 10000 })
676
+ return { ok: true }
677
+ }
678
+
679
+ /** POST /queue { delete: [...ids] } -> { ok:true } */
680
+ export async function deleteQueued(baseUrl, promptIds) {
681
+ const ids = Array.isArray(promptIds) ? promptIds : [promptIds]
682
+ await request(baseUrl, '/queue', {
683
+ method: 'POST',
684
+ body: { delete: ids.filter((id) => id !== undefined && id !== null).map(String) },
685
+ timeoutMs: 10000,
686
+ })
687
+ return { ok: true }
688
+ }
689
+
690
+ /** POST /queue { clear:true } -> { ok:true } */
691
+ export async function clearQueue(baseUrl) {
692
+ await request(baseUrl, '/queue', { method: 'POST', body: { clear: true }, timeoutMs: 10000 })
693
+ return { ok: true }
694
+ }
695
+
696
+ // ---------------------------------------------------------------------------
697
+ // /view、/upload/image
698
+ // ---------------------------------------------------------------------------
699
+
700
+ /** GET /view?filename=&subfolder=&type= -> { buffer: Buffer, contentType } */
701
+ export async function fetchImage(baseUrl, { filename, subfolder = '', type = 'output' } = {}, { timeoutMs = 60000 } = {}) {
702
+ const base = normalizeBaseUrl(baseUrl)
703
+ if (!filename || typeof filename !== 'string') {
704
+ throw new ComfyError('fetchImage 需要 filename', { code: 'EINVALID_ARG' })
705
+ }
706
+ const query = new URLSearchParams({
707
+ filename: String(filename),
708
+ subfolder: String(subfolder ?? ''),
709
+ type: String(type ?? 'output'),
710
+ })
711
+ const res = await rawFetch(`${base}/view?${query.toString()}`, { method: 'GET', timeoutMs })
712
+ if (!res.ok) {
713
+ let detail = ''
714
+ try {
715
+ detail = (await res.text()).slice(0, 500)
716
+ } catch {
717
+ detail = ''
718
+ }
719
+ throw new ComfyError(`下载图片失败:HTTP ${res.status}${detail ? `(${detail})` : ''}`, {
720
+ code: 'EHTTP',
721
+ status: res.status,
722
+ detail,
723
+ })
724
+ }
725
+ const buffer = Buffer.from(await res.arrayBuffer())
726
+ return {
727
+ buffer,
728
+ contentType: res.headers.get('content-type') || 'application/octet-stream',
729
+ }
730
+ }
731
+
732
+ function guessMime(filename) {
733
+ const lower = String(filename || '').toLowerCase()
734
+ if (lower.endsWith('.png')) return 'image/png'
735
+ if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) return 'image/jpeg'
736
+ if (lower.endsWith('.webp')) return 'image/webp'
737
+ if (lower.endsWith('.gif')) return 'image/gif'
738
+ return 'application/octet-stream'
739
+ }
740
+
741
+ /**
742
+ * 上传图片到 ComfyUI input 目录。
743
+ * data: Buffer | Uint8Array;POST /upload/image multipart。
744
+ * -> { name, subfolder, type };失败抛 ComfyError。
745
+ */
746
+ export async function uploadImage(baseUrl, { data, filename, subfolder = '', type = 'input' } = {}, { timeoutMs = 120000 } = {}) {
747
+ const base = normalizeBaseUrl(baseUrl)
748
+ if (!data) throw new ComfyError('uploadImage 需要 data(Buffer/Uint8Array)', { code: 'EINVALID_ARG' })
749
+ const name = typeof filename === 'string' && filename ? filename : 'image.png'
750
+ const bytes = Buffer.isBuffer(data) ? data : new Uint8Array(data)
751
+ const form = new FormData()
752
+ form.append('image', new Blob([bytes], { type: guessMime(name) }), name)
753
+ if (subfolder) form.append('subfolder', String(subfolder))
754
+ form.append('type', String(type ?? 'input'))
755
+
756
+ const res = await rawFetch(`${base}/upload/image`, { method: 'POST', body: form, timeoutMs })
757
+ let text = ''
758
+ try {
759
+ text = await res.text()
760
+ } catch {
761
+ text = ''
762
+ }
763
+ let json
764
+ if (text) {
765
+ try {
766
+ json = JSON.parse(text)
767
+ } catch {
768
+ json = undefined
769
+ }
770
+ }
771
+ if (!res.ok) {
772
+ const detail = extractDetail(json, text)
773
+ throw new ComfyError(`上传图片失败:HTTP ${res.status}${detail ? `(${detail})` : ''}`, {
774
+ code: 'EHTTP',
775
+ status: res.status,
776
+ detail,
777
+ json,
778
+ })
779
+ }
780
+ const body = json && typeof json === 'object' ? json : {}
781
+ return {
782
+ name: String(body.name ?? body.filename ?? name),
783
+ subfolder: String(body.subfolder ?? subfolder ?? ''),
784
+ type: String(body.type ?? type ?? 'input'),
785
+ }
786
+ }
787
+
788
+ // ---------------------------------------------------------------------------
789
+ // /userdata(服务器侧工作流)
790
+ // ---------------------------------------------------------------------------
791
+
792
+ function parseUserdataList(json) {
793
+ let raw
794
+ if (Array.isArray(json)) {
795
+ raw = json
796
+ } else if (json && typeof json === 'object') {
797
+ for (const key of ['items', 'files', 'workflows', 'data']) {
798
+ if (Array.isArray(json[key])) {
799
+ raw = json[key]
800
+ break
801
+ }
802
+ }
803
+ if (!raw) {
804
+ // { "path/name.json": { size, modified } } 形式
805
+ raw = Object.entries(json).map(([key, value]) => (
806
+ value && typeof value === 'object' ? { path: key, ...value } : { path: key }
807
+ ))
808
+ }
809
+ }
810
+ if (!Array.isArray(raw)) {
811
+ throw new ComfyError('ComfyUI /userdata 返回格式无法识别', { code: 'EBAD_RESPONSE' })
812
+ }
813
+
814
+ const items = []
815
+ const seen = new Set()
816
+ for (const entry of raw) {
817
+ let pathValue
818
+ let size
819
+ let modified
820
+ if (typeof entry === 'string') {
821
+ pathValue = entry
822
+ } else if (entry && typeof entry === 'object') {
823
+ pathValue = entry.path ?? entry.name ?? entry.file ?? entry.filename
824
+ size = entry.size ?? entry.bytes
825
+ modified = entry.modified ?? entry.mtime ?? entry.updatedAt
826
+ }
827
+ if (typeof pathValue !== 'string') continue
828
+ const relPath = pathValue.trim().replace(/^\/+/, '')
829
+ if (!relPath || !/\.json$/i.test(relPath)) continue
830
+ if (seen.has(relPath)) continue
831
+ seen.add(relPath)
832
+ const baseName = relPath.split('/').pop() || relPath
833
+ const item = { path: relPath, name: baseName.replace(/\.json$/i, '') }
834
+ const sizeNumber = Number(size)
835
+ if (Number.isFinite(sizeNumber) && sizeNumber >= 0) item.size = sizeNumber
836
+ if (typeof modified === 'string' || typeof modified === 'number') item.modified = modified
837
+ items.push(item)
838
+ }
839
+ return items
840
+ }
841
+
842
+ /**
843
+ * 列出服务器侧(ComfyUI userdata)工作流。
844
+ * -> { ok:true, items:[{ path, name, size?, modified? }] } | { ok:false, error }
845
+ * 任何失败(404 / 网络 / 格式不符)都返回 ok:false,不抛。
846
+ */
847
+ export async function listUserdataWorkflows(baseUrl, { timeoutMs = 8000 } = {}) {
848
+ let normalized
849
+ try {
850
+ normalized = normalizeBaseUrl(baseUrl)
851
+ } catch (err) {
852
+ return { ok: false, items: [], error: humanError(err) }
853
+ }
854
+ try {
855
+ const res = await request(normalized, '/userdata?dir=workflows&recurse=true&split=false', { timeoutMs })
856
+ const items = parseUserdataList(res.json)
857
+ return { ok: true, items }
858
+ } catch (err) {
859
+ return { ok: false, items: [], error: humanError(err) }
860
+ }
861
+ }
862
+
863
+ /**
864
+ * 读取服务器侧工作流内容(解析后的 JSON 对象)。
865
+ *
866
+ * ⚠️ ComfyUI 的读取接口与列表接口语义不同(app/user_manager.py 实测):
867
+ * - 列表:GET /userdata?dir=workflows&recurse=true&split=false → 文件名相对 workflows/
868
+ * - 读取:GET /userdata/{file},其中 file 是**相对 user 根目录**的路径(要带 `workflows/` 前缀),
869
+ * 且 aiohttp 的 `{file}` 不匹配 `/`,所以整条相对路径必须整体 encodeURIComponent(`/` → `%2F`)。
870
+ * 例如:GET /userdata/workflows%2Fdefault.json
871
+ * 之前少了前缀、还多余地带 ?dir=workflows,会对所有文件 404(用户报的「导入没反应」根因)。
872
+ */
873
+ /** gzip 头长度(处理 FEXTRA/FNAME/FCOMMENT/FHCRC 这些可选字段)。 */
874
+ function gzipHeaderLength(buffer) {
875
+ if (buffer.length < 10) return buffer.length
876
+ let offset = 10
877
+ const flags = buffer[3]
878
+ if (flags & 0x04) {
879
+ if (offset + 2 > buffer.length) return buffer.length
880
+ offset += 2 + buffer.readUInt16LE(offset)
881
+ }
882
+ if (flags & 0x08) {
883
+ while (offset < buffer.length && buffer[offset] !== 0) offset += 1
884
+ offset += 1
885
+ }
886
+ if (flags & 0x10) {
887
+ while (offset < buffer.length && buffer[offset] !== 0) offset += 1
888
+ offset += 1
889
+ }
890
+ if (flags & 0x02) offset += 2
891
+ return Math.min(offset, buffer.length)
892
+ }
893
+
894
+ /**
895
+ * 解码 userdata 里的工作流内容:
896
+ * - 正常情况是明文 JSON;
897
+ * - 少数 ComfyUI 目录里的文件是 gzip(甚至「gzip 前缀 + 明文后缀」的半损坏 gzip,
898
+ * 例如 "▶flux-2-klein-图生图洗图流.json"),这里尽力还原成完整 JSON。
899
+ */
900
+ async function decodeWorkflowBuffer(buffer) {
901
+ if (!(buffer.length >= 2 && buffer[0] === 0x1f && buffer[1] === 0x8b)) return buffer
902
+ try {
903
+ return gunzipSync(buffer)
904
+ } catch {
905
+ // 继续尝试容错解析
906
+ }
907
+ const headerLength = gzipHeaderLength(buffer)
908
+ const inflater = createInflateRaw({ finishFlush: zlibConstants.Z_SYNC_FLUSH })
909
+ const chunks = []
910
+ try {
911
+ for await (const chunk of Readable.from(buffer.subarray(headerLength)).pipe(inflater)) {
912
+ chunks.push(Buffer.from(chunk))
913
+ }
914
+ } catch {
915
+ // 尾部不是合法 deflate:保留已经解出的部分,后面再拼明文后缀
916
+ }
917
+ const decoded = Buffer.concat(chunks)
918
+ const consumed = Number(inflater.bytesWritten) || 0
919
+ if (decoded.length === 0 || consumed === 0) {
920
+ throw new ComfyError('ComfyUI 返回的工作流是 gzip 且无法解压', { code: 'EBAD_RESPONSE' })
921
+ }
922
+ // 先看解出的部分是不是完整 JSON(有些文件是「完整 gzip 工作流 + 明文垃圾尾巴」)
923
+ try {
924
+ JSON.parse(decoded.toString('utf8').replace(/^\uFEFF/, ''))
925
+ return decoded
926
+ } catch {
927
+ // 继续尝试拼回明文后缀
928
+ }
929
+ // deflate 结束后还有 8 字节 gzip 尾部(CRC32 + ISIZE),其余部分当作明文后缀拼回去
930
+ const suffixStart = headerLength + consumed + 8
931
+ const candidate = Buffer.concat([decoded, buffer.subarray(Math.min(suffixStart, buffer.length))])
932
+ try {
933
+ JSON.parse(candidate.toString('utf8').replace(/^\uFEFF/, ''))
934
+ } catch {
935
+ throw new ComfyError('ComfyUI 返回的工作流既不是合法 gzip 也不是合法 JSON', { code: 'EBAD_RESPONSE' })
936
+ }
937
+ return candidate
938
+ }
939
+
940
+ export async function getUserdataWorkflow(baseUrl, path, { timeoutMs = 15000 } = {}) {
941
+ const base = normalizeBaseUrl(baseUrl)
942
+ if (!path || typeof path !== 'string') {
943
+ throw new ComfyError('getUserdataWorkflow 需要 path', { code: 'EINVALID_ARG' })
944
+ }
945
+ const clean = path.trim().replace(/^\/+/, '')
946
+ const relative = /^workflows\//i.test(clean) ? clean : `workflows/${clean}`
947
+ // ⚠️ ComfyUI 的 user_manager 会对 match_info 里含 '%' 的值再做一次 unquote;
948
+ // 所以先把 encodeURIComponent 结果中的 '%' 再转义一层(% → %25),
949
+ // 否则文件名里字面带 %20 的工作流(如 "Character%20Studio...")会 404。
950
+ const encoded = encodeURIComponent(relative).replace(/%/g, '%25')
951
+ const res = await request(base, `/userdata/${encoded}`, { timeoutMs })
952
+ let buffer = res.buffer || Buffer.alloc(0)
953
+ // 有些 ComfyUI 用户目录里的工作流是 gzip(或半损坏 gzip),统一走容错解码
954
+ buffer = await decodeWorkflowBuffer(buffer)
955
+ let parsed
956
+ try {
957
+ parsed = JSON.parse(buffer.toString('utf8').replace(/^\uFEFF/, ''))
958
+ } catch {
959
+ parsed = undefined
960
+ }
961
+ if (parsed === undefined || parsed === null) {
962
+ throw new ComfyError('ComfyUI 工作流内容为空或不是 JSON', {
963
+ code: 'EBAD_RESPONSE',
964
+ detail: clean,
965
+ })
966
+ }
967
+ return parsed
968
+ }