comfy-ts 0.4.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 (59) 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 +1167 -172
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +401 -115
  9. package/dist/index.d.ts +401 -115
  10. package/dist/index.js +1159 -173
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-SDSJo1Qf.js → run-tui-BFhba_oG.js} +132 -609
  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 +6 -1
  22. package/src/cli/comfy-ts-cli.ts +19 -2
  23. package/src/cli/gen.ts +21 -12
  24. package/src/cli/tui/components/TreePanel.tsx +15 -2
  25. package/src/cli/tui/discoverWorkflows.ts +79 -0
  26. package/src/cli/tui/run-tui.tsx +51 -23
  27. package/src/cli/tui/state/HostSt.ts +2 -3
  28. package/src/cli/tui/state/TreeSt.ts +30 -6
  29. package/src/cli/tui/state/TuiSt.ts +21 -3
  30. package/src/cli/tui/state/WorkflowsSt.ts +15 -1
  31. package/src/host/ComfyHost.ts +203 -77
  32. package/src/host/ComfyManager.ts +10 -9
  33. package/src/host/ComfyUploader.ts +1 -2
  34. package/src/host/ResilientWebsocket.ts +3 -1
  35. package/src/host/hostUrl.ts +59 -0
  36. package/src/host/loraManagerApi.ts +5 -4
  37. package/src/index.ts +20 -1
  38. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  39. package/src/litegraph/LiteGraphGroup.ts +9 -7
  40. package/src/litegraph/LiteGraphJSON.ts +34 -13
  41. package/src/litegraph/LiteGraphLink.ts +32 -2
  42. package/src/litegraph/LiteGraphNode.ts +18 -33
  43. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  44. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  45. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  46. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  47. package/src/litegraph/expandSubgraphs.ts +352 -0
  48. package/src/litegraph/normalizeWorkflow.ts +141 -0
  49. package/src/runner/ComfyExecution.ts +4 -5
  50. package/src/runner/ComfyWorkflow.ts +2 -2
  51. package/src/runner/wsBinaryFrame.ts +48 -0
  52. package/src/sdk-generator/Primitives.ts +6 -24
  53. package/src/sdk-generator/comfy-api-json.ts +3 -1
  54. package/src/sdk-generator/inputWidgetKind.ts +179 -0
  55. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  56. package/src/state.ts +13 -2
  57. package/dist/log-CdfgILde.js +0 -10
  58. package/dist/log-CdfgILde.js.map +0 -1
  59. package/dist/run-tui-SDSJo1Qf.js.map +0 -1
@@ -1,565 +1,79 @@
1
- import { t as logError } from "./log-CdfgILde.js";
2
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { a as setLoraKeyword, c as stripAnsi, i as getLoraKeyword, n as LorasVar, o as extractErrorMessage, r as PromptVar, t as DefinedWorkflow, u as logError } from "./DefinedWorkflow-O3ynII3Y.js";
2
+ import { spawn } from "node:child_process";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
5
  import { basename, dirname, join, resolve } from "pathe";
4
6
  import { createHash } from "node:crypto";
5
- import { pathToFileURL } from "node:url";
6
- import { Box, Text, render, useApp, useInput, useStdin } from "ink";
7
- import { action, makeAutoObservable, makeObservable, observable, reaction, runInAction } from "mobx";
7
+ import { type } from "arktype";
8
8
  import sharp from "sharp";
9
9
  import { imageMeta } from "image-meta";
10
+ import { makeAutoObservable, observable, reaction, runInAction } from "mobx";
11
+ import { Box, Text, render, useApp, useInput, useStdin } from "ink";
10
12
  import { observer } from "mobx-react-lite";
11
13
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
- import { spawn } from "node:child_process";
13
- import { type } from "arktype";
14
14
  //#region src/cli/tui-env.ts
15
15
  const COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
16
16
  //#endregion
17
- //#region src/vars/loraKeywords.ts
17
+ //#region src/cli/tui/discoverWorkflows.ts
18
18
  /**
19
- * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras
20
- * overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at
21
- * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
22
- * and must survive a cache wipe). Observable map: overlay rows re-render on
23
- * assignment. Keys are the RAW lora names (folder/file.safetensors).
19
+ * recursive scan for the workflow-module naming convention. Entries BELOW a
20
+ * node_modules segment are skipped: packaged examples arrive via
21
+ * bundledExamplesDir (symlinked layouts like pnpm would otherwise list them
22
+ * twice, un-deduped, as the user's own files), and third-party packages
23
+ * shipping *.cflow.ts are not this project's workflows. A scan root that is
24
+ * ITSELF inside node_modules still works (the filter is relative to the root).
24
25
  */
25
- const keywords = observable.map();
26
- let loaded = false;
27
- function filePath() {
28
- return join(comfyts.baseFolder, "lora-keywords.json");
29
- }
30
- function loadOnce() {
31
- if (loaded) return;
32
- loaded = true;
33
- const path = filePath();
34
- if (!existsSync(path)) return;
35
- try {
36
- const raw = JSON.parse(readFileSync(path, "utf8"));
37
- if (raw == null || typeof raw !== "object") return;
38
- runInAction(() => {
39
- for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
40
- });
41
- } catch (e) {
42
- logError(`[loraKeywords] unreadable ${path}: ${String(e)}`);
43
- }
44
- }
45
- function getLoraKeyword(name) {
46
- loadOnce();
47
- return keywords.get(name) ?? "";
48
- }
49
- /** empty keyword deletes the entry; every set writes the file (tiny, rare) */
50
- function setLoraKeyword(name, keyword) {
51
- loadOnce();
52
- const trimmed = keyword.trim();
53
- runInAction(() => {
54
- if (trimmed === "") keywords.delete(name);
55
- else keywords.set(name, trimmed);
56
- });
57
- const path = filePath();
58
- try {
59
- mkdirSync(dirname(path), { recursive: true });
60
- writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
61
- } catch (e) {
62
- logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
63
- }
26
+ function scanCflowFiles(dir) {
27
+ return readdirSync(dir, { recursive: true }).map((f) => String(f)).filter((f) => !f.split("/").includes("node_modules")).map((f) => join(dir, f)).filter((f) => f.endsWith(".cflow.ts") || f.endsWith(".cflow.tsx")).sort();
64
28
  }
65
- //#endregion
66
- //#region src/vars/ComfyVars.ts
67
- /**
68
- * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
69
- * time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is
70
- * the one Out-specialized var (string in, PromptValue out); the split keeps
71
- * outValue() cast-free.
72
- */
73
- var ComfyVarBase = class {
74
- constructor(defaultValue, label) {
75
- this.defaultValue = defaultValue;
76
- this.label = label;
77
- this.value = defaultValue;
78
- makeObservable(this, {
79
- value: observable,
80
- set: action,
81
- reset: action,
82
- parse: action,
83
- loadJSON: action
84
- });
85
- }
86
- set(value) {
87
- this.value = value;
88
- return this;
89
- }
90
- /** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */
91
- toJSON() {
92
- return this.value;
93
- }
94
- /**
95
- * restore a value produced by toJSON() (drafts). The cast is sanctioned:
96
- * drafts are our own round-trip, subclasses re-validate via set().
97
- */
98
- loadJSON(value) {
99
- return this.set(value);
100
- }
101
- reset() {
102
- this.value = this.defaultValue;
103
- return this;
104
- }
105
- /** how the value renders in a var list */
106
- display() {
107
- return String(this.value);
108
- }
109
- /** the string the inline editor starts from (round-trips through parse) */
110
- toEditBuffer() {
111
- return String(this.value);
112
- }
113
- /** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */
114
- afterRun() {}
115
- };
116
- /** the standard var: the graph consumes the stored value AS-IS (Out = T) */
117
- var ComfyVar = class extends ComfyVarBase {
118
- outValue() {
119
- return this.value;
120
- }
121
- };
122
- var TextVar = class extends ComfyVar {
123
- constructor(..._args) {
124
- super(..._args);
125
- this.kind = "text";
126
- }
127
- parse(raw) {
128
- this.set(raw);
129
- return true;
130
- }
131
- };
132
- const commentLineRe = /^\s*\/\//;
133
- const negativeLineRe = /^\s*- (.*)$/;
134
- /**
135
- * prompt text with editor comforts, all resolved at BUILD time (the editor and
136
- * drafts keep the raw text):
137
- * - `//` lines are COMMENTS — stripped
138
- * - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,
139
- * comma-joined into `.negative`
140
- * - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords
141
- * (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —
142
- * `injectedKeywords()` is public so the TUI can PREVIEW the injection.
143
- */
144
- var PromptVar = class extends ComfyVarBase {
145
- constructor(defaultValue, promptOpts = {}) {
146
- super(defaultValue, promptOpts.label);
147
- this.promptOpts = promptOpts;
148
- this.kind = "text";
149
- }
150
- parse(raw) {
151
- this.set(raw);
152
- return true;
153
- }
154
- static isCommentLine(line) {
155
- return commentLineRe.test(line);
156
- }
157
- static isNegativeLine(line) {
158
- return negativeLineRe.test(line);
159
- }
160
- /** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */
161
- injectedKeywords() {
162
- const src = this.promptOpts.loraKeywordsFrom;
163
- if (src == null) return [];
164
- return [...new Set(src.activeNames().map(getLoraKeyword).filter((k) => k !== ""))];
165
- }
166
- outValue() {
167
- const pos = [];
168
- const neg = [];
169
- for (const line of this.value.split("\n")) {
170
- if (commentLineRe.test(line)) continue;
171
- const m = negativeLineRe.exec(line);
172
- if (m != null) {
173
- const text = (m[1] ?? "").trim();
174
- if (text !== "") neg.push(text);
175
- } else pos.push(line);
176
- }
177
- const body = pos.join("\n").trim();
178
- const keywords = this.injectedKeywords();
179
- return {
180
- positive: keywords.length === 0 ? body : body === "" ? keywords.join(", ") : `${keywords.join(", ")}, ${body}`,
181
- negative: neg.join(", ")
182
- };
183
- }
184
- };
185
- var IntVar = class extends ComfyVar {
186
- constructor(defaultValue, opts = {}) {
187
- super(defaultValue, opts.label);
188
- this.opts = opts;
189
- this.kind = "int";
190
- }
191
- set(value) {
192
- const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
193
- return super.set(clamped);
194
- }
195
- parse(raw) {
196
- const n = Number(raw);
197
- if (Number.isNaN(n)) return false;
198
- this.set(n);
199
- return true;
200
- }
201
- };
202
- var FloatVar = class extends ComfyVar {
203
- constructor(defaultValue, opts = {}) {
204
- super(defaultValue, opts.label);
205
- this.opts = opts;
206
- this.kind = "float";
207
- }
208
- set(value) {
209
- return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
210
- }
211
- parse(raw) {
212
- const n = Number(raw);
213
- if (Number.isNaN(n)) return false;
214
- this.set(n);
215
- return true;
216
- }
217
- };
218
- /**
219
- * a seed is a MODE + a number. `value` stays a plain number (what the graph
220
- * consumes); `mode` decides how it advances after each run (afterRun()):
221
- * `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.
222
- * The number shown is always the seed the NEXT run will use.
223
- */
224
- var SeedVar = class extends ComfyVar {
225
- constructor(defaultValue = 0, label) {
226
- super(defaultValue, label);
227
- this.kind = "seed";
228
- this.mode = "=";
229
- makeObservable(this, {
230
- mode: observable,
231
- setMode: action,
232
- randomize: action,
233
- advance: action
234
- });
235
- }
236
- setMode(mode) {
237
- this.mode = mode;
238
- return this;
239
- }
240
- randomize() {
241
- return this.set(Math.floor(Math.random() * 2 ** 32));
242
- }
243
- set(value) {
244
- return super.set(Math.max(0, Math.floor(value)));
245
- }
246
- /** move the seed to what the NEXT run should use, per mode */
247
- advance() {
248
- if (this.mode === "+") return this.set(this.value + 1);
249
- if (this.mode === "-") return this.set(this.value - 1);
250
- if (this.mode === "?") return this.randomize();
251
- return this;
252
- }
253
- afterRun() {
254
- this.advance();
255
- }
256
- /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
257
- parse(raw) {
258
- const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/);
259
- if (m == null) return false;
260
- const modeChar = m[1];
261
- const numStr = m[2];
262
- if (modeChar == null && numStr == null) return false;
263
- this.setMode(modeChar == null ? "=" : modeChar);
264
- if (numStr != null) this.set(Number(numStr));
265
- return true;
266
- }
267
- display() {
268
- return `${this.mode} ${this.value}`;
269
- }
270
- toEditBuffer() {
271
- return `${this.mode} ${this.value}`;
272
- }
273
- toJSON() {
274
- return {
275
- mode: this.mode,
276
- value: this.value
277
- };
278
- }
279
- loadJSON(value) {
280
- if (typeof value === "number") return this.set(value);
281
- if (value != null && typeof value === "object") {
282
- const o = value;
283
- if (o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?") this.setMode(o.mode);
284
- if (typeof o.value === "number") this.set(o.value);
285
- }
286
- return this;
287
- }
288
- };
289
- var ToggleVar = class extends ComfyVar {
290
- constructor(..._args2) {
291
- super(..._args2);
292
- this.kind = "toggle";
293
- }
294
- toggle() {
295
- return this.set(!this.value);
296
- }
297
- parse(raw) {
298
- if (raw !== "true" && raw !== "false") return false;
299
- this.set(raw === "true");
300
- return true;
301
- }
302
- display() {
303
- return this.value ? "ON" : "OFF";
304
- }
305
- };
306
- var ChoiceVar = class extends ComfyVar {
307
- constructor(choices, defaultValue, label) {
308
- super(defaultValue, label);
309
- this.choices = choices;
310
- this.kind = "choice";
311
- }
312
- next(delta = 1) {
313
- const nextIx = (this.choices.indexOf(this.value) + delta + this.choices.length) % this.choices.length;
314
- return this.set(this.choices[nextIx] ?? this.value);
315
- }
316
- parse(raw) {
317
- const hit = this.choices.find((c) => c === raw);
318
- if (hit == null) return false;
319
- this.set(hit);
320
- return true;
321
- }
322
- };
323
29
  /**
324
- * multi-select lora stack over a DYNAMIC options list — a RegExp resolves
325
- * against the host's loras at define time (DefinedWorkflow calls bindHost),
326
- * or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never
327
- * a hardcoded inventory. Selection is empty by default.
30
+ * the examples/ folder shipped in the npm tarball, resolved from THIS module's
31
+ * own location (NEVER cwd): walking up to the nearest NAMED package.json finds
32
+ * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/cli.js and
33
+ * from this repo's src/cli/tui/. Returns null when the examples are absent
34
+ * (a consumer may prune the folder) or when the nearest named package is not
35
+ * comfy-ts (the lib was inlined into someone else's bundle — its examples are
36
+ * not on disk); no package.json all the way up is a broken install and throws.
328
37
  */
329
- var LorasVar = class LorasVar extends ComfyVar {
330
- constructor(optionsSource, initial = {}, label) {
331
- super(initial, label);
332
- this.optionsSource = optionsSource;
333
- this.kind = "loras";
334
- this.prev = {};
335
- this.resolvedOptions = null;
336
- }
337
- get options() {
338
- if (!(this.optionsSource instanceof RegExp)) return this.optionsSource;
339
- if (this.resolvedOptions == null) throw new Error(`v.loras(${String(this.optionsSource)}) is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list otherwise)`);
340
- return this.resolvedOptions;
341
- }
342
- /** DefinedWorkflow binds the host at define time: a RegExp source resolves here.
343
- * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
344
- * values of the SAME object_info enum the generated E_LoraName union comes from */
345
- bindHost(host) {
346
- if (!(this.optionsSource instanceof RegExp)) return;
347
- this.resolvedOptions = host.schema.getLoras(this.optionsSource);
348
- }
349
- get names() {
350
- return [...this.options];
351
- }
352
- /** loras currently ON (PromptVar keyword prefixing consumes this) */
353
- activeNames() {
354
- return this.names.filter((n) => this.isOn(n));
355
- }
356
- isOn(name) {
357
- const s = this.value[name];
358
- return s != null && s !== false;
359
- }
360
- toggleItem(name) {
361
- const cur = this.value[name];
362
- if (cur == null || cur === false) return this.set({
363
- ...this.value,
364
- [name]: this.prev[name] ?? true
365
- });
366
- this.prev[name] = cur;
367
- return this.set({
368
- ...this.value,
369
- [name]: false
370
- });
371
- }
372
- /** step both strengths by delta (true becomes 1 first); no-op when off */
373
- adjustItem(name, delta) {
374
- const cur = this.value[name];
375
- if (cur == null || cur === false) return this;
376
- const step = (n) => Math.max(0, Math.round((n + delta) * 100) / 100);
377
- const next = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur);
378
- return this.set({
379
- ...this.value,
380
- [name]: next
381
- });
382
- }
383
- /** compact per-item strength label for lists */
384
- strengthLabel(name) {
385
- const s = this.value[name];
386
- if (s == null || s === false) return "";
387
- if (s === true) return "1.00";
388
- if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`;
389
- return s.toFixed(2);
390
- }
391
- parse(raw) {
392
- try {
393
- const parsed = JSON.parse(raw);
394
- if (typeof parsed !== "object" || parsed == null || Array.isArray(parsed)) return false;
395
- this.set(parsed);
396
- return true;
397
- } catch {
398
- return false;
399
- }
400
- }
401
- /** short human name: subfolder + extension stripped */
402
- static shortName(name) {
403
- return (name.split(/[\\/]/).pop() ?? name).replace(/\.safetensors$/, "");
404
- }
405
- /** tick (true) or untick (false) every lora in `names` (default: all options) */
406
- setAll(on, names = this.options) {
407
- const next = { ...this.value };
408
- for (const name of names) {
409
- const cur = next[name];
410
- if (on) {
411
- if (cur == null || cur === false) next[name] = this.prev[name] ?? true;
412
- } else {
413
- if (cur != null && cur !== false) this.prev[name] = cur;
414
- next[name] = false;
38
+ function bundledExamplesDir(moduleUrl = import.meta.url) {
39
+ let dir = dirname(fileURLToPath(moduleUrl));
40
+ let prev = "";
41
+ while (dir !== prev) {
42
+ const pkgPath = join(dir, "package.json");
43
+ if (existsSync(pkgPath)) {
44
+ let pkg = {};
45
+ try {
46
+ pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
47
+ } catch {}
48
+ if (pkg.name === "comfy-ts") {
49
+ const examples = join(dir, "examples");
50
+ return existsSync(examples) ? examples : null;
415
51
  }
52
+ if (pkg.name != null) return null;
416
53
  }
417
- return this.set(next);
418
- }
419
- display() {
420
- const on = this.activeNames();
421
- if (on.length === 0) return `(0/${this.options.length}) none`;
422
- return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(", ")}`;
423
- }
424
- };
425
- /** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */
426
- const DEFAULT_SIZE_PRESETS = [
427
- {
428
- label: "1:1 square",
429
- width: 1024,
430
- height: 1024
431
- },
432
- {
433
- label: "4:3 landscape",
434
- width: 1152,
435
- height: 896
436
- },
437
- {
438
- label: "3:4 portrait",
439
- width: 896,
440
- height: 1152
441
- },
442
- {
443
- label: "3:2 landscape",
444
- width: 1216,
445
- height: 832
446
- },
447
- {
448
- label: "2:3 portrait",
449
- width: 832,
450
- height: 1216
451
- },
452
- {
453
- label: "16:9 widescreen",
454
- width: 1344,
455
- height: 768
456
- },
457
- {
458
- label: "9:16 tall",
459
- width: 768,
460
- height: 1344
461
- }
462
- ];
463
- /** width/height picker: presets + free `WxH` entry */
464
- var SizeVar = class extends ComfyVar {
465
- constructor(defaultValue = {
466
- width: 1024,
467
- height: 1024
468
- }, presets = DEFAULT_SIZE_PRESETS, label) {
469
- super(defaultValue, label);
470
- this.presets = presets;
471
- this.kind = "size";
472
- }
473
- /** accepts '1024x768' / '1024×768' / a preset label */
474
- parse(raw) {
475
- const m = raw.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/);
476
- if (m != null) {
477
- this.set({
478
- width: Number(m[1]),
479
- height: Number(m[2])
480
- });
481
- return true;
482
- }
483
- const preset = this.presets.find((p) => p.label === raw.trim());
484
- if (preset != null) {
485
- this.set({
486
- width: preset.width,
487
- height: preset.height
488
- });
489
- return true;
490
- }
491
- return false;
492
- }
493
- display() {
494
- const { width, height } = this.value;
495
- const hit = this.presets.find((p) => p.width === width && p.height === height);
496
- return `${width}×${height}${hit ? ` (${hit.label})` : ""}`;
54
+ prev = dir;
55
+ dir = dirname(dir);
497
56
  }
498
- };
499
- /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size */
500
- const v = {
501
- text: (defaultValue, label) => new TextVar(defaultValue, label),
502
- prompt: (defaultValue, opts = {}) => new PromptVar(defaultValue, opts),
503
- int: (defaultValue, opts = {}) => new IntVar(defaultValue, opts),
504
- float: (defaultValue, opts = {}) => new FloatVar(defaultValue, opts),
505
- seed: (defaultValue = 0, label) => new SeedVar(defaultValue, label),
506
- toggle: (defaultValue, label) => new ToggleVar(defaultValue, label),
507
- choice: (choices, defaultValue, label) => new ChoiceVar(choices, defaultValue, label),
508
- loras: (options, initial = {}, label) => new LorasVar(options, initial, label),
509
- size: (defaultValue, opts = {}) => new SizeVar(defaultValue, opts.presets, opts.label)
510
- };
511
- function varValues(vars) {
512
- const out = {};
513
- for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue();
514
- return out;
515
- }
516
- //#endregion
517
- //#region src/vars/DefinedWorkflow.ts
518
- /** type predicate (not a cast): a VarsSpec is a plain record, never callable */
519
- function isVarsThunk(vars) {
520
- return typeof vars === "function";
57
+ throw new Error(`[comfy-ts tui] no package.json found walking up from ${fileURLToPath(moduleUrl)}`);
521
58
  }
522
59
  /**
523
- * a re-runnable workflow definition: `build` re-executes per run with the
524
- * current var values, so every run gets a fresh, deterministic graph.
60
+ * PURE merge of the scan with the packaged examples (headless-tested). An
61
+ * explicit target keeps its scope only. Bundled files ALWAYS group under the
62
+ * bundled section, also when the scan already found them (repo dev: ./examples
63
+ * is under cwd) — dedupe relies on the caller passing realpath-normalized
64
+ * strings on both sides.
525
65
  */
526
- var DefinedWorkflow = class {
527
- constructor(host, spec) {
528
- this.host = host;
529
- this.spec = spec;
530
- this.lastWorkflow = null;
531
- this.lastExecution = null;
532
- this.vars = isVarsThunk(spec.vars) ? spec.vars(v) : spec.vars;
533
- for (const [, varDef] of this.entries()) varDef.bindHost?.(this.host);
534
- }
535
- /** [name, var] pairs, for drivers that enumerate the knobs */
536
- entries() {
537
- return Object.entries(this.vars);
538
- }
539
- /**
540
- * build a fresh graph from the CURRENT var values (no send). `p.advance`
541
- * (set by run()) fires each var's afterRun() right after snapshotting the
542
- * values — atomically, before any await — so the graph uses this run's seed
543
- * while the var moves to the next (queued runs get distinct seeds; a bare
544
- * build() for copy/export never advances).
545
- */
546
- async build(p = {}) {
547
- const wf = this.host.workflow({ id: this.spec.id });
548
- const values = varValues(this.vars);
549
- if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun();
550
- await this.spec.build(wf.builder, values, wf);
551
- this.lastWorkflow = wf;
552
- return wf;
553
- }
554
- /** build a fresh graph from the current var values, send it, wait for outputs.
555
- * connects first (idempotent) — modules can import offline from the schema cache */
556
- async run(settings = {}) {
557
- await this.host.connect();
558
- const execution = await (await this.build({ advance: true })).run(settings);
559
- this.lastExecution = execution;
560
- return execution;
561
- }
562
- };
66
+ function mergeWorkflowSources(p) {
67
+ if (p.explicitTarget) return {
68
+ files: p.scanned,
69
+ bundled: /* @__PURE__ */ new Set()
70
+ };
71
+ const bundled = new Set(p.bundledFiles);
72
+ return {
73
+ files: [...p.scanned.filter((f) => !bundled.has(f)), ...p.bundledFiles],
74
+ bundled
75
+ };
76
+ }
563
77
  //#endregion
564
78
  //#region src/cli/tui/findDefinedWorkflow.ts
565
79
  /**
@@ -604,19 +118,6 @@ async function imageBufferToAnsi(input, p) {
604
118
  return rows.join("\n");
605
119
  }
606
120
  //#endregion
607
- //#region src/utils/extractErrorMessage.ts
608
- /** Extracts an error message from an exception stuff. */
609
- const extractErrorMessage = (error) => {
610
- if (error instanceof Error) return error.message;
611
- if (error === null) return "null";
612
- if (typeof error === "string") return error;
613
- if (typeof error === "object") {
614
- if ("message" in error && typeof error.message === "string") return error.message;
615
- return JSON.stringify(error);
616
- }
617
- return String(error);
618
- };
619
- //#endregion
620
121
  //#region src/cli/tui/state/PreviewSt.ts
621
122
  /** OSC 1337 support: the panel can show REAL images instead of half-blocks */
622
123
  function protocolCapable() {
@@ -1729,15 +1230,22 @@ const TreePanel = observer((p) => {
1729
1230
  }),
1730
1231
  tree.rows.map((row, ix) => {
1731
1232
  const sel = focused && ix === tree.ix;
1233
+ if (row.kind === "section") return /* @__PURE__ */ jsxs(Text, {
1234
+ color: "gray",
1235
+ dimColor: true,
1236
+ wrap: "truncate",
1237
+ children: ["─ ", row.label]
1238
+ }, `section·${row.label}`);
1732
1239
  if (row.kind === "workflow") {
1733
1240
  const arrow = row.hasDrafts ? row.expanded ? "▾" : "▸" : " ";
1241
+ const marker = row.error != null ? "✗" : row.current ? "●" : " ";
1734
1242
  return /* @__PURE__ */ jsxs(Text, {
1735
1243
  inverse: sel,
1736
- color: row.current ? "green" : void 0,
1244
+ color: row.error != null ? "red" : row.current ? "green" : void 0,
1737
1245
  wrap: "truncate",
1738
1246
  children: [
1739
1247
  arrow,
1740
- row.current ? "●" : " ",
1248
+ marker,
1741
1249
  " ",
1742
1250
  row.name
1743
1251
  ]
@@ -2806,7 +2314,7 @@ var HostSt = class {
2806
2314
  this.spinTimer = spin;
2807
2315
  let ok = false;
2808
2316
  try {
2809
- const res = await fetch(`${host.getServerHostHTTP()}/api/prompt`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
2317
+ const res = await host.fetch("/prompt", { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
2810
2318
  res.body?.cancel();
2811
2319
  ok = res.ok;
2812
2320
  } catch {
@@ -2921,30 +2429,6 @@ var HostSt = class {
2921
2429
  }
2922
2430
  };
2923
2431
  //#endregion
2924
- //#region src/utils/ansi.ts
2925
- const codes = {
2926
- bold: [1, 22],
2927
- underline: [4, 24],
2928
- red: [31, 39],
2929
- green: [32, 39],
2930
- yellow: [33, 39],
2931
- blue: [34, 39],
2932
- greenBright: [92, 39]
2933
- };
2934
- function styler(open = "", close = "") {
2935
- const fn = (s) => open + s + close;
2936
- return new Proxy(fn, { get(_target, prop) {
2937
- const c = codes[prop];
2938
- if (c == null) throw new Error(`unknown ansi style: ${prop}`);
2939
- return styler(`${open}\x1b[${c[0]}m`, `\x1b[${c[1]}m${close}`);
2940
- } });
2941
- }
2942
- styler();
2943
- const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]|\x1b[A-Za-z]/g;
2944
- function stripAnsi(s) {
2945
- return s.replace(ANSI_RE, "");
2946
- }
2947
- //#endregion
2948
2432
  //#region src/utils/mojibake.ts
2949
2433
  const CP1252_REVERSE = {
2950
2434
  "€": 128,
@@ -3111,13 +2595,12 @@ function loraPreviewKey(name) {
3111
2595
  * (server-relative). Returns null when the extension is absent (404/network).
3112
2596
  */
3113
2597
  async function fetchLoraPreviewMap(host) {
3114
- const base = host.getServerHostHTTP();
3115
2598
  const map = /* @__PURE__ */ new Map();
3116
2599
  const pageSize = 500;
3117
2600
  for (let page = 1; page <= 20; page++) {
3118
2601
  let res;
3119
2602
  try {
3120
- res = await fetch(`${base}/api/lm/loras/list?page=${page}&page_size=${pageSize}`);
2603
+ res = await host.fetch(`/api/lm/loras/list?page=${page}&page_size=${pageSize}`, {}, { apiPrefix: false });
3121
2604
  } catch {
3122
2605
  return null;
3123
2606
  }
@@ -3176,7 +2659,7 @@ async function fetchLoraPreviewBytes(host, previewUrl) {
3176
2659
  const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash("sha1").update(previewUrl).digest("hex")}`);
3177
2660
  if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath));
3178
2661
  try {
3179
- const res = await fetch(`${host.getServerHostHTTP()}${previewUrl}`);
2662
+ const res = await host.fetch(previewUrl, {}, { apiPrefix: false });
3180
2663
  if (!res.ok) return null;
3181
2664
  const ct = res.headers.get("content-type") ?? "";
3182
2665
  if (ct !== "" && !ct.startsWith("image/")) return null;
@@ -3580,7 +3063,15 @@ var TreeSt = class {
3580
3063
  this.st.drafts.version;
3581
3064
  const w = this.st.workflows;
3582
3065
  const rows = [];
3066
+ let sectionPushed = false;
3583
3067
  for (const file of w.files) {
3068
+ if (!sectionPushed && w.bundled.has(file)) {
3069
+ rows.push({
3070
+ kind: "section",
3071
+ label: "comfy-ts examples"
3072
+ });
3073
+ sectionPushed = true;
3074
+ }
3584
3075
  const current = file === w.currentPath;
3585
3076
  const expanded = this.expandedFiles.has(file);
3586
3077
  const drafts = listDraftsForFile(file);
@@ -3590,7 +3081,8 @@ var TreeSt = class {
3590
3081
  name: draftKeyForFile(file),
3591
3082
  expanded,
3592
3083
  current,
3593
- hasDrafts: drafts.length > 0
3084
+ hasDrafts: drafts.length > 0,
3085
+ error: w.loadErrors.get(file) ?? null
3594
3086
  });
3595
3087
  if (!expanded) continue;
3596
3088
  for (const draft of drafts) rows.push({
@@ -3624,22 +3116,28 @@ var TreeSt = class {
3624
3116
  this.st.mode = "nav";
3625
3117
  }
3626
3118
  move(delta) {
3627
- const len = this.rows.length;
3119
+ const rows = this.rows;
3120
+ const len = rows.length;
3628
3121
  if (len === 0) return;
3629
- this.ix = (this.ix + delta + len) % len;
3122
+ let ix = this.ix;
3123
+ for (let step = 0; step < len; step++) {
3124
+ ix = (ix + delta + len) % len;
3125
+ if (rows[ix]?.kind !== "section") break;
3126
+ }
3127
+ this.ix = ix;
3630
3128
  }
3631
3129
  /** →: unfold the workflow under the cursor; on a draft row there is nothing
3632
3130
  * left to unfold, so → continues rightwards into the vars panel */
3633
3131
  unfold() {
3634
3132
  const row = this.selected;
3635
- if (row == null) return;
3133
+ if (row == null || row.kind === "section") return;
3636
3134
  if (row.kind === "workflow") this.expandedFiles.add(row.file);
3637
3135
  else this.blur();
3638
3136
  }
3639
3137
  /** ←: fold the workflow under the cursor; on a draft row, jump to (and fold) its parent */
3640
3138
  fold() {
3641
3139
  const row = this.selected;
3642
- if (row == null) return;
3140
+ if (row == null || row.kind === "section") return;
3643
3141
  this.expandedFiles.delete(row.file);
3644
3142
  if (row.kind === "draft") {
3645
3143
  const ix = this.rows.findIndex((r) => r.kind === "workflow" && r.file === row.file);
@@ -3649,13 +3147,14 @@ var TreeSt = class {
3649
3147
  /** ⏎: load the workflow (into 'default'), or the exact draft under the cursor */
3650
3148
  async commit() {
3651
3149
  const row = this.selected;
3652
- if (row == null) return;
3150
+ if (row == null || row.kind === "section") return;
3653
3151
  if (row.kind === "workflow") return this.st.workflows.commit(row.file);
3654
3152
  return this.st.workflows.commit(row.file, row.draft);
3655
3153
  }
3656
3154
  /** n: new draft — current workflow only (a draft snapshots its LIVE var values) */
3657
3155
  promptNewDraft() {
3658
3156
  const row = this.selected;
3157
+ if (row?.kind === "section") return;
3659
3158
  if (row != null && row.file !== this.st.workflows.currentPath) {
3660
3159
  this.st.exec.notice = "load that workflow first (⏎) — a new draft snapshots its live vars";
3661
3160
  return;
@@ -3679,12 +3178,14 @@ var TreeSt = class {
3679
3178
  //#region src/cli/tui/state/WorkflowsSt.ts
3680
3179
  /** workflow-module data layer: scanned files, module loading, opened-host set (TreeSt is the UI over it) */
3681
3180
  var WorkflowsSt = class {
3682
- constructor(st, files, currentPath = null) {
3181
+ constructor(st, files, currentPath = null, bundled = /* @__PURE__ */ new Set(), loadErrors = /* @__PURE__ */ new Map()) {
3683
3182
  this.st = st;
3684
3183
  this.files = files;
3685
3184
  this.loading = false;
3686
3185
  this.loadedHosts = /* @__PURE__ */ new Set();
3687
3186
  this.currentPath = currentPath;
3187
+ this.bundled = bundled;
3188
+ this.loadErrors = loadErrors;
3688
3189
  makeAutoObservable(this, { st: false });
3689
3190
  }
3690
3191
  disconnectAllHosts() {
@@ -3718,6 +3219,7 @@ var WorkflowsSt = class {
3718
3219
  const wf = findDefinedWorkflow(await import(pathToFileURL(resolve(path)).href + (bustCache ? `?v=${Date.now()}` : "")));
3719
3220
  if (wf == null) throw new Error(`${path} exports no DefinedWorkflow`);
3720
3221
  runInAction(() => {
3222
+ this.loadErrors.delete(path);
3721
3223
  this.loadedHosts.add(this.st.wf.host);
3722
3224
  this.loadedHosts.add(wf.host);
3723
3225
  this.st.wf = wf;
@@ -3733,8 +3235,10 @@ var WorkflowsSt = class {
3733
3235
  });
3734
3236
  } catch (e) {
3735
3237
  runInAction(() => {
3238
+ const msg = extractErrorMessage(e);
3239
+ this.loadErrors.set(path, msg);
3736
3240
  this.st.mode = "nav";
3737
- this.st.exec.error = extractErrorMessage(e);
3241
+ this.st.exec.error = msg;
3738
3242
  });
3739
3243
  } finally {
3740
3244
  runInAction(() => {
@@ -3778,7 +3282,7 @@ var TuiSt = class {
3778
3282
  this.editor = new EditorSt(this);
3779
3283
  this.picker = new PickerSt(this);
3780
3284
  this.loras = new LorasSt(this);
3781
- this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null);
3285
+ this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null, opts.bundledFiles, opts.loadErrors);
3782
3286
  this.tree = new TreeSt(this);
3783
3287
  this.drafts = new DraftsSt(this);
3784
3288
  this.exec = new ExecSt(this);
@@ -3807,7 +3311,7 @@ var TuiSt = class {
3807
3311
  }
3808
3312
  /** left tree panel width: longest row (workflow or indented draft), clamped */
3809
3313
  get treeWidth() {
3810
- const longest = Math.max(8, ...this.tree.rows.map((r) => r.kind === "workflow" ? r.name.length : r.draft.length + 3));
3314
+ const longest = Math.max(8, ...this.tree.rows.map((r) => r.kind === "workflow" ? r.name.length : r.kind === "draft" ? r.draft.length + 3 : r.label.length));
3811
3315
  return Math.min(32, longest + 7);
3812
3316
  }
3813
3317
  get entries() {
@@ -3850,31 +3354,50 @@ var TuiSt = class {
3850
3354
  };
3851
3355
  //#endregion
3852
3356
  //#region src/cli/tui/run-tui.tsx
3853
- /** recursive scan for the workflow-module naming convention */
3854
- function scanCflowFiles(dir) {
3855
- return readdirSync(dir, { recursive: true }).map((f) => join(dir, String(f))).filter((f) => f.endsWith(".cflow.ts") || f.endsWith(".cflow.tsx")).sort();
3856
- }
3857
3357
  async function runTui(args) {
3858
- const target = args.find((a) => !a.startsWith("--")) ?? ".";
3358
+ const target = args.find((a) => !a.startsWith("--"));
3859
3359
  process.env[COMFY_TS_TUI_ENV] = "1";
3860
3360
  process.env.COMFY_TS_QUIET = "1";
3861
- const abs = resolve(target);
3361
+ const abs = realpathSync(resolve(target ?? "."));
3862
3362
  const isDir = statSync(abs).isDirectory();
3863
3363
  const scanned = scanCflowFiles(isDir ? abs : dirname(abs));
3864
- const workflowFiles = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned];
3865
- const first = isDir ? workflowFiles[0] : abs;
3866
- if (first == null) {
3364
+ const scannedPlusArg = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned];
3365
+ const canImportBundled = process.versions.bun != null;
3366
+ const examplesDir = canImportBundled ? bundledExamplesDir() : null;
3367
+ if (!canImportBundled && target == null) logError("packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)");
3368
+ const discovery = mergeWorkflowSources({
3369
+ explicitTarget: target != null,
3370
+ scanned: scannedPlusArg,
3371
+ bundledFiles: examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir))
3372
+ });
3373
+ const workflowFiles = discovery.files;
3374
+ if (workflowFiles.length === 0) {
3867
3375
  console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`);
3868
3376
  return 1;
3869
3377
  }
3870
- const wf = findDefinedWorkflow(await import(pathToFileURL(first).href));
3871
- if (wf == null) {
3872
- console.error(`[comfy-ts tui] ${first} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`);
3378
+ const candidates = !isDir && workflowFiles.includes(abs) ? [abs, ...workflowFiles.filter((f) => f !== abs)] : workflowFiles;
3379
+ const loadErrors = /* @__PURE__ */ new Map();
3380
+ let first = null;
3381
+ let wf = null;
3382
+ for (const file of candidates) try {
3383
+ const found = findDefinedWorkflow(await import(pathToFileURL(file).href));
3384
+ if (found == null) throw new Error(`${file} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`);
3385
+ first = file;
3386
+ wf = found;
3387
+ break;
3388
+ } catch (e) {
3389
+ loadErrors.set(file, extractErrorMessage(e));
3390
+ }
3391
+ if (first == null || wf == null) {
3392
+ console.error(`[comfy-ts tui] no loadable workflow module among ${candidates.length} file(s):`);
3393
+ for (const [file, err] of loadErrors) console.error(` ${file}: ${err}`);
3873
3394
  return 1;
3874
3395
  }
3875
3396
  const st = new TuiSt(wf, {
3876
3397
  workflowFiles,
3877
- currentFile: first
3398
+ currentFile: first,
3399
+ bundledFiles: discovery.bundled,
3400
+ loadErrors
3878
3401
  });
3879
3402
  const altScreen = process.stdout.isTTY === true;
3880
3403
  if (altScreen) process.stdout.write("\x1B[?1049h\x1B[H\x1B[>4;1m");
@@ -3893,4 +3416,4 @@ async function runTui(args) {
3893
3416
  //#endregion
3894
3417
  export { runTui };
3895
3418
 
3896
- //# sourceMappingURL=run-tui-SDSJo1Qf.js.map
3419
+ //# sourceMappingURL=run-tui-BFhba_oG.js.map