comfy-ts 2.6.0 → 2.8.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 (101) hide show
  1. package/README.md +22 -13
  2. package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
  3. package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
  4. package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
  5. package/dist/LogsSt-DFxzQfDc.js.map +1 -0
  6. package/dist/cli.js +8 -6
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +288 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +128 -7
  11. package/dist/index.d.ts +128 -7
  12. package/dist/index.js +286 -37
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-_nrvJYyt.js +1948 -0
  15. package/dist/run-serve-_nrvJYyt.js.map +1 -0
  16. package/dist/{run-tui-idFhdO4f.js → run-tui-BPw-SZYW.js} +107 -158
  17. package/dist/run-tui-BPw-SZYW.js.map +1 -0
  18. package/dist/serve-web.js +434 -81
  19. package/dist/{state-C90kdjtB.js → state-B-boDz-Z.js} +184 -45
  20. package/dist/state-B-boDz-Z.js.map +1 -0
  21. package/dist/web.d.ts +112 -7
  22. package/dist/web.js +239 -36
  23. package/dist/web.js.map +1 -1
  24. package/examples/README.md +1 -0
  25. package/examples/comfy-cloud/sdk.d.ts +4066 -321
  26. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
  27. package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
  28. package/examples/web/tsconfig.json +7 -1
  29. package/extra/README.md +32 -0
  30. package/extra/comfyui-textgen-stream/README.md +35 -0
  31. package/extra/comfyui-textgen-stream/__init__.py +166 -0
  32. package/extra/scripts/fetch_text_encoder.py +137 -0
  33. package/package.json +6 -3
  34. package/src/cli/comfy-ts-cli.ts +4 -2
  35. package/src/cli/serve/ServeApp.ts +825 -43
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  39. package/src/cli/serve/run-serve.ts +58 -29
  40. package/src/cli/serve/serveSettings.ts +86 -0
  41. package/src/cli/serve/startupPrint.ts +111 -0
  42. package/src/cli/serve/web/api.ts +120 -1
  43. package/src/cli/serve/web/components/App.tsx +61 -22
  44. package/src/cli/serve/web/components/Gallery.tsx +243 -30
  45. package/src/cli/serve/web/components/Icon.tsx +160 -0
  46. package/src/cli/serve/web/components/PromptEnhancer.tsx +85 -38
  47. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  48. package/src/cli/serve/web/components/VarsForm.tsx +440 -80
  49. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  50. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  51. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  52. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  53. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  54. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  55. package/src/cli/serve/web/llm.ts +254 -0
  56. package/src/cli/serve/web/logWeb.ts +6 -0
  57. package/src/cli/serve/web/state/EnhancerSt.ts +261 -157
  58. package/src/cli/serve/web/state/FormSt.ts +70 -18
  59. package/src/cli/serve/web/state/RunSt.ts +22 -1
  60. package/src/cli/serve/web/state/WebSt.ts +542 -13
  61. package/src/cli/serve/web/state/lightbox.ts +44 -0
  62. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  63. package/src/cli/serve/web/state/payload.ts +44 -2
  64. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  65. package/src/cli/serve/web/styles.ts +415 -57
  66. package/src/cli/serve/web/tsconfig.json +4 -0
  67. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  68. package/src/cli/tui/components/StatusBar.tsx +14 -1
  69. package/src/cli/tui/components/TuiApp.tsx +5 -2
  70. package/src/cli/tui/state/HostSt.ts +3 -2
  71. package/src/cli/tui/state/PickerSt.ts +48 -2
  72. package/src/cli/tui/state/TreeSt.ts +1 -1
  73. package/src/cli/tui/state/TuiSt.ts +2 -1
  74. package/src/coreExports.ts +8 -1
  75. package/src/graph/ComfyNode.ts +58 -1
  76. package/src/host/ComfyHost.ts +13 -2
  77. package/src/host/ComfyManager.ts +31 -13
  78. package/src/host/loraInfoCache.ts +35 -1
  79. package/src/host/loraManagerApi.ts +94 -0
  80. package/src/index.ts +2 -0
  81. package/src/promptEnhancers.ts +102 -0
  82. package/src/runner/ComfyExecution.ts +61 -6
  83. package/src/runner/ComfyWorkflow.ts +18 -4
  84. package/src/runner/ComfyWsApi.ts +3 -0
  85. package/src/runner/describePromptRejection.ts +34 -0
  86. package/src/sdk-generator/ComfySchema.ts +17 -4
  87. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  88. package/src/state.ts +6 -0
  89. package/src/utils/ansi.ts +13 -0
  90. package/src/utils/matchesRegex.ts +13 -0
  91. package/src/utils/safeName.ts +29 -0
  92. package/src/utils/stringMap.ts +9 -0
  93. package/src/vars/ComfyVars.ts +61 -10
  94. package/src/vars/presets.ts +17 -0
  95. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  96. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  97. package/dist/run-serve-CVu39RNd.js +0 -1002
  98. package/dist/run-serve-CVu39RNd.js.map +0 -1
  99. package/dist/run-tui-idFhdO4f.js.map +0 -1
  100. package/dist/state-C90kdjtB.js.map +0 -1
  101. package/src/cli/serve/web/openrouter.ts +0 -142
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as fs from "node:fs";
2
- import { existsSync, readFileSync } from "node:fs";
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import { basename, dirname, isAbsolute, join, resolve } from "pathe";
5
5
  import { scope, type } from "arktype";
@@ -110,7 +110,7 @@ function createNodeStorage() {
110
110
  }
111
111
  //#endregion
112
112
  //#region package.json
113
- var version = "2.6.0";
113
+ var version = "2.8.0";
114
114
  //#endregion
115
115
  //#region src/litegraph/LiteGraphLinkID.ts
116
116
  const asLiteGraphLinkID = (id) => id;
@@ -1221,6 +1221,40 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1221
1221
  return prompt;
1222
1222
  };
1223
1223
  //#endregion
1224
+ //#region src/utils/isRecord.ts
1225
+ /** narrows unknown wire json to an indexable object (arrays and null excluded) */
1226
+ function isRecord(v) {
1227
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1228
+ }
1229
+ //#endregion
1230
+ //#region src/runner/describePromptRejection.ts
1231
+ function str(v) {
1232
+ return typeof v === "string" ? v.trim() : "";
1233
+ }
1234
+ function describePromptRejection(body) {
1235
+ if (!isRecord(body)) return "no reason given";
1236
+ const parts = [];
1237
+ const err = body["error"];
1238
+ if (isRecord(err)) {
1239
+ const head = str(err["message"]);
1240
+ const detail = str(err["details"]);
1241
+ if (head !== "") parts.push(detail === "" ? head : `${head} (${detail})`);
1242
+ }
1243
+ const nodes = body["node_errors"];
1244
+ if (isRecord(nodes)) for (const [nodeId, raw] of Object.entries(nodes)) {
1245
+ if (!isRecord(raw)) continue;
1246
+ const list = raw["errors"];
1247
+ if (!Array.isArray(list)) continue;
1248
+ for (const e of list) {
1249
+ if (!isRecord(e)) continue;
1250
+ const detail = str(e["details"]);
1251
+ const msg = str(e["message"]);
1252
+ parts.push(`node ${nodeId}: ${[msg, detail].filter((x) => x !== "").join(" — ")}`);
1253
+ }
1254
+ }
1255
+ return parts.length === 0 ? "no reason given" : parts.join(" · ");
1256
+ }
1257
+ //#endregion
1224
1258
  //#region src/errors/InvalidPromptError.ts
1225
1259
  var InvalidPromptError = class extends Error {
1226
1260
  constructor(message, snapshot, details) {
@@ -1271,6 +1305,7 @@ var ComfyNodeOutput = class {
1271
1305
  };
1272
1306
  //#endregion
1273
1307
  //#region src/graph/ComfyNode.ts
1308
+ const isScalarValue = (x) => typeof x === "string" || typeof x === "number" || typeof x === "boolean";
1274
1309
  /** ComfyNode
1275
1310
  * - correspond to a signal in the graph
1276
1311
  * - belongs to a script
@@ -1363,13 +1398,27 @@ var ComfyNode = class ComfyNode {
1363
1398
  _convertPromptExtToPrompt(promptExt) {
1364
1399
  const inputs = {};
1365
1400
  const _done = /* @__PURE__ */ new Set();
1401
+ /** every dotted key of every branch: the selected ones are written here, the rest are dropped */
1402
+ const _comboBranchKeys = /* @__PURE__ */ new Set();
1366
1403
  for (const i of this.$schema.inputs) {
1367
1404
  _done.add(i.nameInComfy);
1405
+ const kind = classifySchemaInput(i);
1406
+ if (kind.kind === "dynamic-combo") {
1407
+ this._writeDynamicCombo({
1408
+ name: i.nameInComfy,
1409
+ options: kind.options,
1410
+ defaultKey: kind.defaultKey,
1411
+ provided: promptExt.inputs,
1412
+ out: inputs,
1413
+ claimed: _comboBranchKeys
1414
+ });
1415
+ continue;
1416
+ }
1368
1417
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
1369
1418
  if (value !== void 0) inputs[i.nameInComfy] = value;
1370
1419
  }
1371
1420
  for (const [nameInComfy, rawVal] of Object.entries(promptExt.inputs)) {
1372
- if (_done.has(nameInComfy)) continue;
1421
+ if (_done.has(nameInComfy) || _comboBranchKeys.has(nameInComfy)) continue;
1373
1422
  inputs[nameInComfy] = this.serializeValue(nameInComfy, rawVal);
1374
1423
  }
1375
1424
  return {
@@ -1377,6 +1426,31 @@ var ComfyNode = class ComfyNode {
1377
1426
  inputs
1378
1427
  };
1379
1428
  }
1429
+ /** dynamic combo → the key plus ONLY the selected branch's dotted inputs, absent ones
1430
+ * filled from the schema (agent/architecture.md, dynamic-combo fill). The host declares
1431
+ * those branch inputs required and default-fills none of them */
1432
+ _writeDynamicCombo(p) {
1433
+ for (const opt of p.options) for (const e of opt.inputs) p.claimed.add(`${p.name}.${e.name}`);
1434
+ const raw = p.provided[p.name];
1435
+ const key = typeof raw === "string" ? raw : p.defaultKey;
1436
+ const branch = p.options.find((o) => o.key === key);
1437
+ if (branch == null) {
1438
+ const known = p.options.map((o) => o.key).join(", ");
1439
+ console.error(`🔴 unknown "${p.name}" option ${JSON.stringify(key)} (known: ${known})`);
1440
+ this.graph.recordProblem(`🔴 unknown "${p.name}" option ${JSON.stringify(key)} on ${this.$schema.nodeKey}#${this.uid} (known: ${known})`);
1441
+ return;
1442
+ }
1443
+ p.out[p.name] = key;
1444
+ for (const e of branch.inputs) {
1445
+ const dotted = `${p.name}.${e.name}`;
1446
+ const given = p.provided[dotted];
1447
+ p.out[dotted] = given === void 0 ? defaultValueForWidget({
1448
+ type: typeof e.type === "string" ? e.type : "COMBO",
1449
+ opts: e.opts,
1450
+ enumValues: Array.isArray(e.type) ? e.type.filter(isScalarValue) : void 0
1451
+ }) : this.serializeValue(dotted, given);
1452
+ }
1453
+ }
1380
1454
  /** return the list of nodes piped into this node */
1381
1455
  _incomingNodes() {
1382
1456
  const incomingNodes = [];
@@ -1934,7 +2008,8 @@ const types$1 = scope({
1934
2008
  node: "ComfyNodeID",
1935
2009
  output: {
1936
2010
  "previews?": [{ filepath: "string" }, "[]"],
1937
- "images?": "ComfyImageInfo[]"
2011
+ "images?": "ComfyImageInfo[]",
2012
+ "text?": "unknown[]"
1938
2013
  },
1939
2014
  prompt_id: "PromptID"
1940
2015
  },
@@ -2243,6 +2318,15 @@ var ComfyExecution = class {
2243
2318
  };
2244
2319
  this.onExecuted = (msg) => {
2245
2320
  const promptNodeID = msg.data.node;
2321
+ for (const entry of msg.data.output?.text ?? []) {
2322
+ if (typeof entry !== "string") continue;
2323
+ const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null;
2324
+ this.texts.push({
2325
+ nodeId: promptNodeID,
2326
+ nodeKey,
2327
+ text: entry
2328
+ });
2329
+ }
2246
2330
  const images = msg.data.output?.images;
2247
2331
  if (images) for (const img of images) this.pendingPromises.push(this.retrieveImage(img, promptNodeID).catch((e) => {
2248
2332
  console.error(`🔴 failed to retrieve ${img.filename}:`, e);
@@ -2360,6 +2444,9 @@ var ComfyExecution = class {
2360
2444
  }), promptNodeID);
2361
2445
  };
2362
2446
  this.images = [];
2447
+ this.texts = [];
2448
+ this.progressTexts = /* @__PURE__ */ new Map();
2449
+ this.progressText = null;
2363
2450
  this.alreadyDone = false;
2364
2451
  this._finish = async (p) => {
2365
2452
  if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`);
@@ -2395,7 +2482,9 @@ var ComfyExecution = class {
2395
2482
  ...this.progressGlobal,
2396
2483
  promptId: this.data.id,
2397
2484
  nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,
2398
- elapsedMs: Date.now() - this.startedAt
2485
+ elapsedMs: Date.now() - this.startedAt,
2486
+ nodeProgress: this.workflow.currentExecutingNode?.progress ?? null,
2487
+ progressText: this.progressText
2399
2488
  };
2400
2489
  }
2401
2490
  emitProgress() {
@@ -2406,16 +2495,21 @@ var ComfyExecution = class {
2406
2495
  const filled = Math.round(p.percent / 100 * width);
2407
2496
  const bar = "█".repeat(filled) + "░".repeat(width - filled);
2408
2497
  const node = p.nodeName ? ` · ${p.nodeName}` : "";
2409
- const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2410
- if (line === this._lastLoggedLine) return;
2411
- this._lastLoggedLine = line;
2412
- if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2413
- else console.log(line);
2498
+ const count = p.nodeProgress ? ` ${p.nodeProgress.value}/${p.nodeProgress.max}` : "";
2499
+ const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node}${count} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2500
+ const tail = p.progressText?.replaceAll("\n", " ").trimEnd().slice(-60);
2501
+ const full = tail == null || tail === "" ? line : `${line} · …${tail}`;
2502
+ if (full === this._lastLoggedLine) return;
2503
+ this._lastLoggedLine = full;
2504
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${full}`);
2505
+ else console.log(full);
2414
2506
  }
2415
2507
  finishProgressLine() {
2416
2508
  if (!this.logProgress) return;
2417
2509
  const p = this.progress;
2418
- const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
2510
+ const outputs = [`${this.images.length} image(s)`];
2511
+ if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`);
2512
+ const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${outputs.join(" · ")}`;
2419
2513
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2420
2514
  else console.log(line);
2421
2515
  }
@@ -2457,6 +2551,16 @@ var ComfyExecution = class {
2457
2551
  if (uid == null) return false;
2458
2552
  return (this.snapshot?.apiJson ?? this.workflow.apiJson)[uid]?.class_type === "SaveImageWebsocket";
2459
2553
  }
2554
+ /** @internal a live-text frame for one node */
2555
+ onProgressText(p) {
2556
+ this.progressTexts.set(p.nodeId, p.text);
2557
+ this.progressText = p.text;
2558
+ this.emitProgress();
2559
+ }
2560
+ /** the last text output, the one a single-generator workflow means by "the result" */
2561
+ get text() {
2562
+ return this.texts.at(-1)?.text ?? null;
2563
+ }
2460
2564
  update(data) {
2461
2565
  Object.assign(this.data, data);
2462
2566
  }
@@ -2489,11 +2593,14 @@ const deepCopyNaive = (x) => JSON.parse(JSON.stringify(x));
2489
2593
  //#region src/utils/ansi.ts
2490
2594
  const codes = {
2491
2595
  bold: [1, 22],
2596
+ dim: [2, 22],
2492
2597
  underline: [4, 24],
2493
2598
  red: [31, 39],
2494
2599
  green: [32, 39],
2495
2600
  yellow: [33, 39],
2496
2601
  blue: [34, 39],
2602
+ cyan: [36, 39],
2603
+ gray: [90, 39],
2497
2604
  greenBright: [92, 39]
2498
2605
  };
2499
2606
  function styler(open = "", close = "") {
@@ -2744,6 +2851,7 @@ var ComfyWorkflow = class {
2744
2851
  return execution;
2745
2852
  };
2746
2853
  this.start = async (p = {}) => {
2854
+ if (this.host.ws == null) throw new Error(`🔴 host '${this.host.data.id}' was never connected — call \`await host.connect()\` before running a workflow`);
2747
2855
  this.resetRunState();
2748
2856
  const snapshot = {
2749
2857
  apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? "use_stringified_numbers_only")),
@@ -2768,8 +2876,9 @@ var ComfyWorkflow = class {
2768
2876
  headers: { "Content-Type": "application/json" },
2769
2877
  body: JSON.stringify(out)
2770
2878
  });
2771
- const promptInfo = softValidate(PromptInfo_ark, await res.json());
2772
- if (res.status !== 200) throw new InvalidPromptError("ComfyUI /prompt request failed", snapshot, promptInfo);
2879
+ const promptInfoJson = await res.json();
2880
+ if (res.status !== 200) throw new InvalidPromptError(`ComfyUI refused the prompt: ${describePromptRejection(promptInfoJson)}`, snapshot, promptInfoJson);
2881
+ const promptInfo = softValidate(PromptInfo_ark, promptInfoJson);
2773
2882
  return new ComfyExecution(this, {
2774
2883
  id: promptInfo.prompt_id,
2775
2884
  executed: false,
@@ -2842,6 +2951,13 @@ var ComfyWorkflow = class {
2842
2951
  }
2843
2952
  };
2844
2953
  //#endregion
2954
+ //#region src/utils/matchesRegex.ts
2955
+ function statelessRegex(re) {
2956
+ if (!re.global && !re.sticky) return re;
2957
+ const source = re.sticky ? `^(?:${re.source})` : re.source;
2958
+ return new RegExp(source, re.flags.replace(/[gy]/g, ""));
2959
+ }
2960
+ //#endregion
2845
2961
  //#region src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts
2846
2962
  /** having a bunch of sensible default will help slightly */
2847
2963
  function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
@@ -2986,6 +3102,25 @@ const wrapQuote = (s) => {
2986
3102
  };
2987
3103
  //#endregion
2988
3104
  //#region src/sdk-generator/comfyui-sdk-codegen.ts
3105
+ const isScalar = (x) => typeof x === "string" || typeof x === "number" || typeof x === "boolean";
3106
+ /** a dynamic-combo branch input, typed the way its dotted prompt key is filled: inline enums
3107
+ * and COMBO option lists become literal unions, everything else stays a named slot */
3108
+ const branchInputType = (entry) => {
3109
+ const opts = isRecord$1(entry.opts) ? entry.opts : null;
3110
+ const scalars = (Array.isArray(entry.type) ? entry.type : Array.isArray(opts?.["options"]) ? opts["options"] : []).filter(isScalar);
3111
+ if (scalars.length > 0) return scalars.map((o) => JSON.stringify(o)).join(" | ");
3112
+ if (typeof entry.type === "string") return `Accepts[${JSON.stringify(entry.type)}]`;
3113
+ return "string | number | boolean";
3114
+ };
3115
+ /** `& ({key:'a'; 'name.x'?: …} | {key:'b'})` — one member per branch, so a key from a branch
3116
+ * you did not select is a type error. Branch fields are optional: ComfyNode fills them
3117
+ * from the schema at serialization (agent/architecture.md, dynamic-combo fill) */
3118
+ const dynamicComboUnion = (p) => {
3119
+ return ` & (${p.options.map((opt) => {
3120
+ const fields = opt.inputs.map((e) => `${escapeJSKey(`${p.name}.${e.name}`)}?: ${branchInputType(e)}`);
3121
+ return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
3122
+ }).join(" | ")})`;
3123
+ };
2989
3124
  /**
2990
3125
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
2991
3126
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -3038,6 +3173,7 @@ function codegenSDK(opts) {
3038
3173
  b.indent();
3039
3174
  for (const n of nodes) {
3040
3175
  p(`${escapeJSKey(n.nodeKey)}: {`);
3176
+ const comboSuffixes = [];
3041
3177
  for (const i of n.inputs) {
3042
3178
  const kind = classifySchemaInput(i);
3043
3179
  if (kind.kind === "dynamic-container") {
@@ -3048,6 +3184,16 @@ function codegenSDK(opts) {
3048
3184
  });
3049
3185
  continue;
3050
3186
  }
3187
+ if (kind.kind === "dynamic-combo") {
3188
+ const optsDyn = typeof i.opts === "string" ? null : i.opts;
3189
+ comboSuffixes.push(dynamicComboUnion({
3190
+ name: i.nameInComfy,
3191
+ nameEscaped: i.nameInComfyEscaped,
3192
+ options: kind.options,
3193
+ keyOptional: optsDyn?.default !== void 0 || !i.required
3194
+ }));
3195
+ continue;
3196
+ }
3051
3197
  const opts_ = typeof i.opts === "string" ? null : i.opts;
3052
3198
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
3053
3199
  const comboOptions = i.typeName === "COMBO" && Array.isArray(opts_?.options) ? opts_.options.filter((o) => typeof o === "string" || typeof o === "number" || typeof o === "boolean") : [];
@@ -3064,7 +3210,7 @@ function codegenSDK(opts) {
3064
3210
  const canBeOmmited = opts_?.default !== void 0 || !i.required;
3065
3211
  p(` ${i.nameInComfyEscaped}${canBeOmmited ? "?" : ""}: ${type}`);
3066
3212
  }
3067
- p(`},`);
3213
+ p(`}${comboSuffixes.join("")},`);
3068
3214
  }
3069
3215
  b.deindent();
3070
3216
  p("}");
@@ -3233,7 +3379,8 @@ var ComfySchema = class {
3233
3379
  };
3234
3380
  this.getLoras = (filter) => {
3235
3381
  const all = this.stringValues("LoraLoader.lora_name");
3236
- return filter == null ? all : all.filter((n) => filter.test(n));
3382
+ const stateless = filter == null ? null : statelessRegex(filter);
3383
+ return stateless == null ? all : all.filter((n) => stateless.test(n));
3237
3384
  };
3238
3385
  this.getImages = () => {
3239
3386
  return this.stringValues("LoadImage.image");
@@ -3367,15 +3514,19 @@ var ComfySchema = class {
3367
3514
  comfyUnionDef: slotType
3368
3515
  }).unionName);
3369
3516
  else throw new Error(`invalid schema (${JSON.stringify(slotType)}) for input "${ipt.name}" in node "${nodeNameInComfy}" (type: ${typeof slotType}; expected: Array | string)`);
3370
- const isAutogrowContainer = typeof slotType === "string" && classifyWidgetInput({
3517
+ const widgetKind = typeof slotType === "string" ? classifyWidgetInput({
3371
3518
  name: ipt.name,
3372
3519
  type: slotType,
3373
3520
  opts: slotOpts
3374
- }).kind === "dynamic-container";
3521
+ }) : null;
3522
+ const isAutogrowContainer = widgetKind?.kind === "dynamic-container";
3375
3523
  if (isAutogrowContainer) {
3376
3524
  const instType = containerInstanceSlotType(slotOpts);
3377
3525
  if (instType != null) this.knownSlotTypes.add(asComfyNodeSlotTypeName(instType));
3378
3526
  }
3527
+ if (widgetKind?.kind === "dynamic-combo") {
3528
+ for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
3529
+ }
3379
3530
  node.inputs.push({
3380
3531
  slotName: inputSlotName,
3381
3532
  required: ipt.required && !isAutogrowContainer,
@@ -3551,7 +3702,19 @@ var ComfyManager = class {
3551
3702
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3552
3703
  };
3553
3704
  this.restartComfyUI = async () => {
3554
- return this.fetchGetJSON("/manager/reboot");
3705
+ const refusals = [];
3706
+ for (const method of ["POST", "GET"]) {
3707
+ let response;
3708
+ try {
3709
+ response = await this.host.fetch("/manager/reboot", { method });
3710
+ } catch {
3711
+ return;
3712
+ }
3713
+ if (response.ok) return;
3714
+ refusals.push(`${method} → ${response.status}`);
3715
+ if (response.status !== 404) break;
3716
+ }
3717
+ throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(", ")}) — ComfyUI-Manager is not installed there, or its reboot route moved again`);
3555
3718
  };
3556
3719
  this.modelList = null;
3557
3720
  this.fetchModels = () => {
@@ -3676,7 +3839,7 @@ var ComfyManager = class {
3676
3839
  }
3677
3840
  rebootComfyUIAndUpdateHostPluginsAndModelsAfter10Seconds() {
3678
3841
  setTimeout(() => void this.fetchPluginsAndModels(), 1e4);
3679
- return this.fetchGetJSON("/manager/reboot");
3842
+ return this.restartComfyUI();
3680
3843
  }
3681
3844
  get titlesOfAllInstalledPlugins() {
3682
3845
  return this.pluginList?.custom_nodes.filter((x) => x.installed === "True").map((x) => x.title) ?? [];
@@ -3899,12 +4062,6 @@ var ResilientWebSocketClient = class {
3899
4062
  }
3900
4063
  }
3901
4064
  };
3902
- //#endregion
3903
- //#region src/utils/isRecord.ts
3904
- /** narrows unknown wire json to an indexable object (arrays and null excluded) */
3905
- function isRecord(v) {
3906
- return typeof v === "object" && v !== null && !Array.isArray(v);
3907
- }
3908
4065
  type({
3909
4066
  items: "unknown[]",
3910
4067
  "total?": "number"
@@ -4065,7 +4222,6 @@ function getLoraPreviewUrl(name, hostId) {
4065
4222
  const info = getLoraInfo(name, hostId);
4066
4223
  return info == null ? null : lmPreviewUrl(info);
4067
4224
  }
4068
- /** the lora's NAMES: the file, and the model name a human would call it by */
4069
4225
  function loraSearchNames(name, hostId) {
4070
4226
  const names = [loraBasename(name), name.replaceAll("\\", "/")];
4071
4227
  const info = getLoraInfo(name, hostId);
@@ -4187,6 +4343,20 @@ function writeKeywords() {
4187
4343
  }
4188
4344
  }
4189
4345
  //#endregion
4346
+ //#region src/vars/presets.ts
4347
+ function toPresetList(spec) {
4348
+ if (spec == null) return [];
4349
+ return Object.entries(spec).map(([label, text]) => ({
4350
+ label,
4351
+ text
4352
+ }));
4353
+ }
4354
+ /** which preset the value still IS, or null once it was hand-edited (trailing whitespace ignored) */
4355
+ function activePresetLabel(presets, value) {
4356
+ const v = value.trim();
4357
+ return presets.find((p) => p.text.trim() === v)?.label ?? null;
4358
+ }
4359
+ //#endregion
4190
4360
  //#region src/vars/ComfyVars.ts
4191
4361
  /**
4192
4362
  * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
@@ -4244,9 +4414,14 @@ var ComfyVar = class extends ComfyVarBase {
4244
4414
  }
4245
4415
  };
4246
4416
  var TextVar = class extends ComfyVar {
4247
- constructor(..._args) {
4248
- super(..._args);
4417
+ /** a bare label string was the whole second parameter before opts existed: a published
4418
+ * consumer passing one must keep working, exactly as SeedVar does */
4419
+ constructor(defaultValue, opts = {}) {
4420
+ const o = typeof opts === "string" ? { label: opts } : opts;
4421
+ super(defaultValue, o.label);
4249
4422
  this.kind = "text";
4423
+ this.opts = o;
4424
+ this.presets = toPresetList(o.presets);
4250
4425
  }
4251
4426
  parse(raw) {
4252
4427
  this.set(raw);
@@ -4270,6 +4445,7 @@ var PromptVar = class extends ComfyVarBase {
4270
4445
  super(defaultValue, promptOpts.label);
4271
4446
  this.promptOpts = promptOpts;
4272
4447
  this.kind = "prompt";
4448
+ this.presets = toPresetList(promptOpts.presets);
4273
4449
  }
4274
4450
  parse(raw) {
4275
4451
  this.set(raw);
@@ -4346,11 +4522,14 @@ var FloatVar = class extends ComfyVar {
4346
4522
  * The number shown is always the seed the NEXT run will use.
4347
4523
  */
4348
4524
  var SeedVar = class extends ComfyVar {
4349
- constructor(defaultValue = 0, label) {
4350
- super(defaultValue, label);
4525
+ /** `opts` is the modern shape; a bare label string stays accepted, since that was the
4526
+ * signature before a workflow could declare the mode it wants to run in */
4527
+ constructor(defaultValue = 0, opts = {}) {
4528
+ const o = typeof opts === "string" ? { label: opts } : opts;
4529
+ super(defaultValue, o.label);
4351
4530
  this.kind = "seed";
4352
- this.mode = "=";
4353
- this.defaultMode = "=";
4531
+ this.mode = o.mode ?? "=";
4532
+ this.defaultMode = this.mode;
4354
4533
  makeObservable(this, {
4355
4534
  mode: observable,
4356
4535
  setMode: action,
@@ -4418,8 +4597,8 @@ var SeedVar = class extends ComfyVar {
4418
4597
  }
4419
4598
  };
4420
4599
  var ToggleVar = class extends ComfyVar {
4421
- constructor(..._args2) {
4422
- super(..._args2);
4600
+ constructor(..._args) {
4601
+ super(..._args);
4423
4602
  this.kind = "toggle";
4424
4603
  }
4425
4604
  toggle() {
@@ -4480,6 +4659,12 @@ var LorasVar = class LorasVar extends ComfyVar {
4480
4659
  this.resolvedOptions = null;
4481
4660
  this.hostId = void 0;
4482
4661
  }
4662
+ /** the filter the workflow declared, when it declared one (`v.loras(/krea-?2/i)`). Public so
4663
+ * a UI can SHOW it, and so serve applies the same narrowing to loras only its lora-manager
4664
+ * mirror knows, an unfiltered union would put the whole catalog back in a filtered picker */
4665
+ get optionsFilter() {
4666
+ return this.optionsSource instanceof RegExp ? this.optionsSource : null;
4667
+ }
4483
4668
  get options() {
4484
4669
  if (!(this.optionsSource instanceof RegExp)) return this.optionsSource;
4485
4670
  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)`);
@@ -4734,11 +4919,13 @@ var ImageVar = class extends ComfyVar {
4734
4919
  };
4735
4920
  /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size / v.image */
4736
4921
  const v = {
4737
- text: (defaultValue, label) => new TextVar(defaultValue, label),
4922
+ text: (defaultValue, opts = {}) => new TextVar(defaultValue, typeof opts === "string" ? { label: opts } : opts),
4738
4923
  prompt: (defaultValue, opts = {}) => new PromptVar(defaultValue, opts),
4739
4924
  int: (defaultValue, opts = {}) => new IntVar(defaultValue, opts),
4740
4925
  float: (defaultValue, opts = {}) => new FloatVar(defaultValue, opts),
4741
- seed: (defaultValue = 0, label) => new SeedVar(defaultValue, label),
4926
+ /** `mode` is the SPEC default the workflow runs in: `'+'` makes every run step the seed,
4927
+ * which is what a tuning session wants, and reset()/revert come back to it */
4928
+ seed: (defaultValue = 0, opts = {}) => new SeedVar(defaultValue, opts),
4742
4929
  toggle: (defaultValue, label) => new ToggleVar(defaultValue, label),
4743
4930
  choice: (choices, defaultValue, label) => new ChoiceVar(choices, defaultValue, label),
4744
4931
  loras: (options, initial = {}, label) => new LorasVar(options, initial, label),
@@ -5085,6 +5272,7 @@ var ComfyHost = class {
5085
5272
  this.activePromptID = null;
5086
5273
  this.latentPreview = null;
5087
5274
  this.onLatentPreview = null;
5275
+ this.onProgressText = null;
5088
5276
  this.onStatus = null;
5089
5277
  this.onSession = null;
5090
5278
  this.onLogs = null;
@@ -5298,6 +5486,17 @@ var ComfyHost = class {
5298
5486
  this._unknownBinaryFrameTypes.add(frame.eventType);
5299
5487
  console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`);
5300
5488
  }
5489
+ if (frame.kind === "text") {
5490
+ (this.activePromptID != null ? this.executions.get(this.activePromptID) : null)?.onProgressText({
5491
+ nodeId: frame.nodeId,
5492
+ text: frame.text
5493
+ });
5494
+ this.onProgressText?.({
5495
+ nodeId: frame.nodeId,
5496
+ text: frame.text,
5497
+ promptID: this.activePromptID
5498
+ });
5499
+ }
5301
5500
  return;
5302
5501
  }
5303
5502
  const msg_ = JSON.parse(String(e.data));
@@ -5968,6 +6167,10 @@ var ComfyTS = class ComfyTS {
5968
6167
  resolveFromDrafts(relativePath) {
5969
6168
  return asAbsolutePath(join(this.baseFolder, "drafts", relativePath));
5970
6169
  }
6170
+ /** master prompts of the serve web ui's prompt enhancer — hand-editable markdown */
6171
+ resolveFromPromptEnhancers(relativePath) {
6172
+ return asAbsolutePath(join(this.baseFolder, "prompt-enhancers", relativePath));
6173
+ }
5971
6174
  resolveFromCache(relativePath) {
5972
6175
  return asAbsolutePath(join(this.baseFolder, "cache", relativePath));
5973
6176
  }
@@ -6050,6 +6253,52 @@ function exampleImagePath(name) {
6050
6253
  return abs;
6051
6254
  }
6052
6255
  //#endregion
6256
+ //#region src/utils/safeName.ts
6257
+ /** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */
6258
+ function validStoreName(raw) {
6259
+ const name = raw.trim();
6260
+ if (name.length > 100) return null;
6261
+ return /^[\w][\w .-]*$/.test(name) ? name : null;
6262
+ }
6263
+ //#endregion
6264
+ //#region src/promptEnhancers.ts
6265
+ const EXT = ".md";
6266
+ function promptEnhancersDir() {
6267
+ return comfyts.resolveFromPromptEnhancers("");
6268
+ }
6269
+ /** the PURE read: no seeding, no writing. What a workflow calls at define time, since importing
6270
+ * a module must never create files in someone's project */
6271
+ function readPromptEnhancers() {
6272
+ const dir = promptEnhancersDir();
6273
+ if (!existsSync(dir)) return [];
6274
+ const out = [];
6275
+ for (const file of readdirSync(dir).sort()) {
6276
+ if (!file.endsWith(EXT)) continue;
6277
+ const name = file.slice(0, -3);
6278
+ if (validStoreName(name) == null) continue;
6279
+ try {
6280
+ out.push({
6281
+ name,
6282
+ text: readFileSync(join(dir, file), "utf8")
6283
+ });
6284
+ } catch (e) {
6285
+ console.error(`[serve] prompt enhancer '${name}' unreadable, skipped:`, e);
6286
+ }
6287
+ }
6288
+ return out;
6289
+ }
6290
+ /**
6291
+ * the same master prompts, shaped for `v.text(x, { presets })` / `v.prompt`: file name → text.
6292
+ * The point is that ONE library of texts serves the ✨ enhancer and every var that wants them,
6293
+ * so a paragraph you tuned in the panel is offered by the workflow too, with no copy.
6294
+ * Empty when the folder is absent, so a var keeps whatever presets it declares inline.
6295
+ */
6296
+ function promptEnhancerPresets() {
6297
+ const out = {};
6298
+ for (const e of readPromptEnhancers()) out[e.name] = e.text;
6299
+ return out;
6300
+ }
6301
+ //#endregion
6053
6302
  //#region src/cli/tui-env.ts
6054
6303
  const COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
6055
6304
  function isTuiActive() {
@@ -6063,6 +6312,6 @@ function isTuiActive() {
6063
6312
  */
6064
6313
  setDefaultComfyStorage(createNodeStorage());
6065
6314
  //#endregion
6066
- export { ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyHostUnreachableError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, clearLoraKeywordOverride, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, createMemoryStorage, exampleImagePath, getComfyStorage, getLoraDisplayName, getLoraInfo, getLoraKeyword, getLoraPreviewUrl, getLoraTriggerWords, hostIdToNamespace, isLoraKeywordFromMirror, isTuiActive, loraKey, loraKeywordFromMirror, loraMatchesFilter, loraSearchNames, loraSearchText, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, refreshLoraInfoCacheIfChanged, reloadLoraInfoCache, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setDefaultComfyStorage, setLoraKeyword, v };
6315
+ export { ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyHostUnreachableError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, activePresetLabel, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, clearLoraKeywordOverride, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, createMemoryStorage, exampleImagePath, getComfyStorage, getLoraDisplayName, getLoraInfo, getLoraKeyword, getLoraPreviewUrl, getLoraTriggerWords, hostIdToNamespace, isLoraKeywordFromMirror, isTuiActive, loraKey, loraKeywordFromMirror, loraMatchesFilter, loraSearchNames, loraSearchText, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, promptEnhancerPresets, readPromptEnhancers, refreshLoraInfoCacheIfChanged, reloadLoraInfoCache, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setDefaultComfyStorage, setLoraKeyword, toPresetList, v };
6067
6316
 
6068
6317
  //# sourceMappingURL=index.js.map