comfy-ts 0.3.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +349 -255
  2. package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
  3. package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
  4. package/dist/cli.js +3969 -128
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1208 -170
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +449 -115
  9. package/dist/index.d.ts +449 -115
  10. package/dist/index.js +1200 -171
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-Io8Xea0L.js → run-tui-BFhba_oG.js} +744 -665
  13. package/dist/run-tui-BFhba_oG.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +66 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +67 -0
  19. package/examples/comfy-cloud/sdk.d.ts +122674 -0
  20. package/guide-for-agents.md +166 -0
  21. package/package.json +7 -3
  22. package/src/cli/comfy-ts-cli.ts +19 -2
  23. package/src/cli/gen.ts +21 -12
  24. package/src/cli/tui/components/Header.tsx +5 -0
  25. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +52 -7
  27. package/src/cli/tui/components/StatusBar.tsx +10 -4
  28. package/src/cli/tui/components/TreePanel.tsx +15 -2
  29. package/src/cli/tui/components/TuiApp.tsx +26 -3
  30. package/src/cli/tui/discoverWorkflows.ts +79 -0
  31. package/src/cli/tui/protocolImagePainter.ts +54 -18
  32. package/src/cli/tui/run-tui.tsx +55 -24
  33. package/src/cli/tui/state/ExecSt.ts +4 -1
  34. package/src/cli/tui/state/HostSt.ts +123 -1
  35. package/src/cli/tui/state/LogsSt.ts +107 -0
  36. package/src/cli/tui/state/PreviewSt.ts +173 -23
  37. package/src/cli/tui/state/SettingsSt.ts +48 -21
  38. package/src/cli/tui/state/TreeSt.ts +30 -6
  39. package/src/cli/tui/state/TuiSt.ts +27 -3
  40. package/src/cli/tui/state/WorkflowsSt.ts +16 -1
  41. package/src/host/ComfyHost.ts +241 -71
  42. package/src/host/ComfyManager.ts +10 -9
  43. package/src/host/ComfyUploader.ts +1 -2
  44. package/src/host/ResilientWebsocket.ts +3 -1
  45. package/src/host/hostUrl.ts +59 -0
  46. package/src/host/loraManagerApi.ts +5 -4
  47. package/src/index.ts +20 -1
  48. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  49. package/src/litegraph/LiteGraphGroup.ts +9 -7
  50. package/src/litegraph/LiteGraphJSON.ts +34 -13
  51. package/src/litegraph/LiteGraphLink.ts +32 -2
  52. package/src/litegraph/LiteGraphNode.ts +18 -33
  53. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  54. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  55. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  56. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  57. package/src/litegraph/expandSubgraphs.ts +352 -0
  58. package/src/litegraph/normalizeWorkflow.ts +141 -0
  59. package/src/runner/ComfyExecution.ts +4 -5
  60. package/src/runner/ComfyWorkflow.ts +2 -2
  61. package/src/runner/ComfyWsApi.ts +12 -1
  62. package/src/runner/wsBinaryFrame.ts +48 -0
  63. package/src/sdk-generator/Primitives.ts +6 -24
  64. package/src/sdk-generator/comfy-api-json.ts +3 -1
  65. package/src/sdk-generator/inputWidgetKind.ts +179 -0
  66. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  67. package/src/ssh-host-manager/ssh-manager.ts +0 -15
  68. package/src/state.ts +13 -2
  69. package/src/utils/ansi.ts +7 -0
  70. package/src/utils/mojibake.ts +60 -0
  71. package/dist/log-CdfgILde.js +0 -10
  72. package/dist/log-CdfgILde.js.map +0 -1
  73. package/dist/run-tui-Io8Xea0L.js.map +0 -1
package/README.md CHANGED
@@ -1,325 +1,406 @@
1
1
  # comfy-ts
2
2
 
3
- > Type-safe ComfyUI companion for TypeScript. Connect to any number of ComfyUI
4
- > hosts, get ONE generated SDK per host (global `Comfy.<HostNs>.*` namespaces),
5
- > build workflows in code with full autocomplete, execute them over websocket,
6
- > get your images back. Plus a terminal UI to tweak and re-run any workflow.
3
+ _the ultimate ComfyUI toolkit for TypeScript: `SDK` + `CLI` + `TUI` + agent guide_
7
4
 
8
5
  [![CI](https://github.com/rvion/comfy-ts/actions/workflows/ci.yml/badge.svg)](https://github.com/rvion/comfy-ts/actions/workflows/ci.yml)
9
6
  [![npm version](https://img.shields.io/npm/v/comfy-ts.svg)](https://www.npmjs.com/package/comfy-ts)
10
7
 
11
- ## Table of contents
12
-
13
- - [Goals](#goals)
14
- - [Install](#install)
15
- - [Quick start](#quick-start)
16
- - [The per-host typed SDK](#the-per-host-typed-sdk)
17
- - [Vars: tweak and re-run](#vars-tweak-and-re-run)
18
- - [The TUI](#the-tui)
19
- - [The sidekick CLI](#the-sidekick-cli)
20
- - [Examples](#examples)
21
- - [The `.comfy-ts/` folder](#the-comfy-ts-folder)
22
- - [Feature status](#feature-status)
23
- - [DX goodies](#dx-goodies)
24
- - [Related projects](#related-projects)
25
-
26
- ## Goals
27
-
28
- 1. **Create and execute workflows from TypeScript**, including uploading and
29
- retrieving assets, with smart abstractions leaning on content addressing
30
- (uploads are hash-named and deduped before any byte is sent).
31
- 2. **Fully type-safe, per host.** Every host you connect to gets its own
32
- generated SDK: node inputs, model names, samplers, loras, embeddings are
33
- literal types **from that actual install**.
34
- 3. **Ecosystem discovery codegen**: typed unions of every custom node,
35
- plugin, and model known to the ComfyUI-Manager registry.
36
- 4. **Import both ComfyUI JSON formats**: `api.json` (prompt) and
37
- `workflow.json` (litegraph graph) into code.
38
- 5. **Export both formats**: `api.json` for execution, plus an easy-to-read,
39
- autolayouted `workflow.json` you can drag into the ComfyUI editor.
40
- 6. **Local and remote instances**: same API whether Comfy runs next to you
41
- or on a GPU box over ssh.
42
- 7. **A sidekick CLI**: codegen and an interactive TUI, without writing a line
43
- of code.
44
-
45
- ## Install
8
+ **Everything ComfyUI, from TypeScript.** Build workflows in code with
9
+ autocomplete on every node and model of your exact install. Run them on any
10
+ host, from the box under your desk to a cloud GPU, and get the images
11
+ straight back into your code. Drive them from a terminal UI with live
12
+ latent previews. Let scripts and agents discover and install whatever the
13
+ ecosystem offers. Import and export both ComfyUI JSON formats. One library,
14
+ the whole pipeline.
15
+
16
+ **Jump to:**
17
+ [⚡ 60 second start](#-60-second-start) ·
18
+ [🧩 SDK](#-the-sdk-workflows-as-code) ·
19
+ [🧬 Codegen](#-the-codegen-nothing-else-comes-close) ·
20
+ [🎛️ App mode & vars](#-app-mode--vars-knobs-on-everything) ·
21
+ [🖥️ TUI](#-the-tui) ·
22
+ [⌨️ CLI](#-the-cli) ·
23
+ [🌍 Comfy Cloud & hosts](#-hosts-local-lan-comfy-cloud-any-provider) ·
24
+ [🔌 Ecosystem](#-ecosystem-discovery-and-install) ·
25
+ [🤖 Agents](#-for-ai-agents) ·
26
+ [📚 Examples](#-examples) ·
27
+ [🧱 Trust](#-a-lib-you-can-trust-made-to-last)
28
+
29
+ ## What's inside
30
+
31
+ | piece | what it gives you |
32
+ | ---------------- | ---------------------------------------------------------------------------------------- |
33
+ | 🧩 **the SDK** | build and run workflows in code, typed down to the model names of your exact machine |
34
+ | ⌨️ **the CLI** | one command codegens a full typed SDK for any host, local or remote cloud |
35
+ | 🖥️ **the TUI** | drive every workflow from the terminal: knobs, drafts, queue, live latent previews |
36
+ | 🤖 **agent tools** | typed discovery and install across the whole custom node ecosystem, built for automation |
37
+ | 🔁 **JSON, both ways** | import and export `api.json` and `workflow.json`, drag your code onto the Comfy canvas |
38
+
39
+ ## ⚡ 60 second start
46
40
 
47
41
  ```bash
48
42
  bun add comfy-ts # or npm / pnpm / yarn
49
43
  ```
50
44
 
51
- Runs under Bun and node ≥ 20. Ships dual ESM/CJS.
52
-
53
- ## Quick start
54
-
55
- A workflow module (from [`examples/01-txt2img.cflow.ts`](examples/01-txt2img.cflow.ts)):
56
-
57
45
  ```ts
58
- import { ComfyTS, v } from 'comfy-ts'
46
+ // myFirstWorkflow.ts
47
+ import { ComfyTS } from 'comfy-ts'
59
48
 
60
49
  const comfy = ComfyTS.create()
61
50
  const host = comfy.host({ id: 'my-gpu', host: '127.0.0.1', port: 8188 })
62
- await host.loadSchemaFromCache() // offline import; run() connects lazily
51
+ await host.connect() // fetches the schema, writes your typed SDK
63
52
 
64
- export const txt2img = host.defineWorkflow({
65
- id: 'txt2img',
66
- vars: {
67
- prompt: v.text('a cozy house in a snowy forest, warm windows'),
68
- seed: v.seed(42),
69
- steps: v.int(20, { min: 1, max: 60 }),
70
- size: v.size({ width: 512, height: 512 }),
71
- },
72
- build: (b, vars) => {
73
- // b is typed: Comfy.MyGpu.Builder, autocomplete on EVERY node of THIS host
53
+ const txt2img = host.defineWorkflow({
54
+ vars: {},
55
+ build: (b) => {
56
+ // b is typed: autocomplete on EVERY node of THIS host
74
57
  const ckpt = b.CheckpointLoaderSimple({ ckpt_name: 'SD1.5\\v1-5-pruned-emaonly.ckpt' })
75
58
  const samples = b.KSampler({
76
59
  model: ckpt,
77
- positive: b.CLIPTextEncode({ clip: ckpt, text: vars.prompt }),
60
+ positive: b.CLIPTextEncode({ clip: ckpt, text: 'a cozy house in a snowy forest' }),
78
61
  negative: b.CLIPTextEncode({ clip: ckpt, text: 'blurry, low quality' }),
79
- latent_image: b.EmptyLatentImage({ width: vars.size.width, height: vars.size.height, batch_size: 1 }),
80
- seed: vars.seed,
81
- steps: vars.steps,
82
- cfg: 7,
83
- sampler_name: 'euler',
84
- scheduler: 'normal',
85
- denoise: 1,
62
+ latent_image: b.EmptyLatentImage({ width: 512, height: 512, batch_size: 1 }),
63
+ seed: 42, steps: 20, cfg: 7,
64
+ sampler_name: 'euler', scheduler: 'normal', denoise: 1,
86
65
  })
87
66
  b.SaveImage({ images: b.VAEDecode({ samples, vae: ckpt }) })
88
67
  },
89
68
  })
90
69
 
91
- export default txt2img
92
-
93
- // standalone run, skipped when a driver (e.g. the TUI) imports this module
94
- if (import.meta.main) {
95
- const execution = await txt2img.run({ log: true }) // ▶ [██████░░] 71% · KSampler · 10s
96
- for (const img of execution.images) console.log(img.absPath) // downloaded outputs
97
- host.disconnect()
98
- }
70
+ const execution = await txt2img.run({ log: true }) // ▶ [██████░░] 71% · KSampler · 10s
71
+ for (const img of execution.images) console.log(img.absPath) // downloaded outputs
72
+ host.disconnect()
99
73
  ```
100
74
 
101
- First time on a host, generate its schema cache and typed SDK once:
102
-
103
- ```bash
104
- bunx comfy-ts gen --id my-gpu --host http://127.0.0.1:8188
75
+ ```sh
76
+ $ bun myFirstWorkflow.ts
77
+ ▶ [████████████████] 100% · SaveImage · 12s
78
+ .comfy-ts/outputs/txt2img_00001.png
105
79
  ```
106
80
 
107
- (or replace `loadSchemaFromCache()` with `await host.connect()`, which fetches
108
- the schema and writes the SDK itself). One tsconfig line activates the
109
- generated types:
81
+ One tsconfig line activates the generated types:
110
82
 
111
83
  ```jsonc
112
84
  { "include": ["src", ".comfy-ts/hosts/**/sdk.d.ts"] }
113
85
  ```
114
86
 
115
- Before the first codegen, builder methods fall back to permissive base types.
116
- Your code compiles either way; the types sharpen once the generated sdk is in
117
- scope.
87
+ No codegen yet? Everything still compiles on permissive base types, and
88
+ sharpens the moment the generated sdk lands. Runs under Bun and node ≥ 20,
89
+ dual ESM/CJS.
90
+
91
+ ## 🧩 The SDK: workflows as code
92
+
93
+ The best embedded DSL we know how to build, distilled from years of writing
94
+ typed DSLs in TypeScript. Fast inference, clever tricks, zero ceremony.
95
+ Wrong workflow? Compile error, before ComfyUI ever sees the graph. Writing
96
+ workflows in code gets so comfortable you may catch yourself experimenting
97
+ here rather than in the visual editor. The tricks this section showcases:
98
+
99
+ - [Pass the node, skip the slot](#pass-the-node-skip-the-slot)
100
+ - [Nested or flat, your call](#nested-or-flat-your-call)
101
+ - [Lambda inputs: autocomplete only what fits](#lambda-inputs-autocomplete-only-what-fits)
102
+ - [auto(): let the graph wire itself](#auto-let-the-graph-wire-itself)
103
+ - [Content-addressed uploads](#content-addressed-uploads)
104
+ - [Problems, not crashes](#problems-not-crashes)
118
105
 
119
- ## The per-host typed SDK
106
+ Wondering how any of this can exist? It all rests on
107
+ [the codegen](#-the-codegen-nothing-else-comes-close) below.
120
108
 
121
- Each host gets its own namespace inside the global `Comfy` namespace, plus a
122
- registry entry, so several hosts coexist in one codebase:
109
+ ### Pass the node, skip the slot
110
+
111
+ When a node has exactly ONE output of the expected type, pass the node
112
+ itself:
113
+
114
+ ```ts
115
+ const ckpt = b.CheckpointLoaderSimple({ ckpt_name: 'SD1.5\\v1-5-pruned-emaonly.ckpt' })
116
+ const samples = b.KSampler({ model: ckpt /* … */ }) // instead of model: ckpt._MODEL
117
+ b.VAEDecode({ samples, vae: ckpt }) // same ckpt node, VAE output this time
118
+ ```
119
+
120
+ `ckpt` carries one MODEL, one CLIP and one VAE output, so it slots into all
121
+ three kinds of inputs directly, and refuses inputs it cannot feed.
122
+
123
+ ### Nested or flat, your call
124
+
125
+ The same graph writes flat (a const per node) or nested (the code shaped
126
+ like the graph). Mix freely; nested is often the practical form for small
127
+ branches:
128
+
129
+ ```ts
130
+ // flat
131
+ const latent = b.EmptyLatentImage({ width: 512, height: 512, batch_size: 1 })
132
+ const samples = b.KSampler({ latent_image: latent /* … */ })
133
+ b.SaveImage({ images: b.VAEDecode({ samples, vae: ckpt }) })
134
+
135
+ // nested
136
+ b.SaveImage({
137
+ images: b.VAEDecode({
138
+ samples: b.KSampler({
139
+ latent_image: b.EmptyLatentImage({ width: 512, height: 512, batch_size: 1 }),
140
+ /* … */
141
+ }),
142
+ vae: ckpt,
143
+ }),
144
+ })
145
+ ```
146
+
147
+ ### Lambda inputs: autocomplete only what fits
148
+
149
+ Any input accepts a lambda. Its parameter is the builder NARROWED to the
150
+ nodes able to produce the expected type, so autocomplete proposes only what
151
+ can actually plug in:
152
+
153
+ ```ts
154
+ b.KSampler({
155
+ // n lists ONLY conditioning producers: CLIPTextEncode and friends
156
+ positive: (n) => n.CLIPTextEncode({ clip: ckpt, text: 'a cozy house' }),
157
+ /* … */
158
+ })
159
+ ```
160
+
161
+ ### auto(): let the graph wire itself
162
+
163
+ Leave a slot blank and comfy-ts wires the most recent node producing the
164
+ right type:
165
+
166
+ ```ts
167
+ import { auto } from 'comfy-ts'
168
+
169
+ const samples = b.KSampler({ latent_image: auto() /* picks the latest LATENT producer */ })
170
+ ```
171
+
172
+ Handy in quick scripts; prefer explicit wiring in code meant to be read.
173
+
174
+ ### Content-addressed uploads
175
+
176
+ Uploads are hash-named and deduped against the host before any byte moves.
177
+ Run the same img2img a hundred times, the input image travels once:
178
+
179
+ ```ts
180
+ build: async (b, vars, wf) => {
181
+ const img = new MediaImage({ path: asAbsolutePath(vars.image) })
182
+ const loaded = await img.loadInWorkflow_viaLoadImageNode(wf) // hash-named, deduped
183
+ b.KSampler({ latent_image: b.VAEEncode({ pixels: loaded, vae: ckpt }) /* … */ })
184
+ }
185
+ ```
186
+
187
+ ### Problems, not crashes
188
+
189
+ Invalid graphs accumulate precise messages in `workflow.problems` before
190
+ ComfyUI ever sees them: missing required inputs, type mismatches, each named
191
+ with the node and field.
192
+
193
+ ## 🧬 The codegen: nothing else comes close
194
+
195
+ Not "a ComfyUI type package" someone published once. One command reads YOUR
196
+ host and writes a full SDK for it:
197
+
198
+ ```bash
199
+ bunx comfy-ts gen --id my-gpu --host http://127.0.0.1:8188
200
+ # → .comfy-ts/hosts/my-gpu/{object_info.json, embeddings.json, sdk.d.ts}
201
+ ```
123
202
 
124
203
  ```ts
125
204
  declare global {
126
205
  namespace Comfy {
127
- namespace MyGpu { // ← generated from THIS host's /object_info
128
- interface IN { … } // input types per node
129
- interface OUT { … } // output slots per node
206
+ namespace MyGpu { // ← generated from THIS host
130
207
  interface Builder { … } // one factory per node
131
208
  interface Union { … } // every enum: model names, samplers, loras, …
132
- // + Node, Slots, Accepts, Producer, Embeddings, Schemas, NodeType
133
209
  }
134
- interface Hosts { 'my-gpu': MyGpu.Sdk }
135
210
  }
136
211
  }
137
212
  ```
138
213
 
139
- `workflow.builder` resolves through `Comfy.Hosts`, so a workflow created on
140
- `comfy.host({ id: 'my-gpu', … })` is typed with **that** host's nodes and
141
- models. Unknown host ids fall back to permissive base types.
142
-
143
- ## Vars: tweak and re-run
144
-
145
- `host.defineWorkflow({ vars, build })` is the re-run contract: declare the
146
- knobs once, and `build` re-executes with the current values on every `run()`,
147
- producing a fresh graph each time.
214
+ - **Literal types from the actual install.** `ckpt_name` only accepts
215
+ checkpoints that machine really has; samplers, schedulers, loras and
216
+ embeddings are unions of the real values.
217
+ - **Custom nodes are first-class.** Every installed pack lands in the
218
+ builder: `b['rmbg.RMBG']` autocompletes like any core node.
219
+ - **One namespace per host, many hosts per codebase.** A workflow written
220
+ against `my-gpu` cannot silently reference a model that only exists on
221
+ `my-laptop`.
222
+ - **Never blocking.** Before the first codegen everything compiles on
223
+ permissive base types, and sharpens the moment the generated sdk lands.
224
+ - **Browsable.** The generated file is real TypeScript;
225
+ `bunx comfy-ts outline` shows it section by section.
226
+ - **See it for real: the Comfy Cloud catalog.**
227
+ [`examples/comfy-cloud/sdk.d.ts`](examples/comfy-cloud/sdk.d.ts) is a full
228
+ generated SDK for [Comfy Cloud](https://cloud.comfy.org) (5.9MB, 3574
229
+ nodes), committed so you can browse it and typecheck graphs against it
230
+ without any host.
231
+ [`examples/05-comfy-cloud.cflow.ts`](examples/05-comfy-cloud.cflow.ts)
232
+ runs against it live: `url` + `apiKey` host config, one env var, images
233
+ back in seconds.
234
+
235
+ ## 🎛️ App mode & vars: knobs on everything
236
+
237
+ Vars turn a workflow module into a small APP: declare the tweakable parts
238
+ once (`import { v } from 'comfy-ts'`) and `build` re-executes with current
239
+ values on every `run()`. The TUI renders vars as its UI, scripts set them
240
+ programmatically, drafts snapshot them. One module, many setups, re-runnable
241
+ forever instead of a one-shot script.
148
242
 
149
243
  ```ts
150
- export const asset = host.defineWorkflow({
151
- id: 'asset',
244
+ export const txt2img = host.defineWorkflow({
245
+ id: 'txt2img',
152
246
  vars: {
153
- prompt: v.text('spherical sheep'),
154
- seed: v.seed(517),
155
- steps: v.int(8, { min: 1, max: 40 }),
156
- size: v.size({ width: 1024, height: 1024 }), // SDXL-bucket presets + WxH custom
157
- removeBg: v.toggle(true, 'remove bg'),
158
- ratio: v.choice(['square', 'wide'] as const, 'square'),
159
- loras: v.loras(/krea-?2/i), // multi-select, resolved against the host's real loras
247
+ prompt: v.text('a cozy house in a snowy forest, warm windows'),
248
+ seed: v.seed(42),
249
+ steps: v.int(20, { min: 1, max: 60 }),
250
+ size: v.size({ width: 512, height: 512 }),
160
251
  },
161
- build: async (b, vars, wf) => { /* typed builder code reading vars.* */ },
252
+ build: (b, vars) => { /* same graph, reading vars.* */ },
162
253
  })
163
254
 
164
- await asset.run({ log: true })
165
- asset.vars.seed.randomize()
166
- await asset.run({ log: true })
255
+ await txt2img.run({ log: true })
256
+ txt2img.vars.seed.randomize()
257
+ await txt2img.run({ log: true }) // fresh graph, fresh image
167
258
  ```
168
259
 
169
- - var kinds: `v.text` / `v.int` / `v.float` / `v.seed` / `v.toggle` /
170
- `v.choice` / `v.size` / `v.loras` / `v.prompt`.
171
- - `v.loras` takes a RegExp (resolved against the host's real lora list at
172
- define time) or any dynamic list such as `host.schema.getLoras(/xl/i)`;
173
- `activeLoras(vars.loras)` normalizes the selection to
174
- `{ lora_name, strength_model, strength_clip }[]`, ready for a standard
175
- `LoraLoader` chain.
176
- - `v.prompt` builds a structured `{ positive, negative }`: `//` lines are
177
- comments (stripped), `- ` lines become the negative prompt, and
178
- `v.prompt({ loraKeywordsFrom: lorasVar })` prefixes the active loras'
179
- trigger keywords.
180
- - `v.seed` is a mode plus a number (`+ N` / `- N` / `= N` / `? N`) and advances
181
- itself after every run, so a queued batch gets distinct seeds.
182
- - `vars` may be a lambda that RECEIVES `v`, giving cross-referencing vars one
183
- scope with the host's own types injected:
260
+ | var kind | superpower |
261
+ | ----------------------- | --------------------------------------------------------------------------------- |
262
+ | `v.seed` | mode + number (`+ N` `- N` `= N` `? N`), advances itself: queued runs differ |
263
+ | `v.prompt` | structured text: `//` comments stripped, `- ` lines become the negative prompt |
264
+ | `v.loras` | RegExp resolved against the host's REAL lora list, fully typed, multi-select |
265
+ | `v.text` `v.int` `v.float` `v.toggle` `v.choice` `v.size` | the everyday knobs, ranges included |
184
266
 
185
- ```ts
186
- export const asset = host.defineWorkflow({
187
- id: 'asset',
188
- vars: (v) => {
189
- const loras = v.loras(/krea-?2/i)
190
- return { loras, prompt: v.prompt('a cozy house', { loraKeywordsFrom: loras }) }
191
- },
192
- build: async (b, vars, wf) => { /* … */ },
193
- })
194
- ```
195
- - `build` may be async (image uploads etc., the third `wf` param feeds
196
- `MediaImage` upload helpers).
197
- - `run()` opens with `await host.connect()`, which is idempotent (cached ready
198
- promise, one websocket per host, ever). Modules import OFFLINE from the
199
- schema cache and connect lazily on first run.
200
- - `ComfyTS.create()` returns the existing global instance or creates it, and
201
- `comfy.host({ id })` is a registry (same id, same instance back). Many
202
- workflow modules can safely import each other, or be co-imported by the TUI,
203
- in one process.
204
- - fast start: `connect()` reuses the `.comfy-ts/` schema cache when younger
205
- than 24h (`connect({ schema: 'refresh' })` forces a re-fetch,
206
- `{ schema: 'cache' }` never fetches).
207
-
208
- Name your workflow modules `*.cflow.ts` and the TUI finds them.
209
-
210
- ## The TUI
267
+ `vars` can be a lambda receiving `v` so vars reference each other:
268
+ `v.prompt('a cozy house', { loraKeywordsFrom: loras })` prefixes the active
269
+ loras' trigger keywords. Name the file `*.cflow.ts` and the TUI finds it.
270
+
271
+ ## 🖥️ The TUI
272
+
273
+ ![the comfy-ts TUI: workflow tree, typed knobs, live latent preview](screenshots/tui-screen-1.png)
211
274
 
212
275
  ```bash
213
- bunx comfy-ts tui examples/ # a dir: scans **/*.cflow.ts
214
- bunx comfy-ts tui my.cflow.ts # a file: scans its folder, file preselected
215
- bunx comfy-ts tui # no arg: scans cwd
276
+ bunx comfy-ts tui
216
277
  ```
217
278
 
218
- ```
219
- ┌ comfy-ts ┐┌ (w)orkflow ─┐┌ (d)raft ─┐┌ (h)ost ──────────────────┐
220
- │ comfy-ts ││ 01-txt2img ││ default ││ windows-1 (127.0.0.1:8085)│
221
- └──────────┘└─────────────┘└──────────┘└──────────────────────────┘
222
- ┌ (t)ree ────────────┐┌ (v)ars ─────────────────────────────┐┌ (p)review ─────┐
223
- │ ▾ 01-txt2img ││ ▸ prompt [text] a cozy house in a… ││ │
224
- │ default ││ seed [seed] ? 42 ││ ▄▓▓▒▒░▄▄▓▒░░ │
225
- │ night-take ││ steps [int] 20 ││ ▓▒░▄▄▓▓▒▒░▄▓ │
226
- │ ▸ 04-krea2-turbo ││ size [size] 512×512 ││ live latent / │
227
- │ ││ loras [loras] (2) styleA, styleB ││ last output │
228
- └────────────────────┘└──────────────────────────────────────┘└────────────────┘
229
- ▶ [██████░░░░░░░░░░] 42% · KSampler · 12s · queue 1
230
- ↑↓ select · ← tree · ⏎/→ edit
231
- r run · s reroll+run · e rename draft · o open image · c/C copy wf/api · q quit
232
- ```
279
+ No argument needed: it finds every `*.cflow.ts` under your project AND the
280
+ examples bundled with the package, so the first launch is never empty. Pass
281
+ a folder or a module to scan just that. Keyboard-first, a persistent keybar
282
+ showing every available key.
283
+
284
+ | panel | what it does |
285
+ | ------------ | -------------------------------------------------------------------------------- |
286
+ | **(t)ree** | every `*.cflow.ts` found, with named drafts (var snapshots) nested under it |
287
+ | **(v)ars** | edit every knob: inline numbers, real multiline editor, fuzzy pickers, lora overlay with per-lora strengths |
288
+ | **(p)review** | LIVE latent previews mid-run, then the final image, painted REAL on iTerm2/WezTerm/VS Code |
289
+ | **(h)ost** | node/lora/embedding counts, live queue, re-codegen, restart Comfy, interrupt |
290
+
291
+ `r` runs, `s` rerolls the seed and runs, `o` opens the output, `c`/`C` copy
292
+ workflow.json / api.json. Press `r` mid-run and it QUEUES with the values as
293
+ they are right now. Drafts autosave: reopening lands you where you left off.
233
294
 
234
- Keyboard-first, three panels, a persistent keybar showing every key available
235
- in the current mode. Every panel and header box is titled with the key that
236
- opens it, and no key is advertised twice.
237
-
238
- - **(t)ree** (left): every `*.cflow.ts` workflow found, with its drafts nested
239
- under it. ↑↓ move, ← folds, → unfolds a workflow or hops into the vars panel
240
- from a draft row, ⏎ loads a workflow or a draft directly.
241
- - **(v)ars** (center): the knobs of the loaded workflow. You are always in a
242
- draft (`default` auto-active per workflow); edits autosave to
243
- `.comfy-ts/drafts/`, `e` renames the active draft inline, `d` opens the
244
- drafts overlay (load / new / duplicate / delete). Drafts are named var-value
245
- snapshots, so one workflow carries many setups, and reopening a workflow
246
- lands back in the draft you left it in.
247
- - **(p)review** (right, `p` cycles native → ansi → off): LIVE latent previews
248
- while a run is in flight (launch ComfyUI with `--preview-method auto`), then
249
- the final output. On iTerm2, WezTerm and VS Code terminals "native" paints
250
- the REAL image over the panel; everywhere else it renders truecolor
251
- half-blocks.
252
- - **(h)ost** (header box): node / lora / embedding counts, live server queue
253
- length, and actions — re-run the SDK codegen, restart ComfyUI, clear the
254
- pending queue, interrupt the current run.
255
-
256
- Editing a var opens the right surface for its kind: numbers edit inline
257
- (readline word ops included), text and prompt vars open a real multiline editor
258
- (⏎ saves, ⇧⏎ or ⌥⏎ inserts a newline, ⌘←→ and ⌃A/⌃E move by logical line, ⌥↑↓
259
- move a line, ⌘/ toggles a `// ` comment), choice and size open a
260
- fuzzy-filterable picker (type `WxH` for a custom size), loras open a
261
- multi-select overlay (type to filter, space ticks, ←→ steps strengths, ⌃A/⌃N
262
- tick/untick all filtered, ⌃K assigns that lora's trigger keywords). A seed row
263
- takes `+` `-` `=` `?` to set its mode and `*` to reroll. If the host has the
264
- [ComfyUI-Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager)
265
- extension installed, the preview panel shows the selected lora's preview image
266
- while you browse; without it, everything else keeps working.
267
-
268
- Global keys: `r` run, `s` reroll seed + run, `o` open the last output in the
269
- OS image viewer (full resolution), `c` copy workflow.json, `C` copy api.json,
270
- `⌃R` run from any mode, `q` quit. Pressing `r` while a run is in flight QUEUES
271
- another prompt on the server (built from the values as they are right now), and
272
- the progress bar, latent preview and outputs follow each queued run in turn.
273
-
274
- ## The sidekick CLI
295
+ ## ⌨️ The CLI
275
296
 
276
297
  ```bash
277
298
  bunx comfy-ts gen --id my-gpu --host http://127.0.0.1:8188
278
299
  # → .comfy-ts/hosts/my-gpu/{object_info.json, embeddings.json, sdk.d.ts}
279
300
 
280
- bunx comfy-ts outline # what's inside that 2MB sdk.d.ts?
281
- bunx comfy-ts outline --section Builder --lines 40
301
+ bunx comfy-ts outline # what's inside that 2MB sdk.d.ts?
302
+ bunx comfy-ts tui # your *.cflow.ts + bundled examples
303
+ bunx comfy-ts tui [dir | module] # scan just that
304
+ ```
305
+
306
+ Any reachable host: the box under your desk or a GPU machine across the
307
+ network, same command, same output.
308
+
309
+ ## 🌍 Hosts: local, LAN, Comfy Cloud, any provider
282
310
 
283
- bunx comfy-ts tui [dir | module.cflow.ts] # see above
311
+ Every Comfy is supported, through one identical API. Same mechanism, same
312
+ codegen, same typed SDK, same TUI, whatever answers the protocol:
313
+
314
+ ```ts
315
+ // the box you are on
316
+ comfy.host({ id: 'local', host: '127.0.0.1', port: 8188 })
317
+
318
+ // another machine on your network
319
+ comfy.host({ id: 'gpu-tower', host: '192.168.1.5', port: 8188 })
320
+
321
+ // official Comfy Cloud: same everything, plus an api key
322
+ comfy.host({ id: 'comfy-cloud', url: 'https://cloud.comfy.org', apiKey: process.env.COMFY_CLOUD_API_KEY })
323
+
324
+ // any third party provider: paste its base url; extra auth headers welcome
325
+ comfy.host({ id: 'runpod', url: 'https://xxxx-8188.proxy.runpod.net' })
326
+ comfy.host({ id: 'modal', url: 'https://you--comfy.modal.run', headers: { 'Modal-Key': '…', 'Modal-Secret': '…' } })
284
327
  ```
285
328
 
286
- ## Examples
329
+ [Comfy Cloud](https://cloud.comfy.org) is first-class: the key rides
330
+ `X-API-Key` on every request and the websocket, outputs download through the
331
+ signed-url redirect, live latent previews stream into the TUI, and the whole
332
+ cloud catalog ships as a committed, browsable SDK
333
+ ([`examples/comfy-cloud/sdk.d.ts`](examples/comfy-cloud/sdk.d.ts), run it
334
+ with [example 05](examples/05-comfy-cloud.cflow.ts)).
335
+
336
+ Reaching a Comfy running on another one of your machines:
287
337
 
288
- Runnable from the repo (they expect a live ComfyUI). Every example is a
289
- `*.cflow.ts` workflow module: run it standalone with bun, or point the TUI at
290
- `examples/`.
338
+ - **ssh tunnel**: `ssh -N -L 8188:127.0.0.1:8188 you@gpu-box`, then
339
+ `host: '127.0.0.1', port: 8188` as if it were local (`ssh -R` does the
340
+ reverse: expose YOUR Comfy to the remote box).
341
+ - **tailscale**: `tailscale serve 8188` on the box gives a stable https url
342
+ for `url:`; plain tailnet hostnames work with `host:` too.
343
+ - **cloudflared**: `cloudflared tunnel --url http://127.0.0.1:8188` prints a
344
+ temporary public https url, paste it into `url:`.
291
345
 
292
- | example | shows |
293
- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
294
- | [`examples/01-txt2img.cflow.ts`](examples/01-txt2img.cflow.ts) | typed builder, vars, execution, downloaded outputs |
295
- | [`examples/02-img2img-upload.cflow.ts`](examples/02-img2img-upload.cflow.ts) | hash-named deduped upload, img2img, async build |
296
- | [`examples/03-export-workflow-json.cflow.ts`](examples/03-export-workflow-json.cflow.ts) | OFFLINE graph building, export api.json + readable workflow.json |
297
- | [`examples/04-krea2-turbo-t2i.cflow.ts`](examples/04-krea2-turbo-t2i.cflow.ts) | a real pipeline: krea2 turbo + `v.loras` multi-select stack (standard LoraLoader chain) + RMBG cutout → transparent png |
346
+ ## 🔌 Ecosystem discovery and install
298
347
 
299
- ## The `.comfy-ts/` folder
348
+ The whole ComfyUI-Manager registry, mirrored into generated types: every
349
+ known custom node pack, plugin title and model is a typed union.
300
350
 
301
- Every repo using comfy-ts gets one `.comfy-ts/` folder at its root:
351
+ ```ts
352
+ await host.installCustomNodeByTitle('ComfyUI Impact Pack') // autocompletes across the ecosystem
353
+ await host.manager.installModel(modelInfo)
354
+ ```
355
+
356
+ A script (or an agent) can look at a workflow, see what is missing, and
357
+ install it by name with the compiler checking the spelling. Install
358
+ endpoints currently target the Manager v2 API; v3 moved them behind a queue
359
+ API and support is being ground down (see the feature table).
360
+
361
+ ## 🤖 For AI agents
362
+
363
+ comfy-ts is built to be driven by agents as much as by people. After
364
+ installing, one line in your `CLAUDE.md` teaches your agent the whole
365
+ library:
302
366
 
303
367
  ```
304
- .comfy-ts/
305
- hosts/<host-id>/object_info.json raw schema dump from the host
306
- hosts/<host-id>/embeddings.json embeddings list
307
- hosts/<host-id>/sdk.d.ts the generated typed SDK (per host)
308
- outputs/ images and workflows produced by runs
309
- drafts/<module-basename>/<name>.json named var snapshots from the TUI
310
- settings.json TUI settings (preview mode, last draft)
311
- lora-keywords.json trigger keywords you assigned to loras
312
- cache/ lora preview images, refetchable
368
+ @./node_modules/comfy-ts/guide-for-agents.md
313
369
  ```
314
370
 
315
- Everything under `.comfy-ts/` is local state: gitignore it. `hosts/` in
316
- particular is a full dump of that machine's models, loras and paths (often
317
- ~10MB per host), so committing it publishes your setup — regenerate it instead
318
- with `bun run gen:sdk` or a first `connect()`. In a PRIVATE repo, committing
319
- `hosts/` is what buys you typed CI. This repo does not commit it, and the
320
- library is built to typecheck with no generated SDK on disk at all.
371
+ ## 🔁 JSON, both ways
372
+
373
+ - `workflow.toApiJson()`: the executable prompt format.
374
+ - `await workflow.toWorkflowJson()`: an AUTOLAYOUTED litegraph file. Drop it
375
+ on the ComfyUI canvas and see the graph you wrote in code, readably laid
376
+ out.
377
+ - `host.importApiJson` / `host.importWorkflowJson`: both directions, covered
378
+ by round-trip tests. Newer editor features (subgraphs) are the current
379
+ compat frontier: we sweep every official Comfy-Org template against our
380
+ schemas to grind that gap down.
321
381
 
322
- ## Feature status
382
+ ## 📚 Examples
383
+
384
+ Every example is a runnable `*.cflow.ts` module: run it with bun, or point
385
+ the TUI at `examples/`.
386
+
387
+ | example | shows |
388
+ | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
389
+ | [`01-txt2img`](examples/01-txt2img.cflow.ts) | typed builder, vars, execution, downloaded outputs |
390
+ | [`02-img2img-upload`](examples/02-img2img-upload.cflow.ts) | hash-named deduped upload, img2img, async build |
391
+ | [`03-export-workflow-json`](examples/03-export-workflow-json.cflow.ts) | OFFLINE graph building, export api.json + readable workflow.json |
392
+ | [`04-krea2-turbo-t2i`](examples/04-krea2-turbo-t2i.cflow.ts) | a real pipeline: krea2 turbo, lora stack, RMBG cutout → transparent png |
393
+ | [`05-comfy-cloud`](examples/05-comfy-cloud.cflow.ts) | the same code on Comfy Cloud: `url` + `apiKey` host, typechecked against the committed catalog SDK |
394
+
395
+ ## 🗂️ The `.comfy-ts/` folder
396
+
397
+ One folder of local state per consumer repo: `hosts/` (schema dumps + the
398
+ generated sdk per host), `outputs/`, `drafts/`, TUI settings, lora keywords.
399
+ Gitignore all of it. `hosts/` is a full dump of that machine's models and
400
+ paths (~10MB), so committing it publishes your setup; in a PRIVATE repo,
401
+ committing it is what buys you typed CI.
402
+
403
+ ## ✅ Feature status
323
404
 
324
405
  | feature | status |
325
406
  | -------------------------------------------------------------- | :----: |
@@ -334,23 +415,36 @@ library is built to typecheck with no generated SDK on disk at all.
334
415
  | import api.json into a live workflow | ✅ |
335
416
  | import workflow.json (litegraph → api conversion) | ✅ |
336
417
  | sidekick CLI (`gen`, `outline`, `tui`) | ✅ |
418
+ | cloud hosts: `url` + `X-API-Key` auth, Comfy Cloud ran live | ✅ |
337
419
  | ComfyUI-Manager registry mirror + Known\* ecosystem unions | ✅ |
338
- | install custom nodes / models via ComfyUI-Manager | ✅ |
420
+ | install custom nodes / models via ComfyUI-Manager (v2 API) | 🔶 |
339
421
  | locality-aware media retrieval fast-path (local vs remote) | 🔶 |
340
422
  | content-addressed local asset cache | 🔶 |
341
423
 
342
424
  ✅ working and exercised · 🔶 partial / in progress
343
425
 
344
- ## DX goodies
345
-
346
- - **`auto<T>()`**: leave a slot blank; comfy-ts wires the most recent node
347
- producing the right type.
348
- - **functional inputs**: any input accepts `(producers) => value`, with
349
- `producers` narrowed to the nodes able to output the expected type.
350
- - **`HasSingle` shortcuts**: pass a whole node wherever it has exactly one
351
- output of the expected type (`model: ckpt` instead of `ckpt._MODEL`).
352
- - **problems, not crashes**: invalid graphs accumulate precise messages in
353
- `workflow.problems` before Comfy ever sees them.
426
+ ## 🧱 A lib you can trust, made to last
427
+
428
+ The glitter above sits on boring foundations:
429
+
430
+ - **Strict TypeScript everywhere.** `strict` + `noUncheckedIndexedAccess`,
431
+ no `any`, every remaining cast individually justified in a reviewed
432
+ whitelist.
433
+ - **A hard CI gate on every commit.** Typecheck, zero-warning lint (a
434
+ warning is fixed or the rule is disabled on purpose, never ignored),
435
+ format check, import hygiene, the full headless test suite.
436
+ - **Runtime validation with arktype.** Wire messages and JSON formats are
437
+ schema-validated. When ComfyUI drifts faster than the schemas, failures
438
+ are logged loud, never swallowed.
439
+ - **Codegen you can regenerate, never hand-edit.** The SDK, the manager
440
+ unions and the snapshot tests around them all rebuild from source data
441
+ with one command each.
442
+ - **A compat grind loop, not compat hope.** The full official template
443
+ corpus (~780 workflows from Comfy-Org) is mirrored locally and swept
444
+ against our schemas on demand, so upstream format changes surface as a
445
+ failing report line, not as your broken pipeline.
446
+ - **Boring packaging.** Dual ESM/CJS, Bun and node ≥ 20, `src/` shipped in
447
+ the tarball for go-to-definition.
354
448
 
355
449
  ## Related projects
356
450