@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,441 @@
1
+ /**
2
+ * Comfy API v2 transport and the workflow runner shared by the SDK-backed
3
+ * ComfyUI nodes.
4
+ *
5
+ * A {@link ComfyTransport} is the only thing that differs between Comfy
6
+ * surfaces: Comfy Cloud gets {@link cloudTransport}, and any other v2 surface
7
+ * at a known base URL gets {@link v2Transport}. {@link runComfyWorkflow} takes one, plus
8
+ * an API-format prompt and the node's dynamic inputs, and yields the same
9
+ * frames every ComfyUI node in this package yields — one per output file on
10
+ * `"<comfyNodeId>:<kind>"`, then a final `output` frame.
11
+ *
12
+ * The structural `ComfyJob` / `ComfyOutput` / `ComfyRunEvent` types mirror the
13
+ * `@comfyorg/sdk` surface this module uses. The compile-time assignability
14
+ * checks at the bottom of the type block pin that surface, so a breaking bump
15
+ * of the (0.1.x) SDK fails `tsc` here instead of at run time.
16
+ */
17
+ import { Buffer } from "node:buffer";
18
+ import { randomUUID } from "node:crypto";
19
+ import { Asset, AssetFactory, Comfy, ComfyError, Job, QueueFull, WorkflowFormatUi } from "@comfyorg/sdk";
20
+ import { ApiError, ComfyLow } from "@comfyorg/sdk/low";
21
+ import { loadMediaRefBytes } from "@nodetool-ai/runtime";
22
+ /** Media kind → default filename extension / mime for uploads. */
23
+ export const UPLOAD_DEFAULTS = {
24
+ image: { ext: "png", mime: "image/png" },
25
+ audio: { ext: "wav", mime: "audio/wav" },
26
+ video: { ext: "mp4", mime: "video/mp4" }
27
+ };
28
+ /** A connected media ref looks like an object carrying uri/data/asset_id. */
29
+ export function isMediaRef(value) {
30
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
31
+ return false;
32
+ }
33
+ const v = value;
34
+ return ("uri" in v || "data" in v || "asset_id" in v || typeof v.type === "string");
35
+ }
36
+ export function extFromUri(uri) {
37
+ if (!uri)
38
+ return undefined;
39
+ const clean = uri.split("?")[0].split("#")[0];
40
+ const ext = clean.split(".").pop();
41
+ return ext && ext.length <= 5 && /^[a-z0-9]+$/i.test(ext)
42
+ ? ext.toLowerCase()
43
+ : undefined;
44
+ }
45
+ /** Filename + content type to upload a connected media ref under. */
46
+ export function uploadNaming(nodeId, field, value) {
47
+ const fallback = UPLOAD_DEFAULTS[value.type ?? "image"] ?? UPLOAD_DEFAULTS.image;
48
+ const ext = extFromUri(value.uri) ?? fallback.ext;
49
+ return {
50
+ filename: `nodetool_${nodeId}_${field}.${ext}`,
51
+ contentType: fallback.mime
52
+ };
53
+ }
54
+ /** Comfy Cloud, authenticated with a `COMFY_API_KEY`. */
55
+ export function cloudTransport(apiKey) {
56
+ const client = new Comfy({ apiKey });
57
+ return {
58
+ async submit(graph, options) {
59
+ const workflow = client.workflows.fromJson(graph);
60
+ return client.submit(workflow, {
61
+ signal: options.signal,
62
+ apiKey: options.apiKey
63
+ });
64
+ },
65
+ assetFromBytes: (bytes, filename, contentType) => client.assets.fromBytes(bytes, { filename, contentType })
66
+ };
67
+ }
68
+ // How long a full queue is retried before submit gives up, and the pause used
69
+ // for a `queue_full` a server sent without a `Retry-After` header.
70
+ const QUEUE_RETRY_BUDGET_MS = 60_000;
71
+ const DEFAULT_RETRY_AFTER_S = 2;
72
+ /** UI-export JSON carries all three of these top-level keys; API format never does. */
73
+ const UI_FORMAT_KEYS = ["nodes", "links", "last_node_id"];
74
+ /**
75
+ * Validate and canonicalize a caller-supplied Comfy API v2 base URL.
76
+ *
77
+ * `ComfyLow` builds every request URL by appending `/api/v2/<path>` to this
78
+ * string, so a query or fragment would land in the middle of the path and a
79
+ * trailing slash would double the separator. Same rule the SDK applies to
80
+ * `COMFY_BASE_URL` in `resolveBaseUrl`, which is the only base URL it accepts.
81
+ */
82
+ function normalizeBaseUrl(baseUrl) {
83
+ const raw = baseUrl.trim();
84
+ let parsed;
85
+ try {
86
+ parsed = new URL(raw);
87
+ }
88
+ catch {
89
+ parsed = undefined;
90
+ }
91
+ const valid = parsed !== undefined &&
92
+ (parsed.protocol === "http:" || parsed.protocol === "https:") &&
93
+ parsed.search === "" &&
94
+ parsed.hash === "";
95
+ if (!valid) {
96
+ throw new TypeError("Comfy base URL must be an http(s) URL with no query or fragment " +
97
+ `(e.g. "http://127.0.0.1:8189"), got ${JSON.stringify(baseUrl)}`);
98
+ }
99
+ return stripTrailingSlashes(raw);
100
+ }
101
+ /** Drop every trailing `/` without a regex that backtracks on long runs. */
102
+ export function stripTrailingSlashes(value) {
103
+ let end = value.length;
104
+ while (end > 0 && value[end - 1] === "/")
105
+ end--;
106
+ return value.slice(0, end);
107
+ }
108
+ /** `setTimeout` sleep that rejects as soon as `signal` aborts. */
109
+ function abortableSleep(ms, signal) {
110
+ const canceled = () => abortError("Comfy submit was canceled");
111
+ if (signal?.aborted) {
112
+ return Promise.reject(canceled());
113
+ }
114
+ return new Promise((resolve, reject) => {
115
+ const onAbort = () => {
116
+ clearTimeout(timer);
117
+ reject(canceled());
118
+ };
119
+ const timer = setTimeout(() => {
120
+ signal?.removeEventListener("abort", onAbort);
121
+ resolve();
122
+ }, ms);
123
+ signal?.addEventListener("abort", onAbort, { once: true });
124
+ });
125
+ }
126
+ /**
127
+ * Replace every `Asset` handle sitting on a node input with the `core/ASSET`
128
+ * reference the server understands, uploading its bytes on first use.
129
+ *
130
+ * Copies the nodes and their `inputs` maps rather than writing through, so the
131
+ * caller's graph is left as it was. The high-level client does this with
132
+ * `findAssetHandles`/`substituteAssetHandles`, which `@comfyorg/sdk` keeps
133
+ * private to `sdk/core.js`.
134
+ */
135
+ async function materializeAssets(graph, signal) {
136
+ const materialized = {};
137
+ for (const [nodeId, node] of Object.entries(graph)) {
138
+ const inputs = node === null ? undefined : node.inputs;
139
+ if (typeof inputs !== "object" || inputs === null) {
140
+ materialized[nodeId] = node;
141
+ continue;
142
+ }
143
+ const substituted = {};
144
+ for (const [field, value] of Object.entries(inputs)) {
145
+ substituted[field] =
146
+ value instanceof Asset ? await value.asReference(signal) : value;
147
+ }
148
+ materialized[nodeId] = { ...node, inputs: substituted };
149
+ }
150
+ return materialized;
151
+ }
152
+ /**
153
+ * Any Comfy API v2 surface at a caller-supplied base URL — a
154
+ * `comfy-api-proxy` in front of a local ComfyUI, a NodeTool worker, or a
155
+ * ComfyUI that serves v2 itself.
156
+ *
157
+ * The high-level `Comfy` client cannot target one: it reads `COMFY_BASE_URL`
158
+ * from the environment per construction, which is process-global and races
159
+ * across concurrent node runs. So this builds `ComfyLow` directly and
160
+ * reimplements the one thing `Comfy` keeps private — the submit loop: guard
161
+ * UI-format JSON, materialize asset handles, mint an idempotency key, and
162
+ * retry a 429 against a 60 second budget with the same key. Collapses to
163
+ * `new Comfy({ apiKey, baseUrl })` once upstream accepts a `baseUrl` option
164
+ * (spec D3), and the loop below is deleted with it.
165
+ *
166
+ * `options.fetch` is handed to `ComfyLow` verbatim; tests script the wire with
167
+ * it, and production passes nothing.
168
+ */
169
+ export function v2Transport(baseUrl, apiKey, options) {
170
+ const low = new ComfyLow(normalizeBaseUrl(baseUrl), apiKey, {
171
+ fetch: options?.fetch
172
+ });
173
+ const assets = new AssetFactory(low);
174
+ return {
175
+ async submit(graph, submitOptions) {
176
+ if (UI_FORMAT_KEYS.every((key) => key in graph)) {
177
+ throw new WorkflowFormatUi("workflow is in UI-export format (nodes/links/last_node_id); " +
178
+ "submit the API-format graph instead", { code: "workflow_format_ui", httpStatus: 422 });
179
+ }
180
+ const { signal } = submitOptions;
181
+ const workflow = await materializeAssets(graph, signal);
182
+ // One key for the whole loop: a retry must not create a second job.
183
+ const idempotencyKey = randomUUID();
184
+ const extraData = submitOptions.apiKey
185
+ ? { api_key_comfy_org: submitOptions.apiKey }
186
+ : undefined;
187
+ const deadline = performance.now() + QUEUE_RETRY_BUDGET_MS;
188
+ for (;;) {
189
+ try {
190
+ return new Job(low, await low.postJobs(workflow, {
191
+ idempotencyKey,
192
+ extraData,
193
+ signal
194
+ }));
195
+ }
196
+ catch (err) {
197
+ if (!(err instanceof ApiError))
198
+ throw err;
199
+ // Any 429 carrying Retry-After is backpressure; a `queue_full`
200
+ // without one gets the default pause, since servers omit it today.
201
+ const retryAfterS = err.retryAfter ??
202
+ (err.code === "queue_full" ? DEFAULT_RETRY_AFTER_S : null);
203
+ // Clamp to what is left of the budget, so a hostile Retry-After
204
+ // (86400s) cannot sleep past it — the loop-entry check bounds when
205
+ // the next attempt starts, not how long this sleep runs.
206
+ const remainingMs = deadline - performance.now();
207
+ if (err.httpStatus === 429 && retryAfterS !== null && remainingMs > 0) {
208
+ await abortableSleep(Math.min(retryAfterS * 1000, remainingMs), signal);
209
+ continue;
210
+ }
211
+ throw err;
212
+ }
213
+ }
214
+ },
215
+ assetFromBytes: (bytes, filename, contentType) => assets.fromBytes(bytes, { filename, contentType })
216
+ };
217
+ }
218
+ const TERMINAL_STATUSES = new Set([
219
+ "succeeded",
220
+ "canceled",
221
+ "failed",
222
+ "expired"
223
+ ]);
224
+ function abortError(message) {
225
+ const error = new Error(message);
226
+ error.name = "AbortError";
227
+ return error;
228
+ }
229
+ /** Turn an SDK error into a message a workflow author can act on. */
230
+ export function describeComfyError(err) {
231
+ // The high-level client throws `ComfyError` subclasses and `v2Transport`
232
+ // surfaces the low layer's `ApiError`s. Both carry the same `code` and
233
+ // `httpStatus`, so the mapping keys on those rather than on the class.
234
+ if (!(err instanceof ComfyError) && !(err instanceof ApiError)) {
235
+ return err instanceof Error ? err : new Error(String(err));
236
+ }
237
+ if (err.code === "queue_full") {
238
+ const retryAfter = err instanceof QueueFull || err instanceof ApiError
239
+ ? err.retryAfter
240
+ : null;
241
+ const wait = retryAfter === null ? "" : ` Retry after ${retryAfter}s.`;
242
+ return new Error(`Comfy queue is full: ${err.message}${wait}`);
243
+ }
244
+ if (err.code === "workflow_format_ui") {
245
+ return new Error("ComfyUI workflow is in UI-export format. Save it with " +
246
+ "Workflow → Export (API) and paste the API-format JSON instead.");
247
+ }
248
+ if (err.code === "insufficient_credits" || err.httpStatus === 402) {
249
+ return new Error(`Comfy account has insufficient credits: ${err.message}`);
250
+ }
251
+ return err;
252
+ }
253
+ function jobFailure(job) {
254
+ const error = job.error;
255
+ if (!error) {
256
+ return new Error(`Comfy job ${job.id} failed`);
257
+ }
258
+ const where = error.class_type
259
+ ? ` in ${error.class_type} (#${error.node_id ?? "?"})`
260
+ : error.node_id
261
+ ? ` in node #${error.node_id}`
262
+ : "";
263
+ return new Error(`Comfy job ${job.id} failed${where}: ${error.message} [${error.code}]`);
264
+ }
265
+ /** Map one finished output onto its dynamic slot name and frame value. */
266
+ async function outputFrame(output, signal) {
267
+ // Signed output URLs expire, so the bytes are pulled during the run.
268
+ const bytes = await output.toBytes({ signal });
269
+ const slot = `${output.nodeId}:${output.type}`;
270
+ if (output.type === "text") {
271
+ return { [slot]: Buffer.from(bytes).toString("utf-8") };
272
+ }
273
+ const kind = output.type === "image" || output.type === "audio" || output.type === "video"
274
+ ? output.type
275
+ : "document";
276
+ return {
277
+ [slot]: {
278
+ type: kind,
279
+ uri: "",
280
+ data: Buffer.from(bytes).toString("base64"),
281
+ mimeType: output.contentType
282
+ }
283
+ };
284
+ }
285
+ /**
286
+ * Submit `prompt` through `transport` and stream what it produces.
287
+ *
288
+ * Yields one frame per output file, keyed `"<comfyNodeId>:<kind>"`, as each
289
+ * arrives, then a final `{ output }` frame describing the finished job.
290
+ * Throws on a `failed` job (with the node-level detail), on cancellation, and
291
+ * on the SDK errors an author can act on (queue full, insufficient credits,
292
+ * UI-format workflow).
293
+ */
294
+ export async function* runComfyWorkflow(transport, prompt, dynamicProps, options) {
295
+ const { signal, context, nodeId, nodeName } = options;
296
+ const logLine = (content, severity = "info") => {
297
+ context?.postMessage({
298
+ type: "log_update",
299
+ node_id: nodeId,
300
+ node_name: nodeName,
301
+ content,
302
+ severity
303
+ });
304
+ };
305
+ // Deep clone so injected inputs never mutate the stored workflow prop.
306
+ const graph = JSON.parse(JSON.stringify(prompt));
307
+ for (const [handle, value] of dynamicProps) {
308
+ if (value === undefined || value === null)
309
+ continue;
310
+ const sep = handle.indexOf(":");
311
+ if (sep <= 0)
312
+ continue;
313
+ const comfyNodeId = handle.slice(0, sep);
314
+ const field = handle.slice(sep + 1);
315
+ const target = graph[comfyNodeId];
316
+ if (!target || typeof target.inputs !== "object" || target.inputs === null) {
317
+ continue;
318
+ }
319
+ if (isMediaRef(value)) {
320
+ const bytes = await loadMediaRefBytes(value, context);
321
+ if (!bytes)
322
+ continue;
323
+ const { filename, contentType } = uploadNaming(comfyNodeId, field, value);
324
+ target.inputs[field] = transport.assetFromBytes(bytes, filename, contentType);
325
+ }
326
+ else {
327
+ target.inputs[field] = value;
328
+ }
329
+ }
330
+ logLine(`Submitting ComfyUI workflow (${Object.keys(graph).length} nodes)`);
331
+ let job;
332
+ try {
333
+ job = await transport.submit(graph, { signal, apiKey: options.apiKey });
334
+ }
335
+ catch (err) {
336
+ throw describeComfyError(err);
337
+ }
338
+ logLine(`Comfy job ${job.id} submitted`);
339
+ // The abort signal cancels the job server-side, not just this generator.
340
+ const onAbort = () => {
341
+ void job.cancel().catch(() => {
342
+ // Best-effort: a job that already finished stays in its terminal state.
343
+ });
344
+ };
345
+ if (signal.aborted) {
346
+ onAbort();
347
+ }
348
+ else {
349
+ signal.addEventListener("abort", onAbort, { once: true });
350
+ }
351
+ let terminalStatus = null;
352
+ let fileCount = 0;
353
+ try {
354
+ for await (const event of job.events(signal)) {
355
+ switch (event.kind) {
356
+ case "progress": {
357
+ const [progress, total] = event.step !== null && event.steps !== null && event.steps > 0
358
+ ? [event.step, event.steps]
359
+ : event.nodesTotal !== null && event.nodesTotal > 0
360
+ ? [event.value * event.nodesTotal, event.nodesTotal]
361
+ : [event.value, 1];
362
+ context?.postMessage({
363
+ type: "node_progress",
364
+ node_id: nodeId,
365
+ progress,
366
+ total
367
+ });
368
+ break;
369
+ }
370
+ case "log":
371
+ logLine(event.message, event.level === "error"
372
+ ? "error"
373
+ : event.level === "warning"
374
+ ? "warning"
375
+ : "info");
376
+ break;
377
+ case "statusChange":
378
+ logLine(event.queuePosition === null
379
+ ? `Status: ${event.status}`
380
+ : `Status: ${event.status} (queue position ${event.queuePosition})`);
381
+ if (TERMINAL_STATUSES.has(event.status)) {
382
+ terminalStatus = event.status;
383
+ }
384
+ break;
385
+ case "preview":
386
+ // Nothing downstream consumes preview bitmaps today, so they are
387
+ // logged rather than emitted on a slot no consumer declares.
388
+ if (options.previews) {
389
+ logLine(`Preview from #${event.nodeId} (${event.data.length} bytes, ${event.contentType})`);
390
+ }
391
+ break;
392
+ case "outputReady": {
393
+ fileCount += 1;
394
+ logLine(`Output from #${event.output.nodeId} (${event.output.name}, ${event.output.contentType})`);
395
+ yield await outputFrame(event.output, signal);
396
+ break;
397
+ }
398
+ }
399
+ }
400
+ }
401
+ catch (err) {
402
+ if (signal.aborted) {
403
+ throw abortError(`Comfy job ${job.id} was canceled`);
404
+ }
405
+ throw describeComfyError(err);
406
+ }
407
+ finally {
408
+ signal.removeEventListener("abort", onAbort);
409
+ }
410
+ // `events()` never writes the job model, and a deployment without live SSE
411
+ // ends the stream with no terminal frame at all — so pull the authoritative
412
+ // status, outputs and error before deciding what happened.
413
+ await job.refresh(signal);
414
+ const status = TERMINAL_STATUSES.has(job.status)
415
+ ? job.status
416
+ : (terminalStatus ?? job.status);
417
+ if (status === "canceled" || status === "canceling") {
418
+ throw abortError(`Comfy job ${job.id} was canceled`);
419
+ }
420
+ if (status !== "succeeded") {
421
+ const error = status === "failed" ? jobFailure(job) : new Error(`Comfy job ${job.id} ended ${status}`);
422
+ logLine(error.message, "error");
423
+ throw error;
424
+ }
425
+ logLine(`Comfy job ${job.id} completed (${fileCount} file${fileCount === 1 ? "" : "s"})`);
426
+ yield {
427
+ output: {
428
+ job_id: job.id,
429
+ status,
430
+ outputs: job.outputs.map((output) => ({
431
+ node_id: output.nodeId,
432
+ name: output.name,
433
+ type: output.type,
434
+ content_type: output.contentType,
435
+ size_bytes: output.sizeBytes,
436
+ asset_id: output.id
437
+ }))
438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EF,MAAM;QACJ,MAAM,EAAE;YACN,MAAM,EAAE,GAAG,CAAC,EAAE;YACd,MAAM;YACN,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;gBACpC,OAAO,EAAE,MAAM,CAAC,MAAM;gBACtB,IAAI,EAAE,MAAM,CAAC,IAAI;gBACjB,IAAI,EAAE,MAAM,CAAC,IAAI;gBACjB,YAAY,EAAE,MAAM,CAAC,WAAW;gBAChC,UAAU,EAAE,MAAM,CAAC,SAAS;gBAC5B,QAAQ,EAAE,MAAM,CAAC,EAAE;aACpB,CAAC,CAAC;SACJ;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,140 @@
1
+ import { BaseNode } from "@nodetool-ai/node-sdk";
2
+ import { type PythonBridge, type ProcessingContext } from "@nodetool-ai/runtime";
3
+ import { ComfyCloudWorkflowNode } from "./comfy-cloud.js";
4
+ import { type ComfyPrompt, type ComfyTransport } from "./comfy-sdk.js";
5
+ /**
6
+ * Turn a worker WebSocket URL into the HTTP origin its API v2 routes live on:
7
+ * `ws:` becomes `http:`, `wss:` becomes `https:`, and path and query are
8
+ * dropped (`wss://abc-7777.proxy.runpod.net/ws` →
9
+ * `https://abc-7777.proxy.runpod.net`).
10
+ */
11
+ export declare function workerHttpOrigin(workerUrl: string): string;
12
+ /**
13
+ * Run a ComfyUI workflow on any ComfyUI server, with typed inputs/outputs
14
+ * derived from the workflow.
15
+ *
16
+ * The workflow is supplied in ComfyUI's API ("prompt") format — a map of
17
+ * node id to `{ class_type, inputs }`. The web UI loads a workflow (paste or
18
+ * drop a `.json`/`.png`) and exposes its `Load*` nodes as typed inputs and
19
+ * `Save*` nodes as streaming outputs. Dynamic input handles are keyed
20
+ * `"<comfyNodeId>:<field>"`; connected values are injected into the prompt
21
+ * before submission (assets are uploaded to the ComfyUI server first).
22
+ *
23
+ * Outputs stream: this is a streaming-output node, so each save node's media
24
+ * is emitted on a per-node slot keyed `"<comfyNodeId>:image|audio|video"` the
25
+ * moment that node finishes — one item per file, so batches naturally produce
26
+ * multiple outputs. A final `output` slot carries the raw ComfyUI history.
27
+ *
28
+ * Two APIs, selected by the `api` prop. `native` (the default) speaks
29
+ * ComfyUI's own `/prompt` plus WebSocket protocol. `v2` speaks Comfy API v2
30
+ * against `endpoint` as an HTTP origin, for a ComfyUI behind `comfy-api-proxy`
31
+ * (port 8189) or a ComfyUI that serves `/api/v2` itself; its final `output`
32
+ * slot carries the job manifest instead of ComfyUI history.
33
+ */
34
+ export declare class ComfyWorkflowNode extends BaseNode {
35
+ static readonly nodeType = "lib.comfy.RunWorkflow";
36
+ static readonly title = "Run ComfyUI Workflow";
37
+ static readonly 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";
38
+ static readonly supportsDynamicInputs = true;
39
+ static readonly supportsDynamicOutputs = true;
40
+ static readonly metadataOutputTypes: {
41
+ output: string;
42
+ };
43
+ endpoint: string;
44
+ api: "native" | "v2";
45
+ workflow: string | ComfyPrompt;
46
+ timeout: number;
47
+ /**
48
+ * Build the Comfy API v2 transport for the `v2` API. Split out so tests can
49
+ * inject a fake without a v2 server, the way {@link ComfyWorkerWorkflowNode}
50
+ * splits out `connectBridge`.
51
+ */
52
+ protected createTransport(baseUrl: string): ComfyTransport;
53
+ /**
54
+ * Parse the `workflow` prop into a ComfyUI prompt object. The prop holds a
55
+ * JSON string (API prompt format); a raw object is also accepted for
56
+ * backward compatibility with previously-saved graphs.
57
+ */
58
+ private parseWorkflow;
59
+ /**
60
+ * Inject a single dynamic input value into the prompt at
61
+ * `prompt[nodeId].inputs[field]`, uploading media refs to the ComfyUI server
62
+ * and substituting the stored filename.
63
+ */
64
+ private injectInput;
65
+ /** Build a single NodeTool media ref from one downloaded ComfyUI file. */
66
+ private fileToRef;
67
+ /**
68
+ * Buffered fallback for non-streaming consumers: drain the streaming output
69
+ * and merge frames into a single record (slots with multiple files collapse
70
+ * to an array).
71
+ */
72
+ process(context?: ProcessingContext): Promise<Record<string, unknown>>;
73
+ genProcess(context?: ProcessingContext): AsyncGenerator<Record<string, unknown>>;
74
+ }
75
+ /**
76
+ * Run a ComfyUI workflow on a NodeTool worker that fronts a co-located,
77
+ * loopback-only ComfyUI server (the `nodetool-worker-comfy` image). ComfyUI
78
+ * itself is never exposed outside the worker.
79
+ *
80
+ * Two paths, chosen by what the connected worker reports on
81
+ * `worker.status.comfy`. The bridge is connected either way, because it is how
82
+ * that status is read.
83
+ *
84
+ * - **API v2** (`comfy.api_v2: true`): the bridge is closed again and the
85
+ * workflow runs over the worker's Comfy API v2 routes, on the HTTP origin
86
+ * derived from `worker_url` and behind the same bearer token. Media inputs
87
+ * are uploaded as v2 assets. Outputs stream: each file is emitted the moment
88
+ * it lands, on a per-node slot keyed `"<comfyNodeId>:image|audio|video|
89
+ * text|file"`, and the final `output` slot carries the job manifest.
90
+ * - **Bridge** (every worker image that predates v2): the node calls
91
+ * `comfy.execute` over the WebSocket bridge. Input media is sent as bridge
92
+ * blobs referenced from the workflow JSON via `"blob:<key>"` placeholders;
93
+ * the worker uploads them to ComfyUI before submitting. Generated files come
94
+ * back as output blobs, emitted as typed media refs (kind sniffed from the
95
+ * bytes) on their blob-key slots, plus a static `output` slot carrying the
96
+ * raw ComfyUI outputs — all in one final frame, since the bridge call is
97
+ * buffered.
98
+ */
99
+ export declare class ComfyWorkerWorkflowNode extends BaseNode {
100
+ static readonly nodeType = "lib.comfy.RunWorkflowOnWorker";
101
+ static readonly title = "Run ComfyUI Workflow (Worker)";
102
+ static readonly 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";
103
+ static readonly supportsDynamicInputs = true;
104
+ static readonly supportsDynamicOutputs = true;
105
+ static readonly metadataOutputTypes: {
106
+ output: string;
107
+ };
108
+ worker_url: string;
109
+ worker_token: string;
110
+ workflow: string | ComfyPrompt;
111
+ timeout: number;
112
+ previews: boolean;
113
+ /**
114
+ * Connect a bridge to the worker. Split out so tests can inject a fake
115
+ * bridge without standing up a real WebSocket worker.
116
+ */
117
+ protected connectBridge(): Promise<PythonBridge>;
118
+ /**
119
+ * Build the Comfy API v2 transport for a worker that serves it. Split out
120
+ * alongside {@link connectBridge} so tests can inject a fake without a
121
+ * v2-capable worker.
122
+ */
123
+ protected createTransport(baseUrl: string, token?: string): ComfyTransport;
124
+ private parseWorkflow;
125
+ /**
126
+ * Buffered fallback for non-streaming consumers: drain the streaming output
127
+ * and merge frames into a single record (slots with multiple files collapse
128
+ * to an array).
129
+ */
130
+ process(context?: ProcessingContext): Promise<Record<string, unknown>>;
131
+ genProcess(context?: ProcessingContext): AsyncGenerator<Record<string, unknown>>;
132
+ /**
133
+ * The `comfy.execute` bridge path, for a worker image that does not serve
134
+ * API v2. Buffered: the worker returns every output blob at once, so this
135
+ * resolves to the single frame `genProcess` yields.
136
+ */
137
+ private runOverBridge;
138
+ }
139
+ export declare const COMFY_NODES: (typeof ComfyCloudWorkflowNode | typeof ComfyWorkflowNode | typeof ComfyWorkerWorkflowNode)[];
140
+ //# sourceMappingURL=comfy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"comfy.d.ts","sourceRoot":"","sources":["../../src/nodes/comfy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAQ,MAAM,uBAAuB,CAAC;AAEvD,OAAO,EAKL,KAAK,YAAY,EAGjB,KAAK,iBAAiB,EAIvB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAOL,KAAK,WAAW,EAChB,KAAK,cAAc,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