@nodetool-ai/integration-nodes 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,723 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { BaseNode, prop } from "@nodetool-ai/node-sdk";
8
+ import { tagAsServer } from "@nodetool-ai/nodes-utils";
9
+ import { executeComfy, uploadComfyFile, loadMediaRefBytes, WebsocketPythonBridge } from "@nodetool-ai/runtime";
10
+ import { ComfyCloudWorkflowNode } from "./comfy-cloud.js";
11
+ import { extFromUri, isMediaRef, runComfyWorkflow, stripTrailingSlashes, UPLOAD_DEFAULTS, v2Transport } from "./comfy-sdk.js";
12
+ /**
13
+ * Turn a user-supplied server address into an http(s) base URL: a bare
14
+ * `host:port` gets `http://`, and trailing slashes are dropped. Mirrors
15
+ * `normalizeBaseUrl` in the native executor so both APIs read the same prop
16
+ * the same way.
17
+ */
18
+ function httpBaseUrl(address) {
19
+ const withScheme = /^https?:\/\//i.test(address)
20
+ ? address
21
+ : `http://${address}`;
22
+ return stripTrailingSlashes(withScheme);
23
+ }
24
+ /**
25
+ * Turn a worker WebSocket URL into the HTTP origin its API v2 routes live on:
26
+ * `ws:` becomes `http:`, `wss:` becomes `https:`, and path and query are
27
+ * dropped (`wss://abc-7777.proxy.runpod.net/ws` →
28
+ * `https://abc-7777.proxy.runpod.net`).
29
+ */
30
+ export function workerHttpOrigin(workerUrl) {
31
+ const address = workerUrl.trim();
32
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(address)
33
+ ? address
34
+ : `ws://${address}`;
35
+ let url;
36
+ try {
37
+ url = new URL(withScheme);
38
+ }
39
+ catch {
40
+ throw new Error(`Worker URL is not a valid URL: ${workerUrl}`);
41
+ }
42
+ if (url.protocol === "ws:")
43
+ url.protocol = "http:";
44
+ else if (url.protocol === "wss:")
45
+ url.protocol = "https:";
46
+ return url.origin;
47
+ }
48
+ /**
49
+ * Run one prompt over a Comfy API v2 transport, enforcing the node's `timeout`
50
+ * prop with a signal the way the Comfy Cloud node does, and reporting a
51
+ * timeout as a timeout rather than as a bare abort.
52
+ */
53
+ async function* streamComfyV2(transport, prompt, dynamicProps, options) {
54
+ const { context, timeoutSeconds } = options;
55
+ const timeoutSignal = AbortSignal.timeout(timeoutSeconds * 1000);
56
+ const signal = context?.signal
57
+ ? AbortSignal.any([context.signal, timeoutSignal])
58
+ : timeoutSignal;
59
+ try {
60
+ yield* runComfyWorkflow(transport, prompt, dynamicProps, {
61
+ signal,
62
+ context,
63
+ nodeId: options.nodeId,
64
+ nodeName: options.nodeName,
65
+ previews: options.previews
66
+ });
67
+ }
68
+ catch (err) {
69
+ if (timeoutSignal.aborted) {
70
+ throw new Error(`ComfyUI workflow did not finish within ${timeoutSeconds}s`);
71
+ }
72
+ throw err;
73
+ }
74
+ }
75
+ /**
76
+ * Run a ComfyUI workflow on any ComfyUI server, with typed inputs/outputs
77
+ * derived from the workflow.
78
+ *
79
+ * The workflow is supplied in ComfyUI's API ("prompt") format — a map of
80
+ * node id to `{ class_type, inputs }`. The web UI loads a workflow (paste or
81
+ * drop a `.json`/`.png`) and exposes its `Load*` nodes as typed inputs and
82
+ * `Save*` nodes as streaming outputs. Dynamic input handles are keyed
83
+ * `"<comfyNodeId>:<field>"`; connected values are injected into the prompt
84
+ * before submission (assets are uploaded to the ComfyUI server first).
85
+ *
86
+ * Outputs stream: this is a streaming-output node, so each save node's media
87
+ * is emitted on a per-node slot keyed `"<comfyNodeId>:image|audio|video"` the
88
+ * moment that node finishes — one item per file, so batches naturally produce
89
+ * multiple outputs. A final `output` slot carries the raw ComfyUI history.
90
+ *
91
+ * Two APIs, selected by the `api` prop. `native` (the default) speaks
92
+ * ComfyUI's own `/prompt` plus WebSocket protocol. `v2` speaks Comfy API v2
93
+ * against `endpoint` as an HTTP origin, for a ComfyUI behind `comfy-api-proxy`
94
+ * (port 8189) or a ComfyUI that serves `/api/v2` itself; its final `output`
95
+ * slot carries the job manifest instead of ComfyUI history.
96
+ */
97
+ export class ComfyWorkflowNode extends BaseNode {
98
+ static nodeType = "lib.comfy.RunWorkflow";
99
+ static title = "Run ComfyUI Workflow";
100
+ static description = "Run a ComfyUI workflow on a ComfyUI server.\n comfy, comfyui, workflow, image, diffusion\n\n Use cases:\n - Generate images with an existing ComfyUI workflow\n - Call a local or remote ComfyUI server (RunPod, etc.)\n - Embed ComfyUI generation inside a NodeTool workflow";
101
+ static supportsDynamicInputs = true;
102
+ static supportsDynamicOutputs = true;
103
+ static metadataOutputTypes = {
104
+ output: "dict[str, any]"
105
+ };
106
+ /**
107
+ * Build the Comfy API v2 transport for the `v2` API. Split out so tests can
108
+ * inject a fake without a v2 server, the way {@link ComfyWorkerWorkflowNode}
109
+ * splits out `connectBridge`.
110
+ */
111
+ createTransport(baseUrl) {
112
+ return v2Transport(baseUrl);
113
+ }
114
+ /**
115
+ * Parse the `workflow` prop into a ComfyUI prompt object. The prop holds a
116
+ * JSON string (API prompt format); a raw object is also accepted for
117
+ * backward compatibility with previously-saved graphs.
118
+ */
119
+ parseWorkflow(value) {
120
+ let parsed = value;
121
+ if (typeof value === "string") {
122
+ const trimmed = value.trim();
123
+ if (!trimmed)
124
+ return {};
125
+ try {
126
+ parsed = JSON.parse(trimmed);
127
+ }
128
+ catch (err) {
129
+ throw new Error(`ComfyUI workflow is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
130
+ }
131
+ }
132
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
133
+ return {};
134
+ }
135
+ return parsed;
136
+ }
137
+ /**
138
+ * Inject a single dynamic input value into the prompt at
139
+ * `prompt[nodeId].inputs[field]`, uploading media refs to the ComfyUI server
140
+ * and substituting the stored filename.
141
+ */
142
+ async injectInput(prompt, endpoint, handle, value, context) {
143
+ const sep = handle.indexOf(":");
144
+ if (sep <= 0)
145
+ return;
146
+ const nodeId = handle.slice(0, sep);
147
+ const field = handle.slice(sep + 1);
148
+ const node = prompt[nodeId];
149
+ if (!node || typeof node.inputs !== "object" || node.inputs === null) {
150
+ return;
151
+ }
152
+ if (isMediaRef(value)) {
153
+ const bytes = await loadMediaRefBytes(value, context);
154
+ if (!bytes)
155
+ return;
156
+ const kind = value.type ?? "image";
157
+ const fallback = UPLOAD_DEFAULTS[kind] ?? UPLOAD_DEFAULTS.image;
158
+ const ext = extFromUri(value.uri) ?? fallback.ext;
159
+ const filename = `nodetool_${nodeId}_${field}.${ext}`;
160
+ const stored = await uploadComfyFile(endpoint, bytes, filename, fallback.mime);
161
+ node.inputs[field] = stored;
162
+ return;
163
+ }
164
+ node.inputs[field] = value;
165
+ }
166
+ /** Build a single NodeTool media ref from one downloaded ComfyUI file. */
167
+ fileToRef(kind, file) {
168
+ return { type: kind, uri: "", data: file.data, mimeType: file.mimeType };
169
+ }
170
+ /**
171
+ * Buffered fallback for non-streaming consumers: drain the streaming output
172
+ * and merge frames into a single record (slots with multiple files collapse
173
+ * to an array).
174
+ */
175
+ async process(context) {
176
+ const merged = {};
177
+ for await (const frame of this.genProcess(context)) {
178
+ for (const [key, value] of Object.entries(frame)) {
179
+ if (key in merged) {
180
+ const prev = merged[key];
181
+ merged[key] = Array.isArray(prev) ? [...prev, value] : [prev, value];
182
+ }
183
+ else {
184
+ merged[key] = value;
185
+ }
186
+ }
187
+ }
188
+ return merged;
189
+ }
190
+ async *genProcess(context) {
191
+ const endpoint = this.endpoint.trim();
192
+ if (!endpoint) {
193
+ throw new Error("ComfyUI endpoint is required");
194
+ }
195
+ const source = this.parseWorkflow(this.workflow);
196
+ if (Object.keys(source).length === 0) {
197
+ throw new Error("ComfyUI workflow is required (API prompt format: { nodeId: { class_type, inputs } })");
198
+ }
199
+ if (this.api === "v2") {
200
+ yield* streamComfyV2(this.createTransport(httpBaseUrl(endpoint)), source, this.dynamicProps, {
201
+ timeoutSeconds: Math.max(1, this.timeout),
202
+ nodeId: this.__node_id,
203
+ nodeName: this.__node_name ?? "Run ComfyUI Workflow",
204
+ context
205
+ });
206
+ return;
207
+ }
208
+ // Deep clone so injected inputs never mutate the stored workflow prop.
209
+ const prompt = JSON.parse(JSON.stringify(source));
210
+ // Inject dynamic inputs (connected assets + exposed scalar params).
211
+ for (const [handle, value] of this.dynamicProps) {
212
+ if (value === undefined || value === null)
213
+ continue;
214
+ await this.injectInput(prompt, endpoint, handle, value, context);
215
+ }
216
+ const timeoutMs = Math.max(1, this.timeout) * 1000;
217
+ const nodeCount = Object.keys(prompt).length;
218
+ const nodeId = this.__node_id;
219
+ const nodeName = this.__node_name ?? "Run ComfyUI Workflow";
220
+ const logLine = (content, severity = "info") => {
221
+ context?.postMessage({
222
+ type: "log_update",
223
+ node_id: nodeId,
224
+ node_name: nodeName,
225
+ content,
226
+ severity
227
+ });
228
+ };
229
+ logLine(`Running ComfyUI workflow (${nodeCount} nodes) on ${endpoint}`);
230
+ const onProgress = (event) => {
231
+ switch (event.type) {
232
+ case "execution_start":
233
+ logLine("Execution started");
234
+ break;
235
+ case "execution_cached":
236
+ if (event.cached_nodes?.length) {
237
+ logLine(`Reused cache for ${event.cached_nodes.length} node(s)`);
238
+ }
239
+ break;
240
+ case "executing":
241
+ if (event.node) {
242
+ const cls = prompt[event.node]?.class_type ?? event.node;
243
+ logLine(`Executing ${cls} (#${event.node})`);
244
+ }
245
+ break;
246
+ case "progress":
247
+ if (typeof event.progress === "number" &&
248
+ typeof event.total === "number" &&
249
+ event.total > 0) {
250
+ context?.postMessage({
251
+ type: "node_progress",
252
+ node_id: nodeId,
253
+ progress: event.progress,
254
+ total: event.total
255
+ });
256
+ }
257
+ break;
258
+ case "execution_error":
259
+ logLine(`ComfyUI error: ${event.error ?? "unknown"}`, "error");
260
+ break;
261
+ default:
262
+ break;
263
+ }
264
+ };
265
+ // Bridge the executor's onNodeOutput WS callback into this generator: each
266
+ // downloaded file becomes one queued frame that we yield to its node slot.
267
+ const queue = [];
268
+ let notify = null;
269
+ const wake = () => {
270
+ const fn = notify;
271
+ notify = null;
272
+ fn?.();
273
+ };
274
+ let fileCount = 0;
275
+ const onNodeOutput = (cnId, outs) => {
276
+ const groups = [
277
+ ["image", outs.images ?? []],
278
+ ["audio", outs.audio ?? []],
279
+ ["video", outs.video ?? []]
280
+ ];
281
+ for (const [kind, files] of groups) {
282
+ for (const file of files) {
283
+ fileCount += 1;
284
+ queue.push({ [`${cnId}:${kind}`]: this.fileToRef(kind, file) });
285
+ }
286
+ }
287
+ if (queue.length > 0) {
288
+ logLine(`Output from #${cnId}`);
289
+ wake();
290
+ }
291
+ };
292
+ let settledResult = null;
293
+ const { result, cancel } = executeComfy(prompt, endpoint, onProgress, timeoutMs, onNodeOutput);
294
+ // Run-level cancellation: interrupt ComfyUI (POST /interrupt + WS close)
295
+ // rather than merely discarding the result, and wake the drain loop so it
296
+ // does not block on a notify that will never come.
297
+ const signal = context?.signal;
298
+ const onAbort = () => {
299
+ cancel();
300
+ wake();
301
+ };
302
+ if (signal) {
303
+ if (signal.aborted) {
304
+ onAbort();
305
+ }
306
+ else {
307
+ signal.addEventListener("abort", onAbort, { once: true });
308
+ }
309
+ }
310
+ const done = result.then((r) => {
311
+ settledResult = r;
312
+ wake();
313
+ }, (err) => {
314
+ settledResult = {
315
+ status: "failed",
316
+ error: err instanceof Error ? err.message : String(err)
317
+ };
318
+ wake();
319
+ });
320
+ // Drain streamed outputs as they arrive, until execution settles.
321
+ try {
322
+ while (settledResult === null || queue.length > 0) {
323
+ if (queue.length === 0) {
324
+ // An abort that the executor has not yet turned into a result must
325
+ // not park this loop on a notify nobody will fire.
326
+ if (signal?.aborted)
327
+ break;
328
+ await new Promise((resolve) => {
329
+ notify = resolve;
330
+ });
331
+ continue;
332
+ }
333
+ yield queue.shift();
334
+ }
335
+ }
336
+ finally {
337
+ signal?.removeEventListener("abort", onAbort);
338
+ }
339
+ if (settledResult === null) {
340
+ const aborted = new Error("ComfyUI execution was canceled");
341
+ aborted.name = "AbortError";
342
+ logLine(aborted.message, "error");
343
+ throw aborted;
344
+ }
345
+ await done;
346
+ const res = settledResult;
347
+ if (res.status !== "completed") {
348
+ logLine(res.error ?? "ComfyUI execution failed", "error");
349
+ throw new Error(res.error ?? "ComfyUI execution failed");
350
+ }
351
+ logLine(`ComfyUI workflow completed (${fileCount} file${fileCount === 1 ? "" : "s"})`);
352
+ // Final frame: raw ComfyUI history on the static `output` slot.
353
+ yield { output: res.raw_output ?? {} };
354
+ }
355
+ }
356
+ __decorate([
357
+ prop({
358
+ type: "str",
359
+ default: "127.0.0.1:8188",
360
+ title: "Endpoint",
361
+ description: "ComfyUI server address, e.g. 127.0.0.1:8188 or http://host:8188.",
362
+ required: true
363
+ })
364
+ ], ComfyWorkflowNode.prototype, "endpoint", void 0);
365
+ __decorate([
366
+ prop({
367
+ type: "enum",
368
+ default: "native",
369
+ title: "API",
370
+ description: "Which API to speak. `native` speaks ComfyUI's own /prompt and WebSocket protocol; `v2` speaks Comfy API v2 for a server behind comfy-api-proxy (port 8189) or a ComfyUI that serves /api/v2.",
371
+ values: ["native", "v2"]
372
+ })
373
+ ], ComfyWorkflowNode.prototype, "api", void 0);
374
+ __decorate([
375
+ prop({
376
+ type: "str",
377
+ default: "",
378
+ title: "Workflow",
379
+ description: "ComfyUI workflow in API (prompt) format, as a JSON string: a map of node id to { class_type, inputs }.",
380
+ required: true
381
+ })
382
+ ], ComfyWorkflowNode.prototype, "workflow", void 0);
383
+ __decorate([
384
+ prop({
385
+ type: "int",
386
+ default: 600,
387
+ title: "Timeout",
388
+ description: "Maximum seconds to wait for the workflow to finish.",
389
+ min: 1
390
+ })
391
+ ], ComfyWorkflowNode.prototype, "timeout", void 0);
392
+ /** Sniff a media kind + mime from the leading bytes of a ComfyUI output blob. */
393
+ function sniffMedia(bytes) {
394
+ const b = bytes;
395
+ // PNG
396
+ if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) {
397
+ return { kind: "image", mime: "image/png" };
398
+ }
399
+ // JPEG
400
+ if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) {
401
+ return { kind: "image", mime: "image/jpeg" };
402
+ }
403
+ // GIF
404
+ if (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) {
405
+ return { kind: "image", mime: "image/gif" };
406
+ }
407
+ // RIFF container — disambiguate by the form type in bytes 8-11. RIFF is
408
+ // generic (WEBP, WAVE, AVI, …), so only classify on an exact form match and
409
+ // fall through otherwise rather than assuming WebP.
410
+ if (b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46) {
411
+ // "WEBP"
412
+ if (b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) {
413
+ return { kind: "image", mime: "image/webp" };
414
+ }
415
+ // "WAVE"
416
+ if (b[8] === 0x57 && b[9] === 0x41 && b[10] === 0x56 && b[11] === 0x45) {
417
+ return { kind: "audio", mime: "audio/wav" };
418
+ }
419
+ // "AVI "
420
+ if (b[8] === 0x41 && b[9] === 0x56 && b[10] === 0x49 && b[11] === 0x20) {
421
+ return { kind: "video", mime: "video/x-msvideo" };
422
+ }
423
+ }
424
+ // ftyp box → MP4/MOV
425
+ if (b[4] === 0x66 && b[5] === 0x74 && b[6] === 0x79 && b[7] === 0x70) {
426
+ return { kind: "video", mime: "video/mp4" };
427
+ }
428
+ // OGG
429
+ if (b[0] === 0x4f && b[1] === 0x67 && b[2] === 0x67 && b[3] === 0x53) {
430
+ return { kind: "audio", mime: "audio/ogg" };
431
+ }
432
+ // ID3 / MPEG audio
433
+ if (b[0] === 0x49 && b[1] === 0x44 && b[2] === 0x33) {
434
+ return { kind: "audio", mime: "audio/mpeg" };
435
+ }
436
+ return { kind: "image", mime: "image/png" };
437
+ }
438
+ /**
439
+ * Run a ComfyUI workflow on a NodeTool worker that fronts a co-located,
440
+ * loopback-only ComfyUI server (the `nodetool-worker-comfy` image). ComfyUI
441
+ * itself is never exposed outside the worker.
442
+ *
443
+ * Two paths, chosen by what the connected worker reports on
444
+ * `worker.status.comfy`. The bridge is connected either way, because it is how
445
+ * that status is read.
446
+ *
447
+ * - **API v2** (`comfy.api_v2: true`): the bridge is closed again and the
448
+ * workflow runs over the worker's Comfy API v2 routes, on the HTTP origin
449
+ * derived from `worker_url` and behind the same bearer token. Media inputs
450
+ * are uploaded as v2 assets. Outputs stream: each file is emitted the moment
451
+ * it lands, on a per-node slot keyed `"<comfyNodeId>:image|audio|video|
452
+ * text|file"`, and the final `output` slot carries the job manifest.
453
+ * - **Bridge** (every worker image that predates v2): the node calls
454
+ * `comfy.execute` over the WebSocket bridge. Input media is sent as bridge
455
+ * blobs referenced from the workflow JSON via `"blob:<key>"` placeholders;
456
+ * the worker uploads them to ComfyUI before submitting. Generated files come
457
+ * back as output blobs, emitted as typed media refs (kind sniffed from the
458
+ * bytes) on their blob-key slots, plus a static `output` slot carrying the
459
+ * raw ComfyUI outputs — all in one final frame, since the bridge call is
460
+ * buffered.
461
+ */
462
+ export class ComfyWorkerWorkflowNode extends BaseNode {
463
+ static nodeType = "lib.comfy.RunWorkflowOnWorker";
464
+ static title = "Run ComfyUI Workflow (Worker)";
465
+ static description = "Run a ComfyUI workflow on a NodeTool worker (nodetool-worker-comfy) over the worker bridge.\n comfy, comfyui, workflow, worker, runpod, diffusion\n\n Use cases:\n - Run ComfyUI on a remote GPU worker without exposing ComfyUI directly\n - Drive a RunPod ComfyUI worker from inside a NodeTool workflow";
466
+ static supportsDynamicInputs = true;
467
+ static supportsDynamicOutputs = true;
468
+ static metadataOutputTypes = {
469
+ output: "dict[str, any]"
470
+ };
471
+ /**
472
+ * Connect a bridge to the worker. Split out so tests can inject a fake
473
+ * bridge without standing up a real WebSocket worker.
474
+ */
475
+ async connectBridge() {
476
+ const url = this.worker_url.trim();
477
+ const token = this.worker_token.trim();
478
+ const bridge = new WebsocketPythonBridge({
479
+ wsUrl: url,
480
+ workerToken: token || undefined,
481
+ // One-shot per node run — never keep reconnecting after we close.
482
+ autoRestart: false
483
+ });
484
+ await bridge.connect();
485
+ return bridge;
486
+ }
487
+ /**
488
+ * Build the Comfy API v2 transport for a worker that serves it. Split out
489
+ * alongside {@link connectBridge} so tests can inject a fake without a
490
+ * v2-capable worker.
491
+ */
492
+ createTransport(baseUrl, token) {
493
+ return v2Transport(baseUrl, token);
494
+ }
495
+ parseWorkflow(value) {
496
+ let parsed = value;
497
+ if (typeof value === "string") {
498
+ const trimmed = value.trim();
499
+ if (!trimmed)
500
+ return {};
501
+ try {
502
+ parsed = JSON.parse(trimmed);
503
+ }
504
+ catch (err) {
505
+ throw new Error(`ComfyUI workflow is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
506
+ }
507
+ }
508
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
509
+ return {};
510
+ }
511
+ return parsed;
512
+ }
513
+ /**
514
+ * Buffered fallback for non-streaming consumers: drain the streaming output
515
+ * and merge frames into a single record (slots with multiple files collapse
516
+ * to an array).
517
+ */
518
+ async process(context) {
519
+ const merged = {};
520
+ for await (const frame of this.genProcess(context)) {
521
+ for (const [key, value] of Object.entries(frame)) {
522
+ if (key in merged) {
523
+ const prev = merged[key];
524
+ merged[key] = Array.isArray(prev) ? [...prev, value] : [prev, value];
525
+ }
526
+ else {
527
+ merged[key] = value;
528
+ }
529
+ }
530
+ }
531
+ return merged;
532
+ }
533
+ async *genProcess(context) {
534
+ const url = this.worker_url.trim();
535
+ if (!url) {
536
+ throw new Error("Worker URL is required");
537
+ }
538
+ const source = this.parseWorkflow(this.workflow);
539
+ if (Object.keys(source).length === 0) {
540
+ throw new Error("ComfyUI workflow is required (API prompt format: { nodeId: { class_type, inputs } })");
541
+ }
542
+ const bridge = await this.connectBridge();
543
+ // The bridge is how we learn which path this worker supports. A worker
544
+ // serving API v2 is then driven over HTTP, so the bridge is closed again.
545
+ if (bridge.getComfyStatus()?.api_v2 === true) {
546
+ bridge.close();
547
+ const token = this.worker_token.trim();
548
+ yield* streamComfyV2(this.createTransport(workerHttpOrigin(url), token || undefined), source, this.dynamicProps, {
549
+ timeoutSeconds: Math.max(1, this.timeout),
550
+ nodeId: this.__node_id,
551
+ nodeName: this.__node_name ?? "Run ComfyUI Workflow (Worker)",
552
+ context,
553
+ previews: this.previews
554
+ });
555
+ return;
556
+ }
557
+ yield await this.runOverBridge(bridge, source, url, context);
558
+ }
559
+ /**
560
+ * The `comfy.execute` bridge path, for a worker image that does not serve
561
+ * API v2. Buffered: the worker returns every output blob at once, so this
562
+ * resolves to the single frame `genProcess` yields.
563
+ */
564
+ async runOverBridge(bridge, source, url, context) {
565
+ // Deep clone so injected inputs never mutate the stored workflow prop.
566
+ const prompt = JSON.parse(JSON.stringify(source));
567
+ // Inject dynamic inputs. Media refs are sent as bridge blobs referenced
568
+ // from the workflow via "blob:<key>" placeholders; scalars go in directly.
569
+ const blobs = {};
570
+ for (const [handle, value] of this.dynamicProps) {
571
+ if (value === undefined || value === null)
572
+ continue;
573
+ const sep = handle.indexOf(":");
574
+ if (sep <= 0)
575
+ continue;
576
+ const nodeId = handle.slice(0, sep);
577
+ const field = handle.slice(sep + 1);
578
+ const node = prompt[nodeId];
579
+ if (!node || typeof node.inputs !== "object" || node.inputs === null) {
580
+ continue;
581
+ }
582
+ if (isMediaRef(value)) {
583
+ const bytes = await loadMediaRefBytes(value, context);
584
+ if (!bytes)
585
+ continue;
586
+ const key = `${nodeId}_${field}`;
587
+ blobs[key] = bytes;
588
+ node.inputs[field] = `blob:${key}`;
589
+ }
590
+ else {
591
+ node.inputs[field] = value;
592
+ }
593
+ }
594
+ const nodeId = this.__node_id;
595
+ const nodeName = this.__node_name ?? "Run ComfyUI Workflow (Worker)";
596
+ const logLine = (content, severity = "info") => {
597
+ context?.postMessage({
598
+ type: "log_update",
599
+ node_id: nodeId,
600
+ node_name: nodeName,
601
+ content,
602
+ severity
603
+ });
604
+ };
605
+ const onEvent = (event) => {
606
+ switch (event.event) {
607
+ case "started":
608
+ logLine("Execution started");
609
+ break;
610
+ case "cached":
611
+ if (event.nodes?.length) {
612
+ logLine(`Reused cache for ${event.nodes.length} node(s)`);
613
+ }
614
+ break;
615
+ case "executing":
616
+ if (event.node) {
617
+ const cls = prompt[event.node]?.class_type ?? event.node;
618
+ logLine(`Executing ${cls} (#${event.node})`);
619
+ }
620
+ break;
621
+ case "progress":
622
+ if (typeof event.value === "number" &&
623
+ typeof event.max === "number" &&
624
+ event.max > 0) {
625
+ context?.postMessage({
626
+ type: "node_progress",
627
+ node_id: nodeId,
628
+ progress: event.value,
629
+ total: event.max
630
+ });
631
+ }
632
+ break;
633
+ default:
634
+ break;
635
+ }
636
+ };
637
+ let result;
638
+ try {
639
+ if (!bridge.supportsComfy()) {
640
+ throw new Error("The connected worker does not front a ComfyUI server " +
641
+ "(worker.status.comfy.enabled is not set). Deploy the " +
642
+ "nodetool-worker-comfy image.");
643
+ }
644
+ const nodeCount = Object.keys(prompt).length;
645
+ logLine(`Running ComfyUI workflow (${nodeCount} nodes) on ${url}`);
646
+ result = await bridge.comfyExecute(prompt, {
647
+ blobs: Object.keys(blobs).length > 0 ? blobs : undefined,
648
+ previews: this.previews,
649
+ timeout: Math.max(1, this.timeout)
650
+ }, onEvent);
651
+ }
652
+ finally {
653
+ bridge.close();
654
+ }
655
+ const outputs = {};
656
+ const resultBlobs = result.blobs ?? {};
657
+ let fileCount = 0;
658
+ for (const [key, bytes] of Object.entries(resultBlobs)) {
659
+ if (!(bytes instanceof Uint8Array))
660
+ continue;
661
+ const { kind, mime } = sniffMedia(bytes);
662
+ fileCount += 1;
663
+ outputs[key] = {
664
+ type: kind,
665
+ uri: "",
666
+ data: Buffer.from(bytes).toString("base64"),
667
+ mimeType: mime
668
+ };
669
+ }
670
+ logLine(`ComfyUI workflow completed (${fileCount} file${fileCount === 1 ? "" : "s"})`);
671
+ outputs.output = result.outputs ?? {};
672
+ return outputs;
673
+ }
674
+ }
675
+ __decorate([
676
+ prop({
677
+ type: "str",
678
+ default: "ws://127.0.0.1:7777/ws",
679
+ title: "Worker URL",
680
+ description: "WebSocket URL of the NodeTool worker fronting ComfyUI, e.g. ws://host:7777/ws.",
681
+ required: true
682
+ })
683
+ ], ComfyWorkerWorkflowNode.prototype, "worker_url", void 0);
684
+ __decorate([
685
+ prop({
686
+ type: "str",
687
+ default: "",
688
+ title: "Worker Token",
689
+ description: "Bearer token for the worker, if it requires authentication."
690
+ })
691
+ ], ComfyWorkerWorkflowNode.prototype, "worker_token", void 0);
692
+ __decorate([
693
+ prop({
694
+ type: "str",
695
+ default: "",
696
+ title: "Workflow",
697
+ description: "ComfyUI workflow in API (prompt) format, as a JSON string: a map of node id to { class_type, inputs }.",
698
+ required: true
699
+ })
700
+ ], ComfyWorkerWorkflowNode.prototype, "workflow", void 0);
701
+ __decorate([
702
+ prop({
703
+ type: "int",
704
+ default: 600,
705
+ title: "Timeout",
706
+ description: "Maximum seconds to wait for the workflow to finish.",
707
+ min: 1
708
+ })
709
+ ], ComfyWorkerWorkflowNode.prototype, "timeout", void 0);
710
+ __decorate([
711
+ prop({
712
+ type: "bool",
713
+ default: false,
714
+ title: "Previews",
715
+ description: "Stream ComfyUI preview images while the workflow runs."
716
+ })
717
+ ], ComfyWorkerWorkflowNode.prototype, "previews", void 0);
718
+ export const COMFY_NODES = tagAsServer([
719
+ ComfyWorkflowNode,
720
+ ComfyWorkerWorkflowNode,
721
+ ComfyCloudWorkflowNode
722
+ ]);
723
+ //# sourceMappingURL=comfy.js.map