comfyui-node 1.4.3 → 1.4.4
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/LICENSE +1 -1
- package/dist/.tsbuildinfo +1 -1
- package/dist/call-wrapper.d.ts +124 -124
- package/dist/call-wrapper.js +1 -1
- package/dist/call-wrapper.js.map +1 -1
- package/dist/client.d.ts +290 -290
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/pool/WorkflowPool.d.ts +80 -0
- package/dist/pool/WorkflowPool.d.ts.map +1 -1
- package/dist/pool/WorkflowPool.js +147 -2
- package/dist/pool/WorkflowPool.js.map +1 -1
- package/dist/pool/failover/SmartFailoverStrategy.js +1 -1
- package/dist/pool/failover/SmartFailoverStrategy.js.map +1 -1
- package/dist/pool/index.d.ts +1 -0
- package/dist/pool/index.d.ts.map +1 -1
- package/dist/pool/profiling/JobProfiler.d.ts +130 -0
- package/dist/pool/profiling/JobProfiler.d.ts.map +1 -0
- package/dist/pool/profiling/JobProfiler.js +225 -0
- package/dist/pool/profiling/JobProfiler.js.map +1 -0
- package/dist/pool/queue/QueueAdapter.d.ts +30 -30
- package/dist/pool/queue/adapters/memory.d.ts +20 -20
- package/dist/pool/types/job.d.ts +3 -0
- package/dist/pool/types/job.d.ts.map +1 -1
- package/dist/pool.d.ts +180 -180
- package/dist/workflow.js +1 -1
- package/dist/workflow.js.map +1 -1
- package/package.json +1 -1
- package/README.OLD.md +0 -1395
package/README.OLD.md
DELETED
|
@@ -1,1395 +0,0 @@
|
|
|
1
|
-
# ComfyUI SDK
|
|
2
|
-
|
|
3
|
-
[](https://www.npmjs.com/package/comfyui-node)
|
|
4
|
-
[](https://github.com/igorls/comfyui-node/blob/main/LICENSE)
|
|
5
|
-

|
|
6
|
-

|
|
7
|
-

|
|
8
|
-
|
|
9
|
-
TypeScript SDK for interacting with the [ComfyUI](https://github.com/comfyanonymous/ComfyUI) API – focused on workflow construction, prompt execution orchestration, multi‑instance scheduling and extension integration.
|
|
10
|
-
|
|
11
|
-
> 1.0 is a complete redesign around modular feature namespaces (`api.ext.*`) and stronger typing. All legacy instance methods have been removed – see Migration section if upgrading.
|
|
12
|
-
|
|
13
|
-
## Contents
|
|
14
|
-
|
|
15
|
-
- [Features](#features)
|
|
16
|
-
- [Installation](#installation)
|
|
17
|
-
- [Cheat Sheet](#cheat-sheet)
|
|
18
|
-
- [Recent Enhancements (Ergonomics & Typing)](#recent-enhancements-ergonomics--typing)
|
|
19
|
-
- [High‑Level Workflow API (Experimental) – Quick Intro](#highlevel-workflow-api-experimental--quick-intro)
|
|
20
|
-
- [Choosing: Workflow vs PromptBuilder](#choosing-workflow-vs-promptbuilder)
|
|
21
|
-
- [Result Object Anatomy](#result-object-anatomy)
|
|
22
|
-
- [Multi-Instance Pool](#multi-instance-pool)
|
|
23
|
-
- [Authentication](#authentication)
|
|
24
|
-
- [Custom WebSocket](#custom-websocket)
|
|
25
|
-
- [Modular Features (`api.ext`)](#modular-features-apiext)
|
|
26
|
-
- [Events](#events)
|
|
27
|
-
- [Preview Metadata](#preview-metadata)
|
|
28
|
-
- [API Nodes (Comfy.org paid)](#api-nodes-comfyorg-paid)
|
|
29
|
-
- [Image Inputs: Attach Files (DX)](#image-inputs-attach-files-dx)
|
|
30
|
-
- [1.0 Migration](#10-migration)
|
|
31
|
-
- [Reference Overview](#reference-overview)
|
|
32
|
-
- [Examples](#examples)
|
|
33
|
-
- [Errors & Diagnostics](#errors--diagnostics)
|
|
34
|
-
- [Troubleshooting](#troubleshooting)
|
|
35
|
-
- [Published Smoke Test](#published-smoke-test)
|
|
36
|
-
- [Contributing](#contributing)
|
|
37
|
-
- [License](#license)
|
|
38
|
-
|
|
39
|
-
## Features
|
|
40
|
-
|
|
41
|
-
- Fully typed TypeScript surface
|
|
42
|
-
- Fluent `PromptBuilder` for graph mutation & input/output mapping
|
|
43
|
-
- Fluent `PromptBuilder` for graph mutation & input/output mapping (with validation & JSON (de)serialization helpers)
|
|
44
|
-
- WebSocket events (progress, preview, output, completion) with reconnection & HTTP polling fallback
|
|
45
|
-
- Weighted multi‑instance job distribution (`ComfyPool`)
|
|
46
|
-
- Extension integration (Manager, Crystools monitor, feature flags)
|
|
47
|
-
- Modular feature namespaces (`api.ext.queue`, `api.ext.node`, etc.)
|
|
48
|
-
- Upload helpers (images, masks) & user data file operations
|
|
49
|
-
- Authentication strategies (basic, bearer token, custom headers)
|
|
50
|
-
- Structured errors & narrow fetch helper
|
|
51
|
-
- Validation utilities for prompt graphs (missing mappings, immediate cycles)
|
|
52
|
-
- JSON round‑trip support for builder state persistence
|
|
53
|
-
- High‑level `Workflow` abstraction (rapid parameter tweaking of existing JSON graphs)
|
|
54
|
-
- Input sugar helpers: `wf.input(...)`, `wf.batchInputs(...)`
|
|
55
|
-
- Soft autocomplete mode for sampler / scheduler (`Workflow.fromAugmented`)
|
|
56
|
-
- Progressive typed outputs inferred from `wf.output(...)` declarations
|
|
57
|
-
- Per‑node output shape heuristics (e.g. `SaveImage*`, `KSampler`)
|
|
58
|
-
- Automatic random seed substitution for `seed: -1` with `_autoSeeds` metadata
|
|
59
|
-
|
|
60
|
-
## Installation
|
|
61
|
-
|
|
62
|
-
Requires Node.js >= 22 (modern WebSocket + fetch + ES2023 features). Works with Bun as well.
|
|
63
|
-
|
|
64
|
-
```bash
|
|
65
|
-
npm install comfyui-node
|
|
66
|
-
# or
|
|
67
|
-
pnpm add comfyui-node
|
|
68
|
-
# or
|
|
69
|
-
bun add comfyui-node
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
TypeScript types are bundled; no extra install needed.
|
|
73
|
-
|
|
74
|
-
Minimal ESM usage example:
|
|
75
|
-
|
|
76
|
-
```ts
|
|
77
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
78
|
-
import BaseWorkflow from './example-txt2img-workflow.json';
|
|
79
|
-
|
|
80
|
-
async function main() {
|
|
81
|
-
const api = await new ComfyApi('http://127.0.0.1:8188').ready();
|
|
82
|
-
const wf = Workflow.from(BaseWorkflow)
|
|
83
|
-
.set('6.inputs.text', 'Hello ComfyUI SDK')
|
|
84
|
-
.output('images:9');
|
|
85
|
-
const job = await api.run(wf, { autoDestroy: true });
|
|
86
|
-
const result = await job.done();
|
|
87
|
-
for (const img of (result.images?.images || [])) {
|
|
88
|
-
console.log('image path:', api.ext.file.getPathImage(img));
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
main();
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
## Cheat Sheet
|
|
95
|
-
|
|
96
|
-
Fast reference for common operations. See deeper sections for narrative explanations.
|
|
97
|
-
|
|
98
|
-
### Workflow (High-Level)
|
|
99
|
-
|
|
100
|
-
```ts
|
|
101
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
102
|
-
const api = await new ComfyApi('http://127.0.0.1:8188').ready();
|
|
103
|
-
const wf = Workflow.from(json)
|
|
104
|
-
.set('3.inputs.steps', 20) // dotted path set
|
|
105
|
-
.input('SAMPLER','cfg', 4) // input helper
|
|
106
|
-
.batchInputs('SAMPLER', { steps: 15, cfg: 3 })
|
|
107
|
-
.output('images:9'); // alias:nodeId
|
|
108
|
-
const job = await api.run(wf); // acceptance barrier
|
|
109
|
-
job.on('progress_pct', p => console.log(p,'%'));
|
|
110
|
-
const result = await job.done();
|
|
111
|
-
for (const img of (result.images?.images||[])) console.log(api.ext.file.getPathImage(img));
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
### PromptBuilder (Lower-Level)
|
|
115
|
-
|
|
116
|
-
```ts
|
|
117
|
-
import { PromptBuilder } from 'comfyui-node';
|
|
118
|
-
const builder = new PromptBuilder(base,[ 'positive','seed' ],[ 'images' ])
|
|
119
|
-
.setInputNode('positive','6.inputs.text')
|
|
120
|
-
.setInputNode('seed','3.inputs.seed')
|
|
121
|
-
.setOutputNode('images','9')
|
|
122
|
-
.input('positive','A misty forest')
|
|
123
|
-
.input('seed', 1234)
|
|
124
|
-
.validateOutputMappings();
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
### Running (Alternate APIs)
|
|
128
|
-
|
|
129
|
-
```ts
|
|
130
|
-
await api.run(wf); // high-level (Workflow)
|
|
131
|
-
await api.runWorkflow(wf); // alias
|
|
132
|
-
new CallWrapper(api, builder)
|
|
133
|
-
.onFinished(o => console.log(o.images?.images?.length))
|
|
134
|
-
.run(); // builder execution
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
### Declaring Outputs
|
|
138
|
-
|
|
139
|
-
```ts
|
|
140
|
-
wf.output('alias:NodeId');
|
|
141
|
-
wf.output('alias','NodeId');
|
|
142
|
-
wf.output('NodeId'); // key = id
|
|
143
|
-
// none declared -> auto collect SaveImage nodes
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
### Events (WorkflowJob)
|
|
147
|
-
|
|
148
|
-
```txt
|
|
149
|
-
pending -> start -> progress / progress_pct / preview -> output* -> finished (or failed)
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
| Event | Notes |
|
|
153
|
-
| ----- | ----- |
|
|
154
|
-
| pending | accepted into queue |
|
|
155
|
-
| start | first execution step began |
|
|
156
|
-
| progress_pct | integer 0-100 (deduped) |
|
|
157
|
-
| preview | live frame (Blob) |
|
|
158
|
-
| output | a declared / auto-detected node produced data |
|
|
159
|
-
| finished | all requested nodes resolved |
|
|
160
|
-
| failed | execution error / interruption |
|
|
161
|
-
|
|
162
|
-
### Seed Handling
|
|
163
|
-
|
|
164
|
-
```ts
|
|
165
|
-
// -1 sentinel => randomized & reported under _autoSeeds
|
|
166
|
-
wf.batchInputs('SAMPLER', { seed: -1 });
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
### Type Extraction
|
|
170
|
-
|
|
171
|
-
```ts
|
|
172
|
-
type Result = ReturnType<typeof wf.typedResult>;
|
|
173
|
-
```
|
|
174
|
-
|
|
175
|
-
### Pool Quick Start
|
|
176
|
-
|
|
177
|
-
```ts
|
|
178
|
-
const pool = new ComfyPool([
|
|
179
|
-
new ComfyApi('http://localhost:8188'),
|
|
180
|
-
new ComfyApi('http://localhost:8189')
|
|
181
|
-
]);
|
|
182
|
-
const job2 = await pool.clients[0].run(wf, { pool });
|
|
183
|
-
await job2.done();
|
|
184
|
-
```
|
|
185
|
-
|
|
186
|
-
### Selecting Workflow vs PromptBuilder
|
|
187
|
-
|
|
188
|
-
Use Workflow for 90% of: tweak existing JSON, few parameter edits, rapid prototyping. Use PromptBuilder when you must programmatically assemble / rewire node graphs or need validation utilities pre-submit.
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
### High‑Level Workflow API (Experimental) – Quick Intro
|
|
193
|
-
|
|
194
|
-
Skip manual `PromptBuilder` wiring with `Workflow` when you just want to tweak an existing graph JSON and run it. A full step‑by‑step tutorial is below; here is the 10‑second overview:
|
|
195
|
-
|
|
196
|
-
- Load JSON – `Workflow.from(json)`
|
|
197
|
-
- Mutate values – `.set('nodeId.inputs.field', value)`
|
|
198
|
-
- Declare outputs – `.output('alias:nodeId')` (or just `.output('nodeId')`; falls back to auto‑detecting `SaveImage` nodes)
|
|
199
|
-
- Execute – `await api.run(wf)` (or `api.runWorkflow(wf)` alias) returning a `WorkflowJob` (Promise‑like)
|
|
200
|
-
- Subscribe to events – `progress`, `progress_pct`, `preview`, `output`, `finished`, `failed`
|
|
201
|
-
- Await final object – either `await job` or `await job.done()`
|
|
202
|
-
|
|
203
|
-
See the dedicated tutorial section for a narrated example and option details.
|
|
204
|
-
|
|
205
|
-
### Recent Enhancements (Ergonomics & Typing)
|
|
206
|
-
|
|
207
|
-
The `Workflow` surface has gained several quality‑of‑life helpers and **progressive typing** features. All are additive (no breaking changes) and optional—fall back to raw `set()` / `output()` styles whenever you prefer.
|
|
208
|
-
|
|
209
|
-
| Feature | Purpose | Example | Type Effect |
|
|
210
|
-
| ------- | ------- | ------- | ----------- |
|
|
211
|
-
| `wf.input(nodeId, inputName, value)` | Concise single input mutation (vs dotted path) | `wf.input('SAMPLER','steps',30)` | none (runtime sugar) |
|
|
212
|
-
| `wf.batchInputs(nodeId, { ... })` | Set multiple inputs on one node | `wf.batchInputs('SAMPLER',{ steps:30, cfg:5 })` | none |
|
|
213
|
-
| `wf.batchInputs({ NODEA:{...} })` | Multi‑node batch mutation | `wf.batchInputs({ SAMPLER:{ cfg:6 } })` | none |
|
|
214
|
-
| `Workflow.fromAugmented(json)` | Soft autocomplete on sampler / scheduler but still accepts future values | `Workflow.fromAugmented(base)` | narrows fields to union \| (string & {}) |
|
|
215
|
-
| Typed output inference | `.output('alias:ID')` accumulates object keys | `wf.output('images:SAVE_IMAGE')` | widens result shape with `images` key |
|
|
216
|
-
| Per‑node output shape hints | Heuristic shapes for `SaveImage*`, `KSampler` | `result.images.images` | structural hints for nested fields |
|
|
217
|
-
| Multiple output syntaxes | Choose preferred style | `'alias:NodeId'` / `('alias','NodeId')` / `'NodeId'` | identical effect |
|
|
218
|
-
| `wf.typedResult()` | Get IDE type of final result | `type R = ReturnType<typeof wf.typedResult>` | captures accumulated generic |
|
|
219
|
-
| Auto seed substitution | `seed: -1` randomized before submit | `wf.input('SAMPLER','seed',-1)` | adds `_autoSeeds` map key |
|
|
220
|
-
| Acceptance barrier run | `await api.run(wf)` returns job handle pre-completion | `const job=await api.run(wf)` | result type unchanged |
|
|
221
|
-
|
|
222
|
-
> All typing is structural—no runtime validation. Unknown / future sampler names or new node classes continue to work.
|
|
223
|
-
|
|
224
|
-
#### Input Helpers
|
|
225
|
-
|
|
226
|
-
```ts
|
|
227
|
-
const wf = Workflow.fromAugmented(baseJson)
|
|
228
|
-
.input('LOADER','ckpt_name','model.safetensors')
|
|
229
|
-
.batchInputs('SAMPLER', {
|
|
230
|
-
steps: 30,
|
|
231
|
-
cfg: 4,
|
|
232
|
-
sampler_name: 'euler_ancestral', // autocomplete + accepts future strings
|
|
233
|
-
scheduler: 'karras', // autocomplete + forward compatible
|
|
234
|
-
seed: -1 // -1 -> auto randomized before submit
|
|
235
|
-
})
|
|
236
|
-
.batchInputs({
|
|
237
|
-
CLIP_TEXT_ENCODE_POSITIVE: { text: 'A moody cinematic landscape' },
|
|
238
|
-
LATENT_IMAGE: { width: 896, height: 1152 }
|
|
239
|
-
});
|
|
240
|
-
```
|
|
241
|
-
|
|
242
|
-
### Output Declaration & Typing
|
|
243
|
-
|
|
244
|
-
Each `output()` call accumulates inferred keys:
|
|
245
|
-
|
|
246
|
-
```ts
|
|
247
|
-
const wf2 = Workflow.fromAugmented(baseJson)
|
|
248
|
-
.output('gallery:SAVE_IMAGE') // key 'gallery'
|
|
249
|
-
.output('KSamplerNode') // key 'KSamplerNode'
|
|
250
|
-
.output('thumb','THUMBNAIL_NODE'); // key 'thumb'
|
|
251
|
-
|
|
252
|
-
// Type exploration (IDE only):
|
|
253
|
-
type Wf2Result = ReturnType<typeof wf2.typedResult>;
|
|
254
|
-
// Wf2Result ~ {
|
|
255
|
-
// gallery: { images?: any[] }; // SaveImage heuristic
|
|
256
|
-
// KSamplerNode: { samples?: any }; // KSampler heuristic
|
|
257
|
-
// thumb: any; // THUMBNAIL_NODE class not mapped yet
|
|
258
|
-
// _promptId?: string; _nodes?: string[]; _aliases?: Record<string,string>; _autoSeeds?: Record<string,number>;
|
|
259
|
-
// }
|
|
260
|
-
|
|
261
|
-
const job = await api.run(wf2);
|
|
262
|
-
const final = await job.done();
|
|
263
|
-
final.gallery.images?.forEach(img => console.log(api.ext.file.getPathImage(img)));
|
|
264
|
-
```
|
|
265
|
-
|
|
266
|
-
Supported output forms (all equivalent semantically; choose your style):
|
|
267
|
-
|
|
268
|
-
```ts
|
|
269
|
-
wf.output('alias:NodeId');
|
|
270
|
-
wf.output('alias','NodeId');
|
|
271
|
-
wf.output('NodeId'); // raw key = node id
|
|
272
|
-
```
|
|
273
|
-
|
|
274
|
-
If you declare *no* outputs the SDK still auto‑collects all `SaveImage` nodes.
|
|
275
|
-
|
|
276
|
-
#### Per‑Node Output Shapes (Heuristics)
|
|
277
|
-
|
|
278
|
-
Currently recognized:
|
|
279
|
-
|
|
280
|
-
| class_type match | Inferred shape fragment |
|
|
281
|
-
| ---------------- | ----------------------- |
|
|
282
|
-
| `SaveImage`, `SaveImageAdvanced` | `{ images?: any[] }` |
|
|
283
|
-
| `KSampler` | `{ samples?: any }` |
|
|
284
|
-
|
|
285
|
-
All others are typed as `any` (you still get alias key inference). This table will expand; explicit contributions welcome.
|
|
286
|
-
|
|
287
|
-
#### Combining With Result Metadata
|
|
288
|
-
|
|
289
|
-
The object from `job.done()` (and `runAndWait`) is always the intersection:
|
|
290
|
-
|
|
291
|
-
```ts
|
|
292
|
-
// final result shape (conceptual)
|
|
293
|
-
{ ...yourDeclaredOutputs, _promptId?: string, _nodes?: string[], _aliases?: Record<string,string>, _autoSeeds?: Record<string,number> }
|
|
294
|
-
```
|
|
295
|
-
|
|
296
|
-
#### When to Use `Workflow.fromAugmented`
|
|
297
|
-
|
|
298
|
-
Use it when you want IDE suggestions for sampler / scheduler *without* losing forward compatibility. The widened types are `TSamplerName | (string & {})` and `TSchedulerName | (string & {})` internally—any new upstream values are valid.
|
|
299
|
-
|
|
300
|
-
#### Extracting a Stable Result Type
|
|
301
|
-
|
|
302
|
-
If you want to export a type for downstream modules:
|
|
303
|
-
|
|
304
|
-
```ts
|
|
305
|
-
export type MyGenerationResult = ReturnType<typeof wf.typedResult>;
|
|
306
|
-
```
|
|
307
|
-
|
|
308
|
-
This stays accurate as long as all `output()` calls run before the type is captured.
|
|
309
|
-
|
|
310
|
-
#### Limitations & Future Work
|
|
311
|
-
|
|
312
|
-
- Output shapes are heuristic; not all node classes annotated yet.
|
|
313
|
-
- Dynamic node creation using non‑strict `input()` cannot update the generic shape (TypeScript limitation). You can re‑wrap with `Workflow.fromAugmented` after structural edits if needed.
|
|
314
|
-
- Potential future API: `wf.withOutputShapes({ MyCustomNode: { customField: string } })` for user overrides.
|
|
315
|
-
|
|
316
|
-
---
|
|
317
|
-
|
|
318
|
-
## Choosing: Workflow vs PromptBuilder
|
|
319
|
-
|
|
320
|
-
| Criterion | Prefer Workflow | Prefer PromptBuilder |
|
|
321
|
-
| --------- | --------------- | -------------------- |
|
|
322
|
-
| Starting point | You already have a working JSON graph | You need to assemble nodes programmatically |
|
|
323
|
-
| Change pattern | Tweak a handful of numeric/text inputs | Add/remove/re‑wire nodes dynamically |
|
|
324
|
-
| Output declaration | Simple image node aliases | Complex multi‑node mapping / conditional outputs |
|
|
325
|
-
| Validation needs | Light (auto collect `SaveImage`) | Strong: explicit mapping + cycle checks |
|
|
326
|
-
| Type ergonomics | Progressive result typing via `.output()` + heuristics | Fully explicit generic parameters on construction |
|
|
327
|
-
| Autocomplete | Sampler / scheduler (augmented mode) | Input & output alias keys / builder fluency |
|
|
328
|
-
| Serialization | Not needed / reuse same base JSON | Need to persist & replay builder state |
|
|
329
|
-
| Scheduling | Direct `api.run(wf)` | Usually wrapped in `CallWrapper` (or converted later) |
|
|
330
|
-
| Learning curve | Minimal (few fluent methods) | Slightly higher (need to map inputs / outputs) |
|
|
331
|
-
| Migration path | Can drop down later to builder if requirements grow | Can export to JSON & wrap with `Workflow.from(...)` for simpler tweaking |
|
|
332
|
-
|
|
333
|
-
Rule of thumb: start with `Workflow`. Move to `PromptBuilder` when you feel friction needing structural graph edits or stronger pre‑submit validation.
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
Pool variant (experimental):
|
|
337
|
-
|
|
338
|
-
```ts
|
|
339
|
-
import { ComfyApi, ComfyPool, Workflow } from 'comfyui-node';
|
|
340
|
-
import BaseWorkflow from './example-txt2img-workflow.json';
|
|
341
|
-
|
|
342
|
-
const pool = new ComfyPool([
|
|
343
|
-
new ComfyApi('http://localhost:8188'),
|
|
344
|
-
new ComfyApi('http://localhost:8189')
|
|
345
|
-
]);
|
|
346
|
-
|
|
347
|
-
const wf = Workflow.from(BaseWorkflow)
|
|
348
|
-
.set('6.inputs.text', 'A macro photo of a dewdrop on a leaf')
|
|
349
|
-
.output('9');
|
|
350
|
-
|
|
351
|
-
// Run using one specific API (pool provided for scheduling context)
|
|
352
|
-
const api2 = pool.clients[0];
|
|
353
|
-
const job2 = await api2.run(wf, { pool });
|
|
354
|
-
await job2.done();
|
|
355
|
-
```
|
|
356
|
-
|
|
357
|
-
Notes:
|
|
358
|
-
|
|
359
|
-
- Experimental surface: event names / helpers may refine before a stable minor release.
|
|
360
|
-
|
|
361
|
-
### PromptBuilder Validation & Serialization
|
|
362
|
-
|
|
363
|
-
`PromptBuilder` now includes optional robustness helpers you can invoke before submission:
|
|
364
|
-
|
|
365
|
-
```ts
|
|
366
|
-
builder
|
|
367
|
-
.validateOutputMappings() // Ensures every declared output key maps to an existing node id
|
|
368
|
-
.validateNoImmediateCycles(); // Guards against a node directly referencing itself in its input tuple
|
|
369
|
-
|
|
370
|
-
// Serialize to persist / send over IPC
|
|
371
|
-
const saved = builder.toJSON();
|
|
372
|
-
// Later restore (types must line up with original generic parameters when casting)
|
|
373
|
-
const restored = PromptBuilder.fromJSON(saved);
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
If validation fails an `Error` is thrown with a concise list of offending mappings, e.g.
|
|
377
|
-
|
|
378
|
-
```text
|
|
379
|
-
Error: Unmapped or missing output nodes: images:UNMAPPED
|
|
380
|
-
```
|
|
381
|
-
|
|
382
|
-
Cycle detection currently targets immediate self‑cycles (a node whose input tuple references itself). Broader multi‑hop cycle detection can be layered later without breaking this API.
|
|
383
|
-
|
|
384
|
-
### Common Validation Patterns
|
|
385
|
-
|
|
386
|
-
```ts
|
|
387
|
-
function safeBuild(wf: any) {
|
|
388
|
-
return new PromptBuilder(wf,["positive","seed"],["images"])
|
|
389
|
-
.setInputNode("positive","6.inputs.text")
|
|
390
|
-
.setInputNode("seed","3.inputs.seed")
|
|
391
|
-
.setOutputNode("images","9")
|
|
392
|
-
.input("positive","Hello world")
|
|
393
|
-
.input("seed", seed())
|
|
394
|
-
.validateOutputMappings()
|
|
395
|
-
.validateNoImmediateCycles();
|
|
396
|
-
}
|
|
397
|
-
```
|
|
398
|
-
|
|
399
|
-
## Result Object Anatomy
|
|
400
|
-
|
|
401
|
-
All high‑level executions (`api.run(wf)` / `runWorkflow` / `runAndWait`) ultimately resolve to an object merging:
|
|
402
|
-
|
|
403
|
-
1. Declared / inferred output aliases (each key value is the raw node output JSON for that node)
|
|
404
|
-
2. Heuristic shape hints (currently only augmenting `SaveImage*` & `KSampler` nodes with friendly nested fields)
|
|
405
|
-
3. Metadata fields: `_promptId`, `_nodes`, `_aliases`, `_autoSeeds`
|
|
406
|
-
|
|
407
|
-
Conceptual shape:
|
|
408
|
-
|
|
409
|
-
```ts
|
|
410
|
-
type WorkflowResult = {
|
|
411
|
-
// Your keys:
|
|
412
|
-
[aliasOrNodeId: string]: any; // each node's output blob (heuristically narrowed)
|
|
413
|
-
// Metadata:
|
|
414
|
-
_promptId?: string;
|
|
415
|
-
_nodes?: string[]; // collected node ids
|
|
416
|
-
_aliases?: Record<string,string>; // nodeId -> alias
|
|
417
|
-
_autoSeeds?: Record<string,number>; // nodeId -> randomized seed (when -1 sentinel used)
|
|
418
|
-
};
|
|
419
|
-
```
|
|
420
|
-
|
|
421
|
-
Example with heuristics:
|
|
422
|
-
|
|
423
|
-
```ts
|
|
424
|
-
const wf = Workflow.fromAugmented(json)
|
|
425
|
-
.output('gallery:SAVE_IMAGE')
|
|
426
|
-
.output('sampler:KSampler');
|
|
427
|
-
type R = ReturnType<typeof wf.typedResult>; // => { gallery: { images?: any[] }; sampler: { samples?: any }; _promptId?: ... }
|
|
428
|
-
```
|
|
429
|
-
|
|
430
|
-
Heuristics are intentionally shallow – they provide just enough structure for IDE discovery without locking you into specific upstream node versions. Missing shape? You still get the alias key with `any` type; open a PR to extend the mapping.
|
|
431
|
-
|
|
432
|
-
Access patterns:
|
|
433
|
-
|
|
434
|
-
```ts
|
|
435
|
-
const job = await api.run(wf);
|
|
436
|
-
job.on('output', id => console.log('node completed', id));
|
|
437
|
-
const res = await job.done();
|
|
438
|
-
console.log(res._promptId, Object.keys(res));
|
|
439
|
-
for (const img of (res.gallery?.images || [])) {
|
|
440
|
-
console.log(api.ext.file.getPathImage(img));
|
|
441
|
-
}
|
|
442
|
-
```
|
|
443
|
-
|
|
444
|
-
If you need a stable exported type for consumers:
|
|
445
|
-
|
|
446
|
-
```ts
|
|
447
|
-
export type GenerationResult = ReturnType<typeof wf.typedResult>;
|
|
448
|
-
```
|
|
449
|
-
|
|
450
|
-
Changing outputs later? Re‑generate the type after adding the new `.output()` call.
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
## Multi-Instance Pool
|
|
454
|
-
|
|
455
|
-
The SDK ships two pooling layers:
|
|
456
|
-
|
|
457
|
-
- **`WorkflowPool` (new, recommended)** – Manages its own queue (pluggable adapters), emits per-job events with consistent job ids, and handles smart failover / retry without depending on the ComfyUI server queue depth. Ideal for multi-tenant services or when integrating with Redis/BullMQ/RabbitMQ backends. **Features automatic health checks (v1.4.1+) to maintain stable connections during idle periods.**
|
|
458
|
-
- **`ComfyPool` (legacy)** – Weighted, in-memory scheduler that delegates most coordination to the ComfyUI queue. Useful for lightweight scripts or when you need backwards compatibility with earlier SDK versions.
|
|
459
|
-
|
|
460
|
-
### WorkflowPool
|
|
461
|
-
|
|
462
|
-
`WorkflowPool` is the recommended approach for production services that need:
|
|
463
|
-
|
|
464
|
-
- **Reliable connection management** – Automatic health checks keep WebSocket connections alive during idle periods, preventing false disconnection alerts
|
|
465
|
-
- **Queue flexibility** – Pluggable queue adapters (memory, Redis, BullMQ, RabbitMQ)
|
|
466
|
-
- **Smart failover** – Per-workflow cooldowns prevent wasting retries on incompatible nodes
|
|
467
|
-
- **Granular events** – Track job lifecycle (queued, assigned, progress, preview, completed, failed, cancelled)
|
|
468
|
-
- **Priority & metadata** – Attach custom metadata and control execution order
|
|
469
|
-
|
|
470
|
-
#### Quick Start
|
|
471
|
-
|
|
472
|
-
```ts
|
|
473
|
-
import { ComfyApi, WorkflowPool, MemoryQueueAdapter } from "comfyui-node";
|
|
474
|
-
import WorkflowJson from "./example-txt2img-workflow.json";
|
|
475
|
-
|
|
476
|
-
// Initialize clients
|
|
477
|
-
const clients = [
|
|
478
|
-
new ComfyApi("http://localhost:8188"),
|
|
479
|
-
new ComfyApi("http://localhost:8189")
|
|
480
|
-
];
|
|
481
|
-
|
|
482
|
-
// Create pool with default settings (includes health checks)
|
|
483
|
-
const pool = new WorkflowPool(clients, {
|
|
484
|
-
queueAdapter: new MemoryQueueAdapter()
|
|
485
|
-
});
|
|
486
|
-
|
|
487
|
-
// Listen to events
|
|
488
|
-
pool.on("job:progress", (ev) => {
|
|
489
|
-
console.log(`job ${ev.detail.jobId} -> ${ev.detail.progress.value}/${ev.detail.progress.max}`);
|
|
490
|
-
});
|
|
491
|
-
|
|
492
|
-
pool.on("job:preview", (ev) => {
|
|
493
|
-
console.log(`preview: ${ev.detail.preview.filename}`);
|
|
494
|
-
});
|
|
495
|
-
|
|
496
|
-
pool.on("client:blocked_workflow", (ev) => {
|
|
497
|
-
console.warn(`client ${ev.detail.clientId} cooling off for workflow ${ev.detail.workflowHash.slice(0, 8)}`);
|
|
498
|
-
});
|
|
499
|
-
|
|
500
|
-
// Enqueue job
|
|
501
|
-
const jobId = await pool.enqueue(WorkflowJson, {
|
|
502
|
-
metadata: { tenant: "alpha", userId: "user123" },
|
|
503
|
-
includeOutputs: ["9"], // collect output from node 9
|
|
504
|
-
priority: 10
|
|
505
|
-
});
|
|
506
|
-
|
|
507
|
-
console.log("queued", jobId);
|
|
508
|
-
|
|
509
|
-
// Get job status anytime
|
|
510
|
-
const job = pool.getJob(jobId);
|
|
511
|
-
console.log(job?.status); // "queued" | "assigned" | "executing" | "completed" | "failed" | "cancelled"
|
|
512
|
-
```
|
|
513
|
-
|
|
514
|
-
#### Configuration Options
|
|
515
|
-
|
|
516
|
-
```ts
|
|
517
|
-
import { WorkflowPool, WorkflowPoolOpts, SmartFailoverStrategy } from "comfyui-node";
|
|
518
|
-
|
|
519
|
-
const pool = new WorkflowPool(clients, {
|
|
520
|
-
// Queue adapter (default: MemoryQueueAdapter)
|
|
521
|
-
queueAdapter: new MemoryQueueAdapter(),
|
|
522
|
-
|
|
523
|
-
// Failover strategy (default: SmartFailoverStrategy)
|
|
524
|
-
failoverStrategy: new SmartFailoverStrategy(),
|
|
525
|
-
|
|
526
|
-
// Retry backoff delay in ms (default: 1000)
|
|
527
|
-
retryBackoffMs: 2000,
|
|
528
|
-
|
|
529
|
-
// Health check interval in ms (default: 30000)
|
|
530
|
-
// Keeps connections alive by pinging idle clients
|
|
531
|
-
// Set to 0 to disable (not recommended for production)
|
|
532
|
-
healthCheckIntervalMs: 30000
|
|
533
|
-
});
|
|
534
|
-
```
|
|
535
|
-
|
|
536
|
-
#### Connection Stability (v1.4.1+)
|
|
537
|
-
|
|
538
|
-
WorkflowPool now includes **automatic health checks** to maintain stable WebSocket connections:
|
|
539
|
-
|
|
540
|
-
- **Prevents idle timeouts** – Pings inactive clients every 30 seconds (configurable) with lightweight `getQueue()` calls
|
|
541
|
-
- **Non-intrusive** – Only pings idle (non-busy) clients to avoid interference with active jobs
|
|
542
|
-
- **Early detection** – Identifies connection issues before they impact job execution
|
|
543
|
-
- **Zero configuration** – Enabled by default with sensible settings
|
|
544
|
-
|
|
545
|
-
If you experience connection instability (clients repeatedly disconnecting/reconnecting), ensure:
|
|
546
|
-
|
|
547
|
-
1. Health checks are enabled (default behavior in v1.4.1+)
|
|
548
|
-
2. Your ComfyUI server is reachable and not behind aggressive firewalls
|
|
549
|
-
3. Network doesn't have overly aggressive idle timeouts (<30s)
|
|
550
|
-
|
|
551
|
-
For debugging connection issues:
|
|
552
|
-
|
|
553
|
-
```ts
|
|
554
|
-
pool.on("client:state", (ev) => {
|
|
555
|
-
console.log(`client ${ev.detail.clientId}: online=${ev.detail.online}, busy=${ev.detail.busy}`);
|
|
556
|
-
});
|
|
557
|
-
```
|
|
558
|
-
|
|
559
|
-
See `docs/workflow-pool.md` for full API and event reference.
|
|
560
|
-
|
|
561
|
-
### Legacy Pool (`ComfyPool`)
|
|
562
|
-
|
|
563
|
-
The legacy `ComfyPool` is a simpler, in-memory scheduler that relies on the server's queue depth for load balancing.
|
|
564
|
-
|
|
565
|
-
#### ComfyPool Modes
|
|
566
|
-
|
|
567
|
-
| Mode | Enum | Behavior | When to use |
|
|
568
|
-
| ---- | ---- | -------- | ----------- |
|
|
569
|
-
| Pick zero queue | `EQueueMode.PICK_ZERO` (default) | Choose any online client whose reported `queue_remaining` is 0 (prefers idle machines). Locks a client until it emits an execution event. | Co-existence with the ComfyUI web UI where queue spikes are common. |
|
|
570
|
-
| Lowest queue | `EQueueMode.PICK_LOWEST` | Choose the online client with the smallest `queue_remaining` (may still be busy). | High throughput batch ingestion; keeps all nodes saturated. |
|
|
571
|
-
| Round-robin | `EQueueMode.PICK_ROUTINE` | Simple rotation through available online clients irrespective of queue depth. | Latency balancing; predictable distribution. |
|
|
572
|
-
|
|
573
|
-
---
|
|
574
|
-
|
|
575
|
-
## High‑Level Workflow Tutorial (New Users of This SDK)
|
|
576
|
-
|
|
577
|
-
Audience: You already understand ComfyUI graphs & node JSON, but are new to this TypeScript SDK.
|
|
578
|
-
|
|
579
|
-
Goals after this section you can: (a) clone a base workflow, (b) modify its parameters, (c) name your desired outputs, (d) track progress & previews, and (e) retrieve final image paths – with minimal boilerplate.
|
|
580
|
-
|
|
581
|
-
### 1. Prepare a Base Workflow JSON
|
|
582
|
-
|
|
583
|
-
Export or copy a working ComfyUI txt2img graph (e.g. the one in `test/example-txt2img-workflow.json`). Ensure you know the node ID of the final `SaveImage` (here we assume `9`).
|
|
584
|
-
|
|
585
|
-
### 2. Initialize the API
|
|
586
|
-
|
|
587
|
-
`api.ready()` handles connection & feature probing. It is idempotent (can be safely called multiple times). You can override the host using `COMFY_HOST`.
|
|
588
|
-
|
|
589
|
-
### 3. Mutate Parameters & Declare Outputs
|
|
590
|
-
|
|
591
|
-
Use `.set('<nodeId>.inputs.<field>', value)` to change values. Call `.output('alias:nodeId')` to collect that node's result under a friendly key (`alias`). If you omit alias (`.output('9')`) the key will be the node ID. If you omit all outputs the SDK tries to collect every `SaveImage` node automatically.
|
|
592
|
-
|
|
593
|
-
Auto seed: If any node has an input field literally named `seed` with value `-1`, the SDK will replace it with a random 32‑bit integer before submission and expose the mapping in the final result under `_autoSeeds` (object keyed by node id). This lets you keep templates with `-1` sentinel for “random every run”.
|
|
594
|
-
|
|
595
|
-
### 4. Run & Observe Progress
|
|
596
|
-
|
|
597
|
-
`api.run(workflow, { autoDestroy: true })` executes and (optionally) closes underlying sockets once finished/failed so the process can exit without manual cleanup. The returned `WorkflowJob` is an EventEmitter‑like object AND a Promise: `await job` works just like `await job.done()`.
|
|
598
|
-
|
|
599
|
-
### 5. Extract Image Paths
|
|
600
|
-
|
|
601
|
-
Final structure includes your alias keys plus `_promptId`, `_nodes` and `_aliases` metadata. Use `api.ext.file.getPathImage(imageInfo)` to build a fetchable URL.
|
|
602
|
-
|
|
603
|
-
### Complete Example
|
|
604
|
-
|
|
605
|
-
```ts
|
|
606
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
607
|
-
import BaseWorkflow from './example-txt2img-workflow.json';
|
|
608
|
-
|
|
609
|
-
async function main() {
|
|
610
|
-
const api = await new ComfyApi(process.env.COMFY_HOST || 'http://127.0.0.1:8188').ready();
|
|
611
|
-
|
|
612
|
-
const wf = Workflow.from(BaseWorkflow)
|
|
613
|
-
.set('4.inputs.ckpt_name', process.env.COMFY_MODEL || 'SDXL/realvisxlV40_v40LightningBakedvae.safetensors')
|
|
614
|
-
.set('6.inputs.text', 'A dramatic cinematic landscape, volumetric light')
|
|
615
|
-
.set('7.inputs.text', 'text, watermark')
|
|
616
|
-
.set('3.inputs.seed', Math.floor(Math.random() * 10_000_000))
|
|
617
|
-
.set('3.inputs.steps', 8)
|
|
618
|
-
.set('3.inputs.cfg', 2)
|
|
619
|
-
.set('3.inputs.sampler_name', 'dpmpp_sde')
|
|
620
|
-
.set('3.inputs.scheduler', 'sgm_uniform')
|
|
621
|
-
.set('5.inputs.width', 1024)
|
|
622
|
-
.set('5.inputs.height', 1024)
|
|
623
|
-
.output('images:9'); // alias 'images' -> node 9
|
|
624
|
-
|
|
625
|
-
const job = await api.runWorkflow(wf, { autoDestroy: true });
|
|
626
|
-
|
|
627
|
-
job
|
|
628
|
-
.on('pending', id => console.log('[queue]', id))
|
|
629
|
-
.on('start', id => console.log('[start]', id))
|
|
630
|
-
.on('progress_pct', pct => process.stdout.write(`\rprogress ${pct}% `))
|
|
631
|
-
.on('preview', blob => console.log('\npreview frame bytes=', blob.size))
|
|
632
|
-
.on('failed', err => console.error('\nerror', err));
|
|
633
|
-
|
|
634
|
-
const result = await job; // or await job.done();
|
|
635
|
-
console.log('\nPrompt ID:', result._promptId);
|
|
636
|
-
for (const img of (result.images?.images || [])) {
|
|
637
|
-
console.log('image path:', api.ext.file.getPathImage(img));
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
main().catch(e => { console.error(e); process.exit(1); });
|
|
642
|
-
```
|
|
643
|
-
|
|
644
|
-
### Key Options Recap
|
|
645
|
-
|
|
646
|
-
| Option | Where | Purpose |
|
|
647
|
-
| ------ | ----- | ------- |
|
|
648
|
-
| `autoDestroy` | `api.run(...)` | Automatically `destroy()` the client on finish/fail |
|
|
649
|
-
| `includeOutputs` | `api.run(wf,{ includeOutputs:['9'] })` | Force extra node IDs (in addition to `.output(...)`) |
|
|
650
|
-
| `pool` | (advanced) | Execute through a `ComfyPool` for multi‑instance scheduling |
|
|
651
|
-
|
|
652
|
-
### Event Cheat Sheet (WorkflowJob)
|
|
653
|
-
|
|
654
|
-
| Event | Payload | Description |
|
|
655
|
-
| ----- | ------- | ----------- |
|
|
656
|
-
| `pending` | promptId | Enqueued, waiting to start |
|
|
657
|
-
| `start` | promptId | Execution began |
|
|
658
|
-
| `progress` | raw `{ value,max }` | Low‑level progress data |
|
|
659
|
-
| `progress_pct` | number (0‑100) | Deduped integer percentage (fires on change) |
|
|
660
|
-
| `preview` | `Blob` | Live image preview frame |
|
|
661
|
-
| `output` | nodeId | Partial node output arrived |
|
|
662
|
-
| `finished` | final object | All requested outputs resolved |
|
|
663
|
-
| `failed` | `Error` | Execution failed / interrupted |
|
|
664
|
-
|
|
665
|
-
### Execution Flow & Await Semantics
|
|
666
|
-
|
|
667
|
-
`await api.run(wf)` resolves AFTER the job has been accepted (queued) and returns a `WorkflowJob` handle you can attach events to. You then explicitly `await job.done()` for final outputs.
|
|
668
|
-
|
|
669
|
-
```ts
|
|
670
|
-
const job = await api.run(wf); // acceptance barrier reached -> you have prompt id via 'pending' event
|
|
671
|
-
job
|
|
672
|
-
.on('progress_pct', pct => console.log('progress', pct))
|
|
673
|
-
.on('preview', blob => console.log('preview frame', blob.size));
|
|
674
|
-
|
|
675
|
-
const outputs = await job.done(); // final mapped outputs + metadata
|
|
676
|
-
```
|
|
677
|
-
|
|
678
|
-
This two‑stage await keeps early feedback (events available immediately after acceptance) while still letting you write linear code for final result consumption.
|
|
679
|
-
|
|
680
|
-
Auto‑generated metadata keys:
|
|
681
|
-
|
|
682
|
-
| Key | Meaning |
|
|
683
|
-
| --- | ------- |
|
|
684
|
-
| `_promptId` | Server prompt id assigned |
|
|
685
|
-
| `_nodes` | Array of collected node ids |
|
|
686
|
-
| `_aliases` | Mapping nodeId -> alias (where provided) |
|
|
687
|
-
| `_autoSeeds` | Mapping nodeId -> randomized seed (only when you used -1 sentinel) |
|
|
688
|
-
|
|
689
|
-
---
|
|
690
|
-
|
|
691
|
-
### Job Weighting
|
|
692
|
-
|
|
693
|
-
Jobs are inserted into an internal priority queue ordered by ascending weight. Lower weight runs earlier. By default the weight is set to the queue length at insertion (FIFO). You can override:
|
|
694
|
-
|
|
695
|
-
```ts
|
|
696
|
-
await Promise.all([
|
|
697
|
-
pool.run(doSomethingHeavy, 10), // runs later
|
|
698
|
-
pool.run(doSomethingQuick, 1), // runs first
|
|
699
|
-
pool.run(anotherTask, 5)
|
|
700
|
-
]);
|
|
701
|
-
```
|
|
702
|
-
|
|
703
|
-
### Include / Exclude Filters
|
|
704
|
-
|
|
705
|
-
Target or avoid specific client IDs:
|
|
706
|
-
|
|
707
|
-
```ts
|
|
708
|
-
await pool.run(taskA, undefined, { includeIds: ["gpu-a"] }); // only gpu-a
|
|
709
|
-
await pool.run(taskB, undefined, { excludeIds: ["gpu-b"] }); // any except gpu-b
|
|
710
|
-
```
|
|
711
|
-
|
|
712
|
-
### Failover & Retries
|
|
713
|
-
|
|
714
|
-
`run()` attempts transparent failover when a job throws. It excludes the failing client and retries another (up to `maxRetries`).
|
|
715
|
-
|
|
716
|
-
```ts
|
|
717
|
-
await pool.run(doGenerate, undefined, undefined, { maxRetries: 3, retryDelay: 1500 });
|
|
718
|
-
```
|
|
719
|
-
|
|
720
|
-
Disable failover:
|
|
721
|
-
|
|
722
|
-
```ts
|
|
723
|
-
await pool.run(doGenerate, undefined, undefined, { enableFailover: false });
|
|
724
|
-
```
|
|
725
|
-
|
|
726
|
-
### Pool Events
|
|
727
|
-
|
|
728
|
-
`ComfyPool` is an `EventTarget` emitting high‑level orchestration signals:
|
|
729
|
-
|
|
730
|
-
| Event | Detail Payload | When |
|
|
731
|
-
| ----- | -------------- | ---- |
|
|
732
|
-
| `init` | – | All clients added & initial processing pass done |
|
|
733
|
-
| `added` / `removed` | `{ client, clientIdx }` | Client lifecycle changes |
|
|
734
|
-
| `ready` | `{ client, clientIdx }` | Individual client fully initialized |
|
|
735
|
-
| `executing` / `executed` | `{ client, clientIdx }` | A job starts / finishes on a client |
|
|
736
|
-
| `execution_error` | `{ client, clientIdx, error, willRetry, attempt, maxRetries }` | A job threw; may retry |
|
|
737
|
-
| `execution_interrupted` | `{ client, clientIdx }` | Underlying API emitted interruption |
|
|
738
|
-
| `connected` / `disconnected` / `reconnected` | `{ client, clientIdx }` | WebSocket state relayed from `ComfyApi` |
|
|
739
|
-
| `terminal` | `{ clientIdx, line }` | Terminal log pass‑through |
|
|
740
|
-
| `system_monitor` | `{ clientIdx, data }` | Crystools monitor snapshot (when supported) |
|
|
741
|
-
| `add_job` | `{ jobIdx, weight }` | Job inserted into internal queue |
|
|
742
|
-
| `change_mode` | `{ mode }` | Queue selection mode altered |
|
|
743
|
-
| `have_job` | `{ client, remain }` | A client reports pending queue > 0 |
|
|
744
|
-
| `idle` | `{ client }` | A previously busy client reports queue 0 |
|
|
745
|
-
|
|
746
|
-
### Cleaning Up
|
|
747
|
-
|
|
748
|
-
Always invoke `destroy()` when finished to clear intervals, event listeners & underlying client connections:
|
|
749
|
-
|
|
750
|
-
```ts
|
|
751
|
-
pool.destroy();
|
|
752
|
-
```
|
|
753
|
-
|
|
754
|
-
### Combined Orchestration Example (Auth + Pool + Validation + Retry)
|
|
755
|
-
|
|
756
|
-
```ts
|
|
757
|
-
import { ComfyApi, ComfyPool, EQueueMode, PromptBuilder, CallWrapper, seed } from "comfyui-node";
|
|
758
|
-
|
|
759
|
-
const pool = new ComfyPool([
|
|
760
|
-
new ComfyApi(process.env.C1!,"c1", { credentials: { type: "bearer_token", token: process.env.C1_TOKEN! } }),
|
|
761
|
-
new ComfyApi(process.env.C2!,"c2")
|
|
762
|
-
], { mode: EQueueMode.PICK_LOWEST });
|
|
763
|
-
|
|
764
|
-
async function generate(api: ComfyApi, text: string) {
|
|
765
|
-
const wf = /* load / clone a base workflow JSON */ {} as any;
|
|
766
|
-
const builder = new PromptBuilder(wf,["positive","seed"],["images"])
|
|
767
|
-
.setInputNode("positive","6.inputs.text")
|
|
768
|
-
.setInputNode("seed","3.inputs.seed")
|
|
769
|
-
.setOutputNode("images","9")
|
|
770
|
-
.input("positive", text)
|
|
771
|
-
.input("seed", seed())
|
|
772
|
-
.validateOutputMappings();
|
|
773
|
-
|
|
774
|
-
return await new Promise<string[]>((resolve, reject) => {
|
|
775
|
-
new CallWrapper(api, builder)
|
|
776
|
-
.onFinished(d => resolve((d.images?.images||[]).map((img:any)=> api.ext.file.getPathImage(img))))
|
|
777
|
-
.onFailed(err => reject(err))
|
|
778
|
-
.run();
|
|
779
|
-
});
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
// Weighted submission with retry semantics
|
|
783
|
-
const tasks = ["cat portrait","cyberpunk city","forest at dawn"].map(txt => (api: ComfyApi) => generate(api, txt));
|
|
784
|
-
const results = await Promise.all(tasks.map((fn,i)=> pool.run(fn, i))); // lower weight = earlier
|
|
785
|
-
console.log(results.flat());
|
|
786
|
-
pool.destroy();
|
|
787
|
-
```
|
|
788
|
-
|
|
789
|
-
### Choosing a Mode
|
|
790
|
-
|
|
791
|
-
| Goal | Suggested Mode |
|
|
792
|
-
| ---- | -------------- |
|
|
793
|
-
| Minimize latency spikes | `PICK_ZERO` |
|
|
794
|
-
| Maximize throughput | `PICK_LOWEST` |
|
|
795
|
-
| Deterministic striping | `PICK_ROUTINE` |
|
|
796
|
-
|
|
797
|
-
You can change dynamically:
|
|
798
|
-
|
|
799
|
-
```ts
|
|
800
|
-
pool.changeMode(EQueueMode.PICK_LOWEST);
|
|
801
|
-
```
|
|
802
|
-
|
|
803
|
-
### Observability Tips
|
|
804
|
-
|
|
805
|
-
Listen for `execution_error` with `willRetry=true` to surface transient node failures; attach Prometheus / metrics counters externally from these events if desired.
|
|
806
|
-
|
|
807
|
-
### Relation to `CallWrapper`
|
|
808
|
-
|
|
809
|
-
`ComfyPool` does not abstract prompt construction or execution detail; each job decides how to use `CallWrapper`, direct `api.ext.queue.*` calls or even file operations before enqueueing.
|
|
810
|
-
|
|
811
|
-
### Future Ideas (Contributions Welcome)
|
|
812
|
-
|
|
813
|
-
- Global circuit breaker (temporarily exclude flapping client)
|
|
814
|
-
- Adaptive weight assignment based on rolling execution duration
|
|
815
|
-
- Pluggable selection strategies via user callback
|
|
816
|
-
|
|
817
|
-
If you build one, open a PR – keep the core minimal & dependency‑free.
|
|
818
|
-
|
|
819
|
-
## Authentication
|
|
820
|
-
|
|
821
|
-
```ts
|
|
822
|
-
import { ComfyApi, BasicCredentials, BearerTokenCredentials, CustomCredentials } from "comfyui-node";
|
|
823
|
-
|
|
824
|
-
const basic = new ComfyApi("http://localhost:8189","id1", { credentials: { type: "basic", username: "u", password: "p" } as BasicCredentials }).init();
|
|
825
|
-
const bearer = new ComfyApi("http://localhost:8189","id2", { credentials: { type: "bearer_token", token: "token" } as BearerTokenCredentials }).init();
|
|
826
|
-
const custom = new ComfyApi("http://localhost:8189","id3", { credentials: { type: "custom", headers: { "X-Api-Key": "abc" } } as CustomCredentials }).init();
|
|
827
|
-
```
|
|
828
|
-
|
|
829
|
-
## Custom WebSocket
|
|
830
|
-
|
|
831
|
-
```ts
|
|
832
|
-
import { ComfyApi, WebSocketInterface } from "comfyui-node";
|
|
833
|
-
import CustomWebSocket from "your-custom-ws";
|
|
834
|
-
|
|
835
|
-
const api = new ComfyApi("http://localhost:8189", "node-id", { customWebSocketImpl: CustomWebSocket as WebSocketInterface }).init();
|
|
836
|
-
```
|
|
837
|
-
|
|
838
|
-
## Modular Features (`api.ext`)
|
|
839
|
-
|
|
840
|
-
```ts
|
|
841
|
-
await api.waitForReady();
|
|
842
|
-
await api.ext.queue.queuePrompt(null, workflow);
|
|
843
|
-
const stats = await api.ext.system.getSystemStats();
|
|
844
|
-
const checkpoints = await api.ext.node.getCheckpoints();
|
|
845
|
-
const embeddings = await api.ext.misc.getEmbeddings();
|
|
846
|
-
const flags = await api.ext.featureFlags.getServerFeatures();
|
|
847
|
-
```
|
|
848
|
-
|
|
849
|
-
| Namespace | Responsibility |
|
|
850
|
-
| --------- | -------------- |
|
|
851
|
-
| `queue` | Prompt submission, append & interrupt |
|
|
852
|
-
| `history` | Execution history retrieval |
|
|
853
|
-
| `system` | System stats & memory free |
|
|
854
|
-
| `node` | Node defs + sampler / checkpoint / lora helpers |
|
|
855
|
-
| `user` | User & settings CRUD |
|
|
856
|
-
| `file` | Uploads, image helpers, user data file ops |
|
|
857
|
-
| `model` | Experimental model browsing & previews |
|
|
858
|
-
| `terminal` | Terminal logs & subscription toggle |
|
|
859
|
-
| `misc` | Extensions list, embeddings (new + fallback) |
|
|
860
|
-
| `manager` | ComfyUI Manager extension integration |
|
|
861
|
-
| `monitor` | Crystools monitor events & snapshot |
|
|
862
|
-
| `featureFlags` | Server capabilities (`/features`) |
|
|
863
|
-
|
|
864
|
-
## Events
|
|
865
|
-
|
|
866
|
-
Both `ComfyApi` and `ComfyPool` expose strongly typed event maps. Import the key unions or event maps for generic helpers:
|
|
867
|
-
|
|
868
|
-
```ts
|
|
869
|
-
import { ComfyApi, ComfyApiEventKey, TComfyAPIEventMap } from 'comfyui-node';
|
|
870
|
-
|
|
871
|
-
const api = new ComfyApi('http://localhost:8188');
|
|
872
|
-
api.on('progress', (ev) => {
|
|
873
|
-
console.log(ev.detail.value, '/', ev.detail.max);
|
|
874
|
-
});
|
|
875
|
-
|
|
876
|
-
function handleApiEvent<K extends ComfyApiEventKey>(k: K, e: TComfyAPIEventMap[K]) {
|
|
877
|
-
if (k === 'executed') {
|
|
878
|
-
console.log('Node executed:', e.detail.node);
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
```
|
|
882
|
-
|
|
883
|
-
Pool usage:
|
|
884
|
-
|
|
885
|
-
```ts
|
|
886
|
-
import { ComfyPool, ComfyPoolEventKey } from 'comfyui-node';
|
|
887
|
-
|
|
888
|
-
pool.on('execution_error', (ev) => {
|
|
889
|
-
if (ev.detail.willRetry) console.warn('Transient failure, retrying...');
|
|
890
|
-
});
|
|
891
|
-
```
|
|
892
|
-
|
|
893
|
-
---
|
|
894
|
-
|
|
895
|
-
## Preview Metadata
|
|
896
|
-
|
|
897
|
-
When the server advertises the `supports_preview_metadata` feature flag, binary preview frames are sent using a richer protocol (`PREVIEW_IMAGE_WITH_METADATA`). The SDK decodes these frames and exposes both legacy and richer events.
|
|
898
|
-
|
|
899
|
-
What you get:
|
|
900
|
-
|
|
901
|
-
- Low-level API events on `ComfyApi`:
|
|
902
|
-
- `b_preview` – existing event with `Blob` image only (kept for backward compatibility)
|
|
903
|
-
- `b_preview_meta` – new event with `{ blob: Blob; metadata: any }`
|
|
904
|
-
|
|
905
|
-
- High-level `WorkflowJob` events:
|
|
906
|
-
- `preview` – existing event with `Blob`
|
|
907
|
-
- `preview_meta` – new event with `{ blob, metadata }`
|
|
908
|
-
|
|
909
|
-
Server protocol (per ComfyUI `protocol.py`):
|
|
910
|
-
|
|
911
|
-
- Binary event IDs:
|
|
912
|
-
- `1` = `PREVIEW_IMAGE` (legacy)
|
|
913
|
-
- `4` = `PREVIEW_IMAGE_WITH_METADATA`
|
|
914
|
-
- For type `4`, payload format after the 4-byte type header:
|
|
915
|
-
- 4 bytes: big-endian uint32 `metadata_length`
|
|
916
|
-
- N bytes: UTF-8 JSON metadata
|
|
917
|
-
- remaining: image bytes (PNG or JPEG)
|
|
918
|
-
|
|
919
|
-
The SDK reads `metadata.image_type` to set the Blob MIME type.
|
|
920
|
-
|
|
921
|
-
Example – low-level API usage:
|
|
922
|
-
|
|
923
|
-
```ts
|
|
924
|
-
api.on('b_preview_meta', (ev) => {
|
|
925
|
-
const { blob, metadata } = ev.detail;
|
|
926
|
-
console.log('[b_preview_meta]', metadata, 'bytes=', blob.size);
|
|
927
|
-
});
|
|
928
|
-
```
|
|
929
|
-
|
|
930
|
-
Example – high-level Workflow API usage:
|
|
931
|
-
|
|
932
|
-
```ts
|
|
933
|
-
const job = await api.run(wf, { autoDestroy: true });
|
|
934
|
-
|
|
935
|
-
job
|
|
936
|
-
.on('preview', (blob) => console.log('preview bytes=', blob.size))
|
|
937
|
-
.on('preview_meta', ({ blob, metadata }) => {
|
|
938
|
-
console.log('mime:', metadata?.image_type, 'size=', blob.size);
|
|
939
|
-
// other metadata fields depend on the server implementation
|
|
940
|
-
});
|
|
941
|
-
```
|
|
942
|
-
|
|
943
|
-
Backwards compatibility:
|
|
944
|
-
|
|
945
|
-
- If the server only emits legacy frames, you will still receive `preview` / `b_preview` events as before.
|
|
946
|
-
- When metadata frames are present, both are emitted: `b_preview` and `b_preview_meta` (and at the high level, `preview` and `preview_meta`).
|
|
947
|
-
|
|
948
|
-
Troubleshooting:
|
|
949
|
-
|
|
950
|
-
- Ensure your ComfyUI build supports `PREVIEW_IMAGE_WITH_METADATA` and that the feature flag is enabled. The SDK announces support via WebSocket on connect.
|
|
951
|
-
|
|
952
|
-
---
|
|
953
|
-
|
|
954
|
-
## API Nodes (Comfy.org paid)
|
|
955
|
-
|
|
956
|
-
Some workflows use paid API nodes (for example, Luma/Photon) that communicate progress and results via additional binary WebSocket frames. This SDK supports those nodes by:
|
|
957
|
-
|
|
958
|
-
- Allowing you to pass your Comfy.org API key to the server with each job
|
|
959
|
-
- Emitting low-level events for binary/text frames so you can surface progress and result URLs
|
|
960
|
-
|
|
961
|
-
### Enabling API-node runs
|
|
962
|
-
|
|
963
|
-
Provide your key through the `comfyOrgApiKey` client option (recommended to source it from an environment variable):
|
|
964
|
-
|
|
965
|
-
```ts
|
|
966
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
967
|
-
import LumaPhoton from './your-luma-photon-workflow.json';
|
|
968
|
-
|
|
969
|
-
const api = await new ComfyApi(
|
|
970
|
-
process.env.COMFY_HOST || 'http://127.0.0.1:8188',
|
|
971
|
-
undefined,
|
|
972
|
-
{
|
|
973
|
-
comfyOrgApiKey: process.env.COMFY_ORG_API_KEY,
|
|
974
|
-
wsTimeout: 30000, // API nodes may take longer; increase if needed
|
|
975
|
-
debug: true // optional: structured socket + polling logs
|
|
976
|
-
}
|
|
977
|
-
).ready();
|
|
978
|
-
|
|
979
|
-
// Minimal example: set prompt/seed, declare output, observe events
|
|
980
|
-
const wf = Workflow.fromAugmented(LumaPhoton)
|
|
981
|
-
.input('LUMA', 'prompt', 'Old photograph of the Guanabara Bay in Rio de Janeiro, aerial view')
|
|
982
|
-
.input('LUMA', 'seed', -1) // -1 => randomized; see _autoSeeds in result
|
|
983
|
-
.output('final_images', '2'); // alias, nodeId (auto-corrects if swapped)
|
|
984
|
-
|
|
985
|
-
// Low-level API-node events (binary channel text + raw preview bytes)
|
|
986
|
-
api.on('b_text', (ev) => {
|
|
987
|
-
const text = (ev as any).detail as string;
|
|
988
|
-
if (typeof text === 'string') console.log('[api-node text]', text.slice(0, 200));
|
|
989
|
-
});
|
|
990
|
-
api.on('b_text_meta', (ev) => {
|
|
991
|
-
// { channel: number, text: string }
|
|
992
|
-
console.log('[api-node text meta]', (ev as any).detail);
|
|
993
|
-
});
|
|
994
|
-
api.on('b_preview_raw', (ev) => {
|
|
995
|
-
const bytes = (ev as any).detail as Uint8Array;
|
|
996
|
-
console.log('[api-node preview raw bytes]', bytes?.byteLength);
|
|
997
|
-
});
|
|
998
|
-
|
|
999
|
-
const job = await api.run(wf, { autoDestroy: true });
|
|
1000
|
-
|
|
1001
|
-
job
|
|
1002
|
-
.on('start', (id) => console.log('[start]', id))
|
|
1003
|
-
.on('progress_pct', (p) => process.stdout.write(`\rprogress ${p}% `))
|
|
1004
|
-
.on('preview', (blob) => console.log('\npreview bytes=', blob.size))
|
|
1005
|
-
.on('failed', (e) => console.error('\nfailed', e));
|
|
1006
|
-
|
|
1007
|
-
const result = await job.done();
|
|
1008
|
-
console.log('\nPrompt ID:', result._promptId);
|
|
1009
|
-
for (const img of (result.final_images?.images || [])) {
|
|
1010
|
-
console.log('image path:', api.ext.file.getPathImage(img));
|
|
1011
|
-
}
|
|
1012
|
-
```
|
|
1013
|
-
|
|
1014
|
-
Notes:
|
|
1015
|
-
|
|
1016
|
-
- API-node text frames often include human-readable progress and a final “Result URL:” line. The SDK exposes the raw text via `b_text` and `{ channel, text }` via `b_text_meta` so you can parse or display them as desired.
|
|
1017
|
-
- For long-running API calls, increase `wsTimeout` and consider enabling `debug` or setting `COMFY_DEBUG=1` to troubleshoot reconnection/polling.
|
|
1018
|
-
- Output declaration accepts any of: `'alias:NodeId'`, `('alias','NodeId')`, or `'NodeId'`. If you accidentally swap the alias/id parameters, the SDK will auto-correct and warn.
|
|
1019
|
-
|
|
1020
|
-
Security tip: Never print your API key. The built-in debug logger redacts common key/authorization fields automatically.
|
|
1021
|
-
|
|
1022
|
-
---
|
|
1023
|
-
|
|
1024
|
-
## Image Inputs: Attach Files (DX)
|
|
1025
|
-
|
|
1026
|
-
When a workflow references images (e.g., `LoadImage.image = "IMAGE_A.png"` or folder loaders such as `LoadImageSetFromFolderNode`), you can attach local buffers directly to the `Workflow` and let the SDK handle uploads before execution.
|
|
1027
|
-
|
|
1028
|
-
Helpers:
|
|
1029
|
-
|
|
1030
|
-
- `wf.attachImage(nodeId, inputName, data, fileName, opts?)`
|
|
1031
|
-
- Uploads `data` (Blob/Buffer/ArrayBuffer/Uint8Array) and sets the node input to `fileName` automatically.
|
|
1032
|
-
- Options: `{ subfolder?: string; override?: boolean }`.
|
|
1033
|
-
- `wf.attachFolderFiles(subfolder, files[], opts?)`
|
|
1034
|
-
- Upload multiple files into a server subfolder; ideal for folder‑based loaders.
|
|
1035
|
-
|
|
1036
|
-
Example (see `scripts/image-loading-demo.ts`):
|
|
1037
|
-
|
|
1038
|
-
```ts
|
|
1039
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
1040
|
-
import Graph from './ImageLoading.json';
|
|
1041
|
-
import * as fs from 'node:fs/promises';
|
|
1042
|
-
import * as path from 'node:path';
|
|
1043
|
-
|
|
1044
|
-
const api = await new ComfyApi(process.env.COMFY_HOST || 'http://127.0.0.1:8188').ready();
|
|
1045
|
-
const wf = Workflow.from(Graph);
|
|
1046
|
-
|
|
1047
|
-
// Attach two individual images for LoadImage nodes 2 and 4
|
|
1048
|
-
const dir = path.resolve(process.cwd(), 'scripts', 'example_images');
|
|
1049
|
-
const a = await fs.readFile(path.join(dir, 'IMAGE_A.png'));
|
|
1050
|
-
const b = await fs.readFile(path.join(dir, 'IMAGE_B.png'));
|
|
1051
|
-
wf.attachImage('2', 'image', a, 'IMAGE_A.png', { override: true })
|
|
1052
|
-
.attachImage('4', 'image', b, 'IMAGE_B.png', { override: true });
|
|
1053
|
-
|
|
1054
|
-
// Attach an entire folder for node 5 (LoadImageSetFromFolderNode)
|
|
1055
|
-
const files = (await fs.readdir(dir))
|
|
1056
|
-
.filter(f => /\.(png|jpe?g|webp)$/i.test(f))
|
|
1057
|
-
.map(async f => ({ fileName: f, data: await fs.readFile(path.join(dir, f)) }));
|
|
1058
|
-
wf.attachFolderFiles('EXAMPLE_IMAGES', await Promise.all(files), { override: true });
|
|
1059
|
-
wf.set('5.inputs.folder', 'EXAMPLE_IMAGES');
|
|
1060
|
-
|
|
1061
|
-
// Collect a simple output target for demonstration
|
|
1062
|
-
wf.output('1');
|
|
1063
|
-
|
|
1064
|
-
const job = await api.run(wf, { autoDestroy: true });
|
|
1065
|
-
job.on('progress_pct', p => process.stdout.write(`\rprogress ${p}% `));
|
|
1066
|
-
await job.done();
|
|
1067
|
-
```
|
|
1068
|
-
|
|
1069
|
-
Notes:
|
|
1070
|
-
|
|
1071
|
-
- The inputs are updated to point at the uploaded filenames; subfolders are handled server‑side.
|
|
1072
|
-
- Use `override: true` to replace existing files with the same name if needed.
|
|
1073
|
-
|
|
1074
|
-
---
|
|
1075
|
-
|
|
1076
|
-
## 1.0 Migration
|
|
1077
|
-
|
|
1078
|
-
All legacy `ComfyApi` instance methods listed below were **removed in 1.0.0** after a deprecation window in 0.2.x. Migrate to the `api.ext.*` namespaces. If you're upgrading from <1.0, replace calls as shown. No runtime warnings remain (they were stripped with the removals).
|
|
1079
|
-
|
|
1080
|
-
| Deprecated | Replacement |
|
|
1081
|
-
| ---------- | ----------- |
|
|
1082
|
-
| `queuePrompt(...)` | `api.ext.queue.queuePrompt(...)` |
|
|
1083
|
-
| `appendPrompt(...)` | `api.ext.queue.appendPrompt(...)` |
|
|
1084
|
-
| `getHistories(...)` | `api.ext.history.getHistories(...)` |
|
|
1085
|
-
| `getHistory(id)` | `api.ext.history.getHistory(id)` |
|
|
1086
|
-
| `getSystemStats()` | `api.ext.system.getSystemStats()` |
|
|
1087
|
-
| `getCheckpoints()` | `api.ext.node.getCheckpoints()` |
|
|
1088
|
-
| `getLoras()` | `api.ext.node.getLoras()` |
|
|
1089
|
-
| `getSamplerInfo()` | `api.ext.node.getSamplerInfo()` |
|
|
1090
|
-
| `getNodeDefs(name?)` | `api.ext.node.getNodeDefs(name?)` |
|
|
1091
|
-
| `getExtensions()` | `api.ext.misc.getExtensions()` |
|
|
1092
|
-
| `getEmbeddings()` | `api.ext.misc.getEmbeddings()` |
|
|
1093
|
-
| `uploadImage(...)` | `api.ext.file.uploadImage(...)` |
|
|
1094
|
-
| `uploadMask(...)` | `api.ext.file.uploadMask(...)` |
|
|
1095
|
-
| `getPathImage(info)` | `api.ext.file.getPathImage(info)` |
|
|
1096
|
-
| `getImage(info)` | `api.ext.file.getImage(info)` |
|
|
1097
|
-
| `getUserData(file)` | `api.ext.file.getUserData(file)` |
|
|
1098
|
-
| `storeUserData(...)` | `api.ext.file.storeUserData(...)` |
|
|
1099
|
-
| `deleteUserData(file)` | `api.ext.file.deleteUserData(file)` |
|
|
1100
|
-
| `moveUserData(...)` | `api.ext.file.moveUserData(...)` |
|
|
1101
|
-
| `listUserData(...)` | `api.ext.file.listUserData(...)` |
|
|
1102
|
-
| `getUserConfig()` | `api.ext.user.getUserConfig()` |
|
|
1103
|
-
| `createUser(name)` | `api.ext.user.createUser(name)` |
|
|
1104
|
-
| `getSettings()` | `api.ext.user.getSettings()` |
|
|
1105
|
-
| `getSetting(id)` | `api.ext.user.getSetting(id)` |
|
|
1106
|
-
| `storeSettings(map)` | `api.ext.user.storeSettings(map)` |
|
|
1107
|
-
| `storeSetting(id,val)` | `api.ext.user.storeSetting(id,val)` |
|
|
1108
|
-
| `getTerminalLogs()` | `api.ext.terminal.getTerminalLogs()` |
|
|
1109
|
-
| `setTerminalSubscription()` | `api.ext.terminal.setTerminalSubscription()` |
|
|
1110
|
-
| `interrupt()` | `api.ext.queue.interrupt()` |
|
|
1111
|
-
|
|
1112
|
-
Quick grep-based migration (bash):
|
|
1113
|
-
|
|
1114
|
-
```bash
|
|
1115
|
-
grep -R "api\.getSystemStats" -n src | cut -d: -f1 | xargs sed -i '' 's/api\.getSystemStats()/api.ext.system.getSystemStats()/g'
|
|
1116
|
-
```
|
|
1117
|
-
|
|
1118
|
-
PowerShell example:
|
|
1119
|
-
|
|
1120
|
-
```powershell
|
|
1121
|
-
Get-ChildItem -Recurse -Include *.ts | ForEach-Object {
|
|
1122
|
-
(Get-Content $_.FullName) -replace 'api.getSystemStats\(\)', 'api.ext.system.getSystemStats()' | Set-Content $_.FullName
|
|
1123
|
-
}
|
|
1124
|
-
```
|
|
1125
|
-
|
|
1126
|
-
(Adjust the pattern per method; or use a codemod tool if you have many occurrences.)
|
|
1127
|
-
|
|
1128
|
-
Diff example:
|
|
1129
|
-
|
|
1130
|
-
Example migration:
|
|
1131
|
-
|
|
1132
|
-
```diff
|
|
1133
|
-
- const stats = await api.getSystemStats();
|
|
1134
|
-
+ const stats = await api.ext.system.getSystemStats();
|
|
1135
|
-
- await api.uploadImage(buf, 'a.png');
|
|
1136
|
-
+ await api.ext.file.uploadImage(buf, 'a.png');
|
|
1137
|
-
```
|
|
1138
|
-
|
|
1139
|
-
## Reference Overview
|
|
1140
|
-
|
|
1141
|
-
Core (non‑deprecated) `ComfyApi` methods: `init`, `waitForReady`, event registration (`on`/`off`/`removeAllListeners`), `fetchApi`, `pollStatus`, `ping`, `reconnectWs`, `destroy`, and modular surface via `ext`.
|
|
1142
|
-
|
|
1143
|
-
Supporting classes:
|
|
1144
|
-
|
|
1145
|
-
- `PromptBuilder` – graph construction & value injection
|
|
1146
|
-
- `CallWrapper` – prompt execution lifecycle helpers
|
|
1147
|
-
- `ComfyPool` – multi‑instance scheduler
|
|
1148
|
-
|
|
1149
|
-
Enums & Types: `EQueueMode`, sampler / scheduler unions, `OSType`, plus exported response types found under `types/*`.
|
|
1150
|
-
|
|
1151
|
-
## Monitoring: System vs Job Progress
|
|
1152
|
-
|
|
1153
|
-
"Monitoring" in this SDK refers to two unrelated event domains:
|
|
1154
|
-
|
|
1155
|
-
| Type | Source | Requires Extension | Events | Usage |
|
|
1156
|
-
| ---- | ------ | ------------------ | ------ | ----- |
|
|
1157
|
-
| System Monitoring | Crystools extension | Yes (ComfyUI-Crystools) | `system_monitor` (pool) + feature internals | Host CPU/GPU/RAM telemetry |
|
|
1158
|
-
| Job Progress | Core ComfyUI | No | `executing`, `progress`, `executed`, `execution_success`, `execution_error`, `execution_interrupted`, `b_preview` | Per‑job progress %, live image previews |
|
|
1159
|
-
|
|
1160
|
-
System monitoring is toggled via env flags in the smoke script (`COMFY_MONITOR`, `COMFY_MONITOR_STRICT`, `COMFY_MONITOR_FORCE`) and is surfaced under `api.ext.monitor`.
|
|
1161
|
-
|
|
1162
|
-
Job progress monitoring is always active: subscribe directly (`api.on("progress", ...)`) or use higher‑level helpers:
|
|
1163
|
-
|
|
1164
|
-
```ts
|
|
1165
|
-
new CallWrapper(api, builder)
|
|
1166
|
-
.onProgress(p => console.log(p.value, '/', p.max))
|
|
1167
|
-
.onPreview(blob => /* show transient image */)
|
|
1168
|
-
.onFinished(out => /* final outputs */)
|
|
1169
|
-
.run();
|
|
1170
|
-
```
|
|
1171
|
-
|
|
1172
|
-
The published smoke test now logs job progress automatically and counts preview frames. Set `COMFY_PROGRESS_VERBOSE=1` to force log every step (not just percentage changes).
|
|
1173
|
-
|
|
1174
|
-
If you only need generation progress & previews you do NOT need the Crystools extension.
|
|
1175
|
-
|
|
1176
|
-
## Examples
|
|
1177
|
-
|
|
1178
|
-
See the `examples` directory for text-to-image, image-to-image, upscaling and pool orchestration patterns. For an end-to-end WorkflowPool + WebSocket demo, open `demos/recursive-edit/` and run the recursive image editing server + web client.
|
|
1179
|
-
|
|
1180
|
-
## Errors & Diagnostics
|
|
1181
|
-
|
|
1182
|
-
The SDK raises specialized subclasses of `Error` to improve debuggability during workflow submission and execution:
|
|
1183
|
-
|
|
1184
|
-
| Error | When | Key Extras |
|
|
1185
|
-
| ----- | ---- | ---------- |
|
|
1186
|
-
| `EnqueueFailedError` | HTTP `/prompt` (append/queue) failed | `status`, `statusText`, `url`, `method`, `bodyJSON`, `bodyTextSnippet`, `reason` |
|
|
1187
|
-
| `ExecutionFailedError` | Execution finished but not all mapped outputs arrived | missing outputs context |
|
|
1188
|
-
| `ExecutionInterruptedError` | Server emitted an interruption mid run | cause carries interruption detail |
|
|
1189
|
-
| `MissingNodeError` | A declared bypass or output node is absent | `cause` (optional) |
|
|
1190
|
-
| `WentMissingError` | Job disappeared from queue and no cached output | – |
|
|
1191
|
-
| `FailedCacheError` | Cached output retrieval failed | – |
|
|
1192
|
-
| `CustomEventError` | Server emitted execution error event | event payload in `cause` |
|
|
1193
|
-
| `DisconnectedError` | WebSocket disconnected mid‑execution | – |
|
|
1194
|
-
|
|
1195
|
-
### Error Codes
|
|
1196
|
-
|
|
1197
|
-
Every custom error exposes a stable `code` (enum) to enable branch logic without string matching message text:
|
|
1198
|
-
|
|
1199
|
-
```ts
|
|
1200
|
-
import { ErrorCode, EnqueueFailedError } from "comfyui-node";
|
|
1201
|
-
|
|
1202
|
-
try { /* run call wrapper */ } catch (e) {
|
|
1203
|
-
if ((e as any).code === ErrorCode.ENQUEUE_FAILED) {
|
|
1204
|
-
// inspect structured diagnostics
|
|
1205
|
-
}
|
|
1206
|
-
}
|
|
1207
|
-
```
|
|
1208
|
-
|
|
1209
|
-
### EnqueueFailedError Details
|
|
1210
|
-
|
|
1211
|
-
When the server rejects a workflow submission the SDK now attempts to surface the underlying cause:
|
|
1212
|
-
|
|
1213
|
-
```ts
|
|
1214
|
-
try {
|
|
1215
|
-
await new CallWrapper(api, workflow).run();
|
|
1216
|
-
} catch (e) {
|
|
1217
|
-
if (e instanceof EnqueueFailedError) {
|
|
1218
|
-
console.error('Status:', e.status, e.statusText);
|
|
1219
|
-
console.error('Reason:', e.reason);
|
|
1220
|
-
console.error('Body JSON:', e.bodyJSON);
|
|
1221
|
-
console.error('Snippet:', e.bodyTextSnippet);
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
```
|
|
1225
|
-
|
|
1226
|
-
`reason` is resolved using (in order): `bodyJSON.error`, `bodyJSON.message`, falling back to a truncated textual body (first 500 chars). Raw JSON (if parseable) and a short text snippet are both retained to help rapidly identify mis‑shaped prompts, missing extensions, permission issues or model path problems.
|
|
1227
|
-
|
|
1228
|
-
If the response body is not JSON, `bodyTextSnippet` contains the first 500 characters of the returned text, which is also copied into `reason`.
|
|
1229
|
-
|
|
1230
|
-
These enriched diagnostics are only attached for the enqueue phase; downstream execution issues still rely on event‑level errors.
|
|
1231
|
-
|
|
1232
|
-
### Execution Failure vs Interruption
|
|
1233
|
-
|
|
1234
|
-
- `ExecutionFailedError`: The workflow ran but one or more declared output nodes never produced data (often due to an upstream node error not surfaced as a global event). Revisit your output mappings or inspect per‑node errors.
|
|
1235
|
-
- `ExecutionInterruptedError`: The server (or user action) actively interrupted execution; retrying may succeed if the interruption cause was transient.
|
|
1236
|
-
|
|
1237
|
-
### Persisting & Replaying Builder State
|
|
1238
|
-
|
|
1239
|
-
You can store builder state in a database / job queue:
|
|
1240
|
-
|
|
1241
|
-
```ts
|
|
1242
|
-
const snapshot = builder.toJSON();
|
|
1243
|
-
// later
|
|
1244
|
-
const restored = PromptBuilder.fromJSON(snapshot)
|
|
1245
|
-
.validateOutputMappings();
|
|
1246
|
-
```
|
|
1247
|
-
|
|
1248
|
-
This is useful for deferred execution, cross‑process scheduling, or audit logging of the exact prompt graph sent to the server.
|
|
1249
|
-
|
|
1250
|
-
## Testing & Coverage
|
|
1251
|
-
|
|
1252
|
-
This repository uses Bun's built-in test runner. Common scripts:
|
|
1253
|
-
|
|
1254
|
-
```bash
|
|
1255
|
-
bun test # unit + lightweight integration tests
|
|
1256
|
-
bun run test:real # real server tests (COMFY_REAL=1)
|
|
1257
|
-
bun run test:full # comprehensive real server tests (COMFY_REAL=1 COMFY_FULL=1)
|
|
1258
|
-
bun run coverage # text coverage summary (lines/functions per file)
|
|
1259
|
-
bun run coverage:lcov # generate coverage/lcov.info (for badges or external services)
|
|
1260
|
-
bun run coverage:enforce # generate LCOV then enforce thresholds
|
|
1261
|
-
```
|
|
1262
|
-
|
|
1263
|
-
Environment flags:
|
|
1264
|
-
|
|
1265
|
-
- `COMFY_REAL=1` enables `test/real.integration.spec.ts` (expects a running ComfyUI at `http://localhost:8188` unless overridden via `COMFY_HOST`).
|
|
1266
|
-
- `COMFY_FULL=1` additionally enables the extended `test/real.full.integration.spec.ts` suite.
|
|
1267
|
-
- `COMFY_HOST=http://host:port` to point at a non-default instance.
|
|
1268
|
-
|
|
1269
|
-
Coverage thresholds are enforced by `scripts/coverage-check.ts` (baseline intentionally modest to allow incremental improvement):
|
|
1270
|
-
|
|
1271
|
-
Default thresholds:
|
|
1272
|
-
|
|
1273
|
-
- Lines: `>= 25%`
|
|
1274
|
-
- Functions: `>= 60%`
|
|
1275
|
-
|
|
1276
|
-
Override thresholds ad hoc (CI example):
|
|
1277
|
-
|
|
1278
|
-
```bash
|
|
1279
|
-
COVERAGE_MIN_LINES=30 COVERAGE_MIN_FUNCTIONS=65 bun run coverage:enforce
|
|
1280
|
-
```
|
|
1281
|
-
|
|
1282
|
-
or in PowerShell:
|
|
1283
|
-
|
|
1284
|
-
```powershell
|
|
1285
|
-
$env:COVERAGE_MIN_LINES=30; $env:COVERAGE_MIN_FUNCTIONS=65; bun run coverage:enforce
|
|
1286
|
-
```
|
|
1287
|
-
|
|
1288
|
-
### Improving Coverage
|
|
1289
|
-
|
|
1290
|
-
Current low-coverage areas (see `bun test --coverage` output):
|
|
1291
|
-
|
|
1292
|
-
- `src/client.ts` – large surface; break out helpers & add unit tests for fetch error branches and WebSocket reconnect logic.
|
|
1293
|
-
- `src/call-wrapper.ts` – test error paths (enqueue failure, execution interruption, missing outputs) with mocked `fetch` & event streams.
|
|
1294
|
-
- Feature modules with toleration logic (`monitoring`, `manager`, `terminal`) – add mocks to simulate absent endpoints & successful responses.
|
|
1295
|
-
|
|
1296
|
-
Incremental strategy:
|
|
1297
|
-
|
|
1298
|
-
1. Extract pure helper functions from monolithic classes (e.g., parsing, polling backoff) into modules you can unit test in isolation.
|
|
1299
|
-
2. Add fine-grained tests for error branches (simulate non-200 responses & malformed JSON bodies) to raise line coverage quickly.
|
|
1300
|
-
3. Introduce deterministic mock WebSocket that replays scripted events (connection drop, progress, output) to cover reconnect & event translation.
|
|
1301
|
-
4. Gradually raise `COVERAGE_MIN_LINES` by 5% after each meaningful set of additions.
|
|
1302
|
-
|
|
1303
|
-
Skipping heavy real-image generation: full suite internally tolerates missing models & will skip or soften assertions rather than fail—use it sparingly in CI (nightly job) if runtime is a concern.
|
|
1304
|
-
|
|
1305
|
-
If contributing, please run at least:
|
|
1306
|
-
|
|
1307
|
-
```bash
|
|
1308
|
-
bun test && bun run coverage
|
|
1309
|
-
```
|
|
1310
|
-
|
|
1311
|
-
before opening a PR, and prefer adding tests alongside new feature code.
|
|
1312
|
-
|
|
1313
|
-
## Troubleshooting
|
|
1314
|
-
|
|
1315
|
-
| Symptom | Likely Cause | Fix |
|
|
1316
|
-
| ------- | ------------ | ---- |
|
|
1317
|
-
| `progress_pct` never fires | Only listening to raw `progress` (or run finished instantly) | Subscribe to `progress_pct`; ensure workflow isn't trivially cached / instant |
|
|
1318
|
-
| Empty `images` array | Wrong node id in `.output()` or no `SaveImage` nodes detected | Verify node id in base JSON; omit outputs to let auto-detect run |
|
|
1319
|
-
| `_autoSeeds` missing | No `seed: -1` inputs present | Set seed field explicitly to `-1` on nodes requiring randomization |
|
|
1320
|
-
| Autocomplete missing for sampler | Used `Workflow.from(...)` not `fromAugmented` | Switch to `Workflow.fromAugmented(json)` |
|
|
1321
|
-
| Type not updating after new `.output()` | Captured type alias before adding the call | Recompute `type R = ReturnType<typeof wf.typedResult>` after the last output declaration |
|
|
1322
|
-
| Execution error but no missing outputs | Underlying node error surfaced via `execution_error` event | Listen to `failed` + inspect error / server logs |
|
|
1323
|
-
| Job hangs waiting for output | Declared non-existent node id | Run with fewer outputs or validate JSON; inspect `_nodes` metadata |
|
|
1324
|
-
| Random seed not changing between runs | Provided explicit numeric seed | Use `-1` sentinel or generate a random seed before `.set()` |
|
|
1325
|
-
| Preview frames never appear | Workflow lacks preview-capable nodes (e.g. KSampler) | Confirm server emits `b_preview` events for your graph |
|
|
1326
|
-
| Pool never selects idle client | Mode set to `PICK_LOWEST` with constant queue depth | Switch to `PICK_ZERO` for latency focus |
|
|
1327
|
-
| High-level run returns immediately | Accessed `await api.run(wf)` only (acceptance barrier) | Await `job.done()` or events to completion |
|
|
1328
|
-
|
|
1329
|
-
Diagnostic tips:
|
|
1330
|
-
|
|
1331
|
-
- Enable verbose progress: set `COMFY_PROGRESS_VERBOSE=1` before running the smoke script.
|
|
1332
|
-
- For enqueue failures inspect `EnqueueFailedError` fields (`status`, `reason`, `bodyTextSnippet`).
|
|
1333
|
-
- Use `_aliases` metadata to confirm alias -> node id mapping at runtime.
|
|
1334
|
-
- Log `_autoSeeds` to verify sentinel replacement behavior in batch runs.
|
|
1335
|
-
- If types feel stale, close & reopen the file – TypeScript sometimes caches deep conditional expansions.
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
## Published Smoke Test
|
|
1339
|
-
|
|
1340
|
-
The script `scripts/published-e2e.ts` offers a zero‑config verification of the published npm artifact with **Bun auto‑install**. It dynamically imports `comfyui-node`, builds a small txt2img workflow (optionally an upscale branch), waits for completion and prints output image URLs.
|
|
1341
|
-
|
|
1342
|
-
### Quick Run (Auto‑Install)
|
|
1343
|
-
|
|
1344
|
-
```bash
|
|
1345
|
-
mkdir comfyui-node-smoke
|
|
1346
|
-
cd comfyui-node-smoke
|
|
1347
|
-
curl -o published-e2e.ts https://raw.githubusercontent.com/igorls/comfyui-node/main/scripts/published-e2e.ts
|
|
1348
|
-
COMFY_HOST=http://localhost:8188 bun run published-e2e.ts
|
|
1349
|
-
```
|
|
1350
|
-
|
|
1351
|
-
### Optional Explicit Install
|
|
1352
|
-
|
|
1353
|
-
```bash
|
|
1354
|
-
mkdir comfyui-node-smoke
|
|
1355
|
-
cd comfyui-node-smoke
|
|
1356
|
-
bun add comfyui-node
|
|
1357
|
-
curl -o published-e2e.ts https://raw.githubusercontent.com/igorls/comfyui-node/main/scripts/published-e2e.ts
|
|
1358
|
-
COMFY_HOST=http://localhost:8188 bun run published-e2e.ts
|
|
1359
|
-
```
|
|
1360
|
-
|
|
1361
|
-
### Environment Variables
|
|
1362
|
-
|
|
1363
|
-
| Var | Default | Purpose |
|
|
1364
|
-
| --- | ------- | ------- |
|
|
1365
|
-
| `COMFY_HOST` | `http://127.0.0.1:8188` | Base ComfyUI server |
|
|
1366
|
-
| `COMFY_MODEL` | `SDXL/sd_xl_base_1.0.safetensors` | Checkpoint file name (must exist) |
|
|
1367
|
-
| `COMFY_POSITIVE_PROMPT` | scenic base prompt | Positive text |
|
|
1368
|
-
| `COMFY_NEGATIVE_PROMPT` | `text, watermark` | Negative text |
|
|
1369
|
-
| `COMFY_SEED` | random | Deterministic seed override |
|
|
1370
|
-
| `COMFY_STEPS` | `8` | Sampling steps |
|
|
1371
|
-
| `COMFY_CFG` | `2` | CFG scale |
|
|
1372
|
-
| `COMFY_SAMPLER` | `dpmpp_sde` | Sampler name |
|
|
1373
|
-
| `COMFY_SCHEDULER` | `sgm_uniform` | Scheduler name |
|
|
1374
|
-
| `COMFY_TIMEOUT_MS` | `120000` | Overall timeout (ms) |
|
|
1375
|
-
| `COMFY_UPSCALE` | unset | If set, adds RealESRGAN upscale branch |
|
|
1376
|
-
| `COMFY_MONITOR` | unset | If set, attempt to enable Crystools system monitor & log first event |
|
|
1377
|
-
| `COMFY_MONITOR_STRICT` | unset | With monitor enabled, fail (exit 5) if no events received |
|
|
1378
|
-
|
|
1379
|
-
Exit codes: 0 success, 1 import failure, 2 timeout, 3 enqueue failure, 4 other error, 5 monitor strict failure.
|
|
1380
|
-
|
|
1381
|
-
### Rationale
|
|
1382
|
-
|
|
1383
|
-
Ensures the published `dist` is coherent and functional in a clean consumer environment; can later be wired into CI behind an opt‑in flag (e.g. `E2E_PUBLISHED=1`).
|
|
1384
|
-
|
|
1385
|
-
### Future
|
|
1386
|
-
|
|
1387
|
-
Possible enhancement: GitHub Action that spins up a ComfyUI container, runs the smoke test, and archives generated images as artifacts.
|
|
1388
|
-
|
|
1389
|
-
## Contributing
|
|
1390
|
-
|
|
1391
|
-
Issues and PRs welcome. Please include focused changes and tests where sensible. Adhere to existing coding style and keep feature surfaces minimal & cohesive.
|
|
1392
|
-
|
|
1393
|
-
## License
|
|
1394
|
-
|
|
1395
|
-
MIT – see `LICENSE`.
|