comfy-ts 1.2.0 → 1.3.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 (42) hide show
  1. package/README.md +40 -0
  2. package/dist/DefinedWorkflow-gpknV-5f.js +686 -0
  3. package/dist/DefinedWorkflow-gpknV-5f.js.map +1 -0
  4. package/dist/DraftsSt-DmA0jWGl.js +434 -0
  5. package/dist/DraftsSt-DmA0jWGl.js.map +1 -0
  6. package/dist/cli.js +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +132 -21
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +5 -0
  11. package/dist/index.d.ts +23 -18
  12. package/dist/index.js +132 -21
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-Bn6yIJB0.js +638 -0
  15. package/dist/run-serve-Bn6yIJB0.js.map +1 -0
  16. package/dist/{run-tui-BAdizWsO.js → run-tui-BtjaOXRh.js} +244 -440
  17. package/dist/run-tui-BtjaOXRh.js.map +1 -0
  18. package/dist/{state-BYbxDgfr.js → state-DKCPy105.js} +130 -698
  19. package/dist/state-DKCPy105.js.map +1 -0
  20. package/package.json +3 -2
  21. package/src/cli/comfy-ts-cli.ts +15 -5
  22. package/src/cli/serve/ServeApp.ts +378 -0
  23. package/src/cli/serve/applyVarPayload.ts +119 -0
  24. package/src/cli/serve/describeVar.ts +74 -0
  25. package/src/cli/serve/run-serve.ts +169 -0
  26. package/src/cli/tui/components/StatusBar.tsx +1 -0
  27. package/src/cli/tui/components/TreePanel.tsx +17 -3
  28. package/src/cli/tui/components/TuiApp.tsx +7 -2
  29. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  30. package/src/cli/tui/imageClipboard.ts +39 -0
  31. package/src/cli/tui/listWindow.ts +36 -0
  32. package/src/cli/tui/state/ExecSt.ts +48 -0
  33. package/src/cli/tui/state/TreeSt.ts +25 -0
  34. package/src/cli/tui/state/TuiSt.ts +34 -0
  35. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  36. package/src/runner/ComfyExecution.ts +21 -4
  37. package/src/runner/outputPath.ts +75 -0
  38. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  39. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  40. package/src/vars/ComfyVars.ts +8 -0
  41. package/dist/run-tui-BAdizWsO.js.map +0 -1
  42. package/dist/state-BYbxDgfr.js.map +0 -1
@@ -1,13 +1,12 @@
1
+ import { _ as logError, g as isQuiet, h as extractErrorMessage, t as DefinedWorkflow, v as logInfo, y as logSuccess } from "./DefinedWorkflow-gpknV-5f.js";
1
2
  import fs, { existsSync, mkdirSync, readFileSync, statSync, writeFile, writeFileSync } from "node:fs";
2
- import { basename, dirname, isAbsolute, join, resolve } from "pathe";
3
+ import { basename, dirname, join } from "pathe";
3
4
  import crypto from "node:crypto";
4
5
  import { scope, type } from "arktype";
5
6
  import { nanoid } from "nanoid";
6
7
  import sharp from "sharp";
7
8
  import { imageMeta } from "image-meta";
8
9
  import WebSocket from "ws";
9
- import { homedir } from "node:os";
10
- import { action, makeObservable, observable, runInAction } from "mobx";
11
10
  import https from "node:https";
12
11
  import { stdout } from "node:process";
13
12
  //#region src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts
@@ -274,6 +273,25 @@ const containerInstanceSlotType = (opts) => {
274
273
  if (subs.length !== 1 || first == null || typeof first.type !== "string") return null;
275
274
  return first.type;
276
275
  };
276
+ /**
277
+ * frontend-registered widgets whose object_info opts carry NO config signal —
278
+ * the one exception to config-only classification (architecture.md rule 8).
279
+ * Every entry must quote the frontend widget-creation source.
280
+ *
281
+ * LOAD_3D (ComfyUI_frontend src/extensions/core/load3d.ts, verified
282
+ * 2026-07-31): the LOAD_3D custom widget handler runs
283
+ * node.addWidget('button', 'upload 3d model', 'upload3dmodel', …)
284
+ * node.addWidget('button', 'upload extra resources', 'uploadExtraResources', …)
285
+ * node.addWidget('button', 'clear', 'clear', …)
286
+ * THEN creates the scene widget, so the serialized run is
287
+ * [btn, btn, btn, value] with the real value LAST. Lax domain: '' in saved
288
+ * files, an {image, mask, normal, camera_info, …} dict at queue time.
289
+ */
290
+ const EMPTY_CONFIG_FRONTEND_WIDGETS = { LOAD_3D: { prefixValues: [
291
+ "upload3dmodel",
292
+ "uploadExtraResources",
293
+ "clear"
294
+ ] } };
277
295
  const classifyWidgetInput = (p) => {
278
296
  const o = isRecord(p.opts) ? p.opts : null;
279
297
  if (o?.["forceInput"] === true) return { kind: "slot" };
@@ -282,7 +300,8 @@ const classifyWidgetInput = (p) => {
282
300
  return {
283
301
  kind: "widget",
284
302
  consumes: controlConsumes(o, tn, p.name),
285
- strictValues: true
303
+ strictValues: true,
304
+ prefixValues: []
286
305
  };
287
306
  }
288
307
  if (typeof p.type !== "string") return { kind: "slot" };
@@ -290,7 +309,8 @@ const classifyWidgetInput = (p) => {
290
309
  if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
291
310
  kind: "widget",
292
311
  consumes: controlConsumes(o, widgetTypeName, p.name),
293
- strictValues: true
312
+ strictValues: true,
313
+ prefixValues: []
294
314
  };
295
315
  const options = o?.["options"];
296
316
  if (Array.isArray(options)) {
@@ -307,7 +327,8 @@ const classifyWidgetInput = (p) => {
307
327
  return {
308
328
  kind: "widget",
309
329
  consumes: controlConsumes(o, p.type, p.name),
310
- strictValues: true
330
+ strictValues: true,
331
+ prefixValues: []
311
332
  };
312
333
  }
313
334
  const template = o?.["template"];
@@ -318,7 +339,15 @@ const classifyWidgetInput = (p) => {
318
339
  if (o?.["socketless"] === true) return {
319
340
  kind: "widget",
320
341
  consumes: 1,
321
- strictValues: false
342
+ strictValues: false,
343
+ prefixValues: []
344
+ };
345
+ const emptyConfigEntry = EMPTY_CONFIG_FRONTEND_WIDGETS[widgetTypeName];
346
+ if (emptyConfigEntry != null) return {
347
+ kind: "widget",
348
+ consumes: emptyConfigEntry.prefixValues.length + 1,
349
+ strictValues: false,
350
+ prefixValues: emptyConfigEntry.prefixValues
322
351
  };
323
352
  return { kind: "slot" };
324
353
  };
@@ -328,11 +357,6 @@ const classifySchemaInput = (input) => classifyWidgetInput({
328
357
  opts: input.opts,
329
358
  isEnumUnion: input.isEnum
330
359
  });
331
- /** how many widgets_values entries this schema input consumes (export path + positional walks) */
332
- const howManyWidgetValuesForThisSchemaType = (input) => {
333
- const kind = classifySchemaInput(input);
334
- return kind.kind === "widget" ? kind.consumes : 0;
335
- };
336
360
  /**
337
361
  * what ComfyUI's frontend gives a widget created with no serialized value
338
362
  * (`getWidgetDefaultValue` semantics), used when a positional array is
@@ -549,14 +573,6 @@ function codegenSDK(opts) {
549
573
  const asComfyNodeSlotTypeName = (x) => x;
550
574
  const asComfyNodeSlotName = (x) => x;
551
575
  //#endregion
552
- //#region src/utils/log.ts
553
- const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
554
- const logInfo = (msg) => {
555
- if (!isQuiet()) console.log(msg);
556
- };
557
- const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
558
- const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
559
- //#endregion
560
576
  //#region src/sdk-generator/ComfySchema.ts
561
577
  /**
562
578
  * ONE host's schema: the parsed view of its object_info.json + embeddings.
@@ -804,7 +820,7 @@ var ComfySchema = class {
804
820
  };
805
821
  //#endregion
806
822
  //#region package.json
807
- var version = "1.2.0";
823
+ var version = "1.3.0";
808
824
  //#endregion
809
825
  //#region src/litegraph/LiteGraphLinkID.ts
810
826
  const asLiteGraphLinkID = (id) => id;
@@ -1475,15 +1491,15 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1475
1491
  if (!p.strict && isRecord(value)) return value;
1476
1492
  throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
1477
1493
  };
1478
- /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
1494
+ /** named wins, then positional cursor (+prefixLen skips leading button values, LOAD_3D); filled=true when both miss (caller falls back to the schema default) */
1479
1495
  const resolveWidgetValue = (p) => {
1480
1496
  let value;
1481
1497
  let has = false;
1482
1498
  if (Object.hasOwn(named, p.promptName)) {
1483
1499
  value = named[p.promptName];
1484
1500
  has = true;
1485
- } else if (offset < positional.length) {
1486
- value = positional[offset];
1501
+ } else if (offset + p.prefixLen < positional.length) {
1502
+ value = positional[offset + p.prefixLen];
1487
1503
  has = true;
1488
1504
  }
1489
1505
  if (positional.length > 0) offset += p.consumes;
@@ -1495,7 +1511,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1495
1511
  const consumePlainWidget = (p) => {
1496
1512
  const r = resolveWidgetValue({
1497
1513
  promptName: p.promptName,
1498
- consumes: p.consumes
1514
+ consumes: p.consumes,
1515
+ prefixLen: p.prefixLen
1499
1516
  });
1500
1517
  const raw = r.filled ? defaultValueForWidget({
1501
1518
  type: p.typeName,
@@ -1514,7 +1531,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1514
1531
  const consumeDynamicCombo = (p) => {
1515
1532
  const r = resolveWidgetValue({
1516
1533
  promptName: p.path,
1517
- consumes: 1
1534
+ consumes: 1,
1535
+ prefixLen: 0
1518
1536
  });
1519
1537
  const key = r.filled ? p.defaultKey : r.value;
1520
1538
  if (typeof key !== "string") throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): dynamic combo "${p.path}" key is not a string: ${JSON.stringify(key)}`, node);
@@ -1542,6 +1560,7 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1542
1560
  typeName: typeof sub.type === "string" ? sub.type : "COMBO",
1543
1561
  opts: sub.opts,
1544
1562
  consumes: kind.consumes,
1563
+ prefixLen: kind.prefixValues.length,
1545
1564
  strict: kind.strictValues,
1546
1565
  enumValues: inlineEnum,
1547
1566
  linkedInput: inputsInNodeJSON.find((i) => i.name === subPath)
@@ -1553,13 +1572,15 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1553
1572
  if (kind.kind === "slot" && input?.widgetName != null) kind = {
1554
1573
  kind: "widget",
1555
1574
  consumes: howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) === 2 ? 2 : 1,
1556
- strictValues: true
1575
+ strictValues: true,
1576
+ prefixValues: []
1557
1577
  };
1558
1578
  if (kind.kind === "widget") consumePlainWidget({
1559
1579
  promptName: field.nameInComfy,
1560
1580
  typeName: field.typeName,
1561
1581
  opts: field.opts,
1562
1582
  consumes: kind.consumes,
1583
+ prefixLen: kind.prefixValues.length,
1563
1584
  strict: kind.strictValues,
1564
1585
  linkedInput: input
1565
1586
  });
@@ -2054,7 +2075,7 @@ const convertNodeToLiteGraphNode = (ctx, node) => {
2054
2075
  const widgets_values = [];
2055
2076
  for (const ipt of node.$schema.inputs) {
2056
2077
  const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
2057
- const isWidget = howManyWidgetValuesForThisSchemaType(ipt) > 0;
2078
+ const kind = classifySchemaInput(ipt);
2058
2079
  if (_isLink(raw)) {
2059
2080
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber, `link target node "${raw[0]}" not found in graph`);
2060
2081
  inputs.push({
@@ -2062,9 +2083,10 @@ const convertNodeToLiteGraphNode = (ctx, node) => {
2062
2083
  type: ipt.typeName,
2063
2084
  link: ctx.allocateLink(nodeUidNumber, raw[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), ipt.typeName)
2064
2085
  });
2065
- } else if (isWidget) {
2066
- widgets_values.push(raw);
2067
- if (ipt.typeName === "INT" && (ipt.nameInComfy === "seed" || ipt.nameInComfy === "noise_seed")) widgets_values.push(false);
2086
+ } else if (kind.kind === "widget") {
2087
+ widgets_values.push(...kind.prefixValues, raw);
2088
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
2089
+ for (let i = 0; i < phantoms; i++) widgets_values.push(false);
2068
2090
  } else inputs.push({
2069
2091
  name: ipt.nameInComfy,
2070
2092
  type: ipt.typeName,
@@ -2110,6 +2132,65 @@ var LiteGraphCtx = class {
2110
2132
  }
2111
2133
  };
2112
2134
  //#endregion
2135
+ //#region src/runner/outputPath.ts
2136
+ /**
2137
+ * local output naming, relative to `.comfy-ts/outputs/` (his repro
2138
+ * 2026-07-31): the server filename is NOT unique — cloud hosts reset the
2139
+ * `_00001_` counter every run, so trusting it overwrote the same file — and
2140
+ * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
2141
+ * prefix. Local names are ours: dir from the prompt's own filename_prefix
2142
+ * (or an explicit saveFormat.prefix override), then
2143
+ * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
2144
+ * per stem and nothing ever collides.
2145
+ */
2146
+ const localOutputPath = (p) => {
2147
+ const dot = p.filename.lastIndexOf(".");
2148
+ const ext = dot === -1 ? "" : p.filename.slice(dot);
2149
+ const base = dot === -1 ? p.filename : p.filename.slice(0, dot);
2150
+ const counterMatch = /_(\d+)_$/.exec(base);
2151
+ const counter = counterMatch?.[1];
2152
+ const serverStem = counterMatch != null ? base.slice(0, base.length - counterMatch[0].length) : base;
2153
+ let dir;
2154
+ let stem;
2155
+ if (p.filenamePrefix != null && p.filenamePrefix !== "") {
2156
+ const slash = p.filenamePrefix.lastIndexOf("/");
2157
+ dir = slash === -1 ? "" : p.filenamePrefix.slice(0, slash);
2158
+ stem = slash === -1 ? p.filenamePrefix : p.filenamePrefix.slice(slash + 1);
2159
+ } else {
2160
+ dir = p.subfolder;
2161
+ stem = serverStem;
2162
+ }
2163
+ if (p.localDir != null) dir = p.localDir;
2164
+ const name = [
2165
+ stem === "" ? null : stem,
2166
+ p.timestamp,
2167
+ counter
2168
+ ].filter((x) => x != null).join("_") + ext;
2169
+ return dir === "" ? name : `${dir}/${name}`;
2170
+ };
2171
+ /**
2172
+ * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR
2173
+ * was already CLAIMED by a still-downloading retrieval (two same-second runs
2174
+ * on a counter-resetting cloud host compute the same name — reviewer catch).
2175
+ * The chosen path is claimed before returning.
2176
+ */
2177
+ const uniquifyOutputPath = (p) => {
2178
+ let out = p.path;
2179
+ if (p.exists(out) || p.claimed.has(out)) {
2180
+ const dot = out.lastIndexOf(".");
2181
+ const stem = dot === -1 ? out : out.slice(0, dot);
2182
+ const ext = dot === -1 ? "" : out.slice(dot);
2183
+ for (let n = 2; p.exists(out) || p.claimed.has(out); n++) out = `${stem}-${n}${ext}`;
2184
+ }
2185
+ p.claimed.add(out);
2186
+ return out;
2187
+ };
2188
+ /** YYYYMMDD-HHmmss, local time — sortable, text-encodable, no colons for filesystems */
2189
+ const runTimestamp = (d) => {
2190
+ const pad = (n) => String(n).padStart(2, "0");
2191
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
2192
+ };
2193
+ //#endregion
2113
2194
  //#region src/types/index.ts
2114
2195
  const asAbsolutePath = (path) => path;
2115
2196
  const resultSuccess = (value) => ({
@@ -2442,6 +2523,9 @@ var MediaImage = class MediaImage {
2442
2523
  };
2443
2524
  //#endregion
2444
2525
  //#region src/runner/ComfyExecution.ts
2526
+ /** paths claimed by in-flight retrievals: two same-second runs on a
2527
+ * counter-resetting cloud host compute the same name before either writes */
2528
+ const CLAIMED_OUTPUT_PATHS = /* @__PURE__ */ new Set();
2445
2529
  var ComfyExecution = class {
2446
2530
  get host() {
2447
2531
  return this.workflow.host;
@@ -2507,11 +2591,23 @@ var ComfyExecution = class {
2507
2591
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
2508
2592
  const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
2509
2593
  const sf = this.saveFormat;
2510
- let absPath = comfyts.resolveFromOutput(join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename));
2594
+ const promptPrefix = promptNode.inputs["filename_prefix"];
2595
+ let absPath = comfyts.resolveFromOutput(localOutputPath({
2596
+ localDir: sf?.prefix,
2597
+ filenamePrefix: typeof promptPrefix === "string" ? promptPrefix : void 0,
2598
+ subfolder: comfyImageInfo.subfolder,
2599
+ filename: comfyImageInfo.filename,
2600
+ timestamp: runTimestamp(new Date(this.startedAt))
2601
+ }));
2511
2602
  if (sf?.format && sf.format !== "raw") {
2512
2603
  const extension = sf.format.split("/")[1];
2513
2604
  absPath += "." + extension;
2514
2605
  }
2606
+ absPath = uniquifyOutputPath({
2607
+ path: absPath,
2608
+ exists: existsSync,
2609
+ claimed: CLAIMED_OUTPUT_PATHS
2610
+ });
2515
2611
  mkdirSync(dirname(absPath), { recursive: true });
2516
2612
  let img;
2517
2613
  if (sf && sf.format !== "raw") {
@@ -3051,19 +3147,6 @@ types.ComfyInputType;
3051
3147
  types.ComfyEnumDef;
3052
3148
  types.ComfyInputOpts;
3053
3149
  //#endregion
3054
- //#region src/utils/extractErrorMessage.ts
3055
- /** Extracts an error message from an exception stuff. */
3056
- const extractErrorMessage = (error) => {
3057
- if (error instanceof Error) return error.message;
3058
- if (error === null) return "null";
3059
- if (typeof error === "string") return error;
3060
- if (typeof error === "object") {
3061
- if ("message" in error && typeof error.message === "string") return error.message;
3062
- return JSON.stringify(error);
3063
- }
3064
- return String(error);
3065
- };
3066
- //#endregion
3067
3150
  //#region src/utils/stringifyReadable.ts
3068
3151
  const tab = " ";
3069
3152
  function readableStringify(obj, maxLevel = 3, level = 0) {
@@ -3440,657 +3523,6 @@ var ResilientWebSocketClient = class {
3440
3523
  }
3441
3524
  };
3442
3525
  //#endregion
3443
- //#region src/vars/loraKeywords.ts
3444
- /**
3445
- * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras
3446
- * overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at
3447
- * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
3448
- * and must survive a cache wipe). Observable map: overlay rows re-render on
3449
- * assignment. Keys are the RAW lora names (folder/file.safetensors).
3450
- */
3451
- const keywords = observable.map();
3452
- let loaded = false;
3453
- function filePath() {
3454
- return join(comfyts.baseFolder, "lora-keywords.json");
3455
- }
3456
- function loadOnce() {
3457
- if (loaded) return;
3458
- loaded = true;
3459
- const path = filePath();
3460
- if (!existsSync(path)) return;
3461
- try {
3462
- const raw = JSON.parse(readFileSync(path, "utf8"));
3463
- if (raw == null || typeof raw !== "object") return;
3464
- runInAction(() => {
3465
- for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
3466
- });
3467
- } catch (e) {
3468
- logError(`[loraKeywords] unreadable ${path}: ${String(e)}`);
3469
- }
3470
- }
3471
- function getLoraKeyword(name) {
3472
- loadOnce();
3473
- return keywords.get(name) ?? "";
3474
- }
3475
- /** empty keyword deletes the entry; every set writes the file (tiny, rare) */
3476
- function setLoraKeyword(name, keyword) {
3477
- loadOnce();
3478
- const trimmed = keyword.trim();
3479
- runInAction(() => {
3480
- if (trimmed === "") keywords.delete(name);
3481
- else keywords.set(name, trimmed);
3482
- });
3483
- const path = filePath();
3484
- try {
3485
- mkdirSync(dirname(path), { recursive: true });
3486
- writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3487
- } catch (e) {
3488
- logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
3489
- }
3490
- }
3491
- //#endregion
3492
- //#region src/vars/ComfyVars.ts
3493
- /**
3494
- * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
3495
- * time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is
3496
- * the one Out-specialized var (string in, PromptValue out); the split keeps
3497
- * outValue() cast-free.
3498
- */
3499
- var ComfyVarBase = class {
3500
- constructor(defaultValue, label) {
3501
- this.defaultValue = defaultValue;
3502
- this.label = label;
3503
- this.value = defaultValue;
3504
- makeObservable(this, {
3505
- value: observable,
3506
- set: action,
3507
- reset: action,
3508
- parse: action,
3509
- loadJSON: action
3510
- });
3511
- }
3512
- set(value) {
3513
- this.value = value;
3514
- return this;
3515
- }
3516
- /** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */
3517
- toJSON() {
3518
- return this.value;
3519
- }
3520
- /**
3521
- * restore a value produced by toJSON() (drafts). The cast is sanctioned:
3522
- * drafts are our own round-trip, subclasses re-validate via set().
3523
- */
3524
- loadJSON(value) {
3525
- return this.set(value);
3526
- }
3527
- reset() {
3528
- this.value = this.defaultValue;
3529
- return this;
3530
- }
3531
- /** how the value renders in a var list */
3532
- display() {
3533
- return String(this.value);
3534
- }
3535
- /** the string the inline editor starts from (round-trips through parse) */
3536
- toEditBuffer() {
3537
- return String(this.value);
3538
- }
3539
- /** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */
3540
- afterRun() {}
3541
- };
3542
- /** the standard var: the graph consumes the stored value AS-IS (Out = T) */
3543
- var ComfyVar = class extends ComfyVarBase {
3544
- outValue() {
3545
- return this.value;
3546
- }
3547
- };
3548
- var TextVar = class extends ComfyVar {
3549
- constructor(..._args) {
3550
- super(..._args);
3551
- this.kind = "text";
3552
- }
3553
- parse(raw) {
3554
- this.set(raw);
3555
- return true;
3556
- }
3557
- };
3558
- const commentLineRe = /^\s*\/\//;
3559
- const negativeLineRe = /^\s*- (.*)$/;
3560
- /**
3561
- * prompt text with editor comforts, all resolved at BUILD time (the editor and
3562
- * drafts keep the raw text):
3563
- * - `//` lines are COMMENTS — stripped
3564
- * - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,
3565
- * comma-joined into `.negative`
3566
- * - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords
3567
- * (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —
3568
- * `injectedKeywords()` is public so the TUI can PREVIEW the injection.
3569
- */
3570
- var PromptVar = class extends ComfyVarBase {
3571
- constructor(defaultValue, promptOpts = {}) {
3572
- super(defaultValue, promptOpts.label);
3573
- this.promptOpts = promptOpts;
3574
- this.kind = "text";
3575
- }
3576
- parse(raw) {
3577
- this.set(raw);
3578
- return true;
3579
- }
3580
- static isCommentLine(line) {
3581
- return commentLineRe.test(line);
3582
- }
3583
- static isNegativeLine(line) {
3584
- return negativeLineRe.test(line);
3585
- }
3586
- /** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */
3587
- injectedKeywords() {
3588
- const src = this.promptOpts.loraKeywordsFrom;
3589
- if (src == null) return [];
3590
- return [...new Set(src.activeNames().map(getLoraKeyword).filter((k) => k !== ""))];
3591
- }
3592
- outValue() {
3593
- const pos = [];
3594
- const neg = [];
3595
- for (const line of this.value.split("\n")) {
3596
- if (commentLineRe.test(line)) continue;
3597
- const m = negativeLineRe.exec(line);
3598
- if (m != null) {
3599
- const text = (m[1] ?? "").trim();
3600
- if (text !== "") neg.push(text);
3601
- } else pos.push(line);
3602
- }
3603
- const body = pos.join("\n").trim();
3604
- const keywords = this.injectedKeywords();
3605
- return {
3606
- positive: keywords.length === 0 ? body : body === "" ? keywords.join(", ") : `${keywords.join(", ")}, ${body}`,
3607
- negative: neg.join(", ")
3608
- };
3609
- }
3610
- };
3611
- var IntVar = class extends ComfyVar {
3612
- constructor(defaultValue, opts = {}) {
3613
- super(defaultValue, opts.label);
3614
- this.opts = opts;
3615
- this.kind = "int";
3616
- }
3617
- set(value) {
3618
- const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
3619
- return super.set(clamped);
3620
- }
3621
- parse(raw) {
3622
- const n = Number(raw);
3623
- if (Number.isNaN(n)) return false;
3624
- this.set(n);
3625
- return true;
3626
- }
3627
- };
3628
- var FloatVar = class extends ComfyVar {
3629
- constructor(defaultValue, opts = {}) {
3630
- super(defaultValue, opts.label);
3631
- this.opts = opts;
3632
- this.kind = "float";
3633
- }
3634
- set(value) {
3635
- return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
3636
- }
3637
- parse(raw) {
3638
- const n = Number(raw);
3639
- if (Number.isNaN(n)) return false;
3640
- this.set(n);
3641
- return true;
3642
- }
3643
- };
3644
- /**
3645
- * a seed is a MODE + a number. `value` stays a plain number (what the graph
3646
- * consumes); `mode` decides how it advances after each run (afterRun()):
3647
- * `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.
3648
- * The number shown is always the seed the NEXT run will use.
3649
- */
3650
- var SeedVar = class extends ComfyVar {
3651
- constructor(defaultValue = 0, label) {
3652
- super(defaultValue, label);
3653
- this.kind = "seed";
3654
- this.mode = "=";
3655
- makeObservable(this, {
3656
- mode: observable,
3657
- setMode: action,
3658
- randomize: action,
3659
- advance: action
3660
- });
3661
- }
3662
- setMode(mode) {
3663
- this.mode = mode;
3664
- return this;
3665
- }
3666
- randomize() {
3667
- return this.set(Math.floor(Math.random() * 2 ** 32));
3668
- }
3669
- set(value) {
3670
- return super.set(Math.max(0, Math.floor(value)));
3671
- }
3672
- /** move the seed to what the NEXT run should use, per mode */
3673
- advance() {
3674
- if (this.mode === "+") return this.set(this.value + 1);
3675
- if (this.mode === "-") return this.set(this.value - 1);
3676
- if (this.mode === "?") return this.randomize();
3677
- return this;
3678
- }
3679
- afterRun() {
3680
- this.advance();
3681
- }
3682
- /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
3683
- parse(raw) {
3684
- const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/);
3685
- if (m == null) return false;
3686
- const modeChar = m[1];
3687
- const numStr = m[2];
3688
- if (modeChar == null && numStr == null) return false;
3689
- this.setMode(modeChar == null ? "=" : modeChar);
3690
- if (numStr != null) this.set(Number(numStr));
3691
- return true;
3692
- }
3693
- display() {
3694
- return `${this.mode} ${this.value}`;
3695
- }
3696
- toEditBuffer() {
3697
- return `${this.mode} ${this.value}`;
3698
- }
3699
- toJSON() {
3700
- return {
3701
- mode: this.mode,
3702
- value: this.value
3703
- };
3704
- }
3705
- loadJSON(value) {
3706
- if (typeof value === "number") return this.set(value);
3707
- if (value != null && typeof value === "object") {
3708
- const o = value;
3709
- if (o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?") this.setMode(o.mode);
3710
- if (typeof o.value === "number") this.set(o.value);
3711
- }
3712
- return this;
3713
- }
3714
- };
3715
- var ToggleVar = class extends ComfyVar {
3716
- constructor(..._args2) {
3717
- super(..._args2);
3718
- this.kind = "toggle";
3719
- }
3720
- toggle() {
3721
- return this.set(!this.value);
3722
- }
3723
- parse(raw) {
3724
- if (raw !== "true" && raw !== "false") return false;
3725
- this.set(raw === "true");
3726
- return true;
3727
- }
3728
- display() {
3729
- return this.value ? "ON" : "OFF";
3730
- }
3731
- };
3732
- var ChoiceVar = class extends ComfyVar {
3733
- constructor(choices, defaultValue, label) {
3734
- super(defaultValue, label);
3735
- this.choices = choices;
3736
- this.kind = "choice";
3737
- }
3738
- next(delta = 1) {
3739
- const nextIx = (this.choices.indexOf(this.value) + delta + this.choices.length) % this.choices.length;
3740
- return this.set(this.choices[nextIx] ?? this.value);
3741
- }
3742
- parse(raw) {
3743
- const hit = this.choices.find((c) => c === raw);
3744
- if (hit == null) return false;
3745
- this.set(hit);
3746
- return true;
3747
- }
3748
- };
3749
- /**
3750
- * multi-select lora stack over a DYNAMIC options list — a RegExp resolves
3751
- * against the host's loras at define time (DefinedWorkflow calls bindHost),
3752
- * or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never
3753
- * a hardcoded inventory. Selection is empty by default.
3754
- */
3755
- var LorasVar = class LorasVar extends ComfyVar {
3756
- constructor(optionsSource, initial = {}, label) {
3757
- super(initial, label);
3758
- this.optionsSource = optionsSource;
3759
- this.kind = "loras";
3760
- this.prev = {};
3761
- this.resolvedOptions = null;
3762
- }
3763
- get options() {
3764
- if (!(this.optionsSource instanceof RegExp)) return this.optionsSource;
3765
- 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)`);
3766
- return this.resolvedOptions;
3767
- }
3768
- /** DefinedWorkflow binds the host at define time: a RegExp source resolves here.
3769
- * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
3770
- * values of the SAME object_info enum the generated E_LoraName union comes from */
3771
- bindHost(host) {
3772
- if (!(this.optionsSource instanceof RegExp)) return;
3773
- this.resolvedOptions = host.schema.getLoras(this.optionsSource);
3774
- }
3775
- get names() {
3776
- return [...this.options];
3777
- }
3778
- /** loras currently ON (PromptVar keyword prefixing consumes this) */
3779
- activeNames() {
3780
- return this.names.filter((n) => this.isOn(n));
3781
- }
3782
- isOn(name) {
3783
- const s = this.value[name];
3784
- return s != null && s !== false;
3785
- }
3786
- toggleItem(name) {
3787
- const cur = this.value[name];
3788
- if (cur == null || cur === false) return this.set({
3789
- ...this.value,
3790
- [name]: this.prev[name] ?? true
3791
- });
3792
- this.prev[name] = cur;
3793
- return this.set({
3794
- ...this.value,
3795
- [name]: false
3796
- });
3797
- }
3798
- /** step both strengths by delta (true becomes 1 first); no-op when off */
3799
- adjustItem(name, delta) {
3800
- const cur = this.value[name];
3801
- if (cur == null || cur === false) return this;
3802
- const step = (n) => Math.max(0, Math.round((n + delta) * 100) / 100);
3803
- const next = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur);
3804
- return this.set({
3805
- ...this.value,
3806
- [name]: next
3807
- });
3808
- }
3809
- /** compact per-item strength label for lists */
3810
- strengthLabel(name) {
3811
- const s = this.value[name];
3812
- if (s == null || s === false) return "";
3813
- if (s === true) return "1.00";
3814
- if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`;
3815
- return s.toFixed(2);
3816
- }
3817
- parse(raw) {
3818
- try {
3819
- const parsed = JSON.parse(raw);
3820
- if (typeof parsed !== "object" || parsed == null || Array.isArray(parsed)) return false;
3821
- this.set(parsed);
3822
- return true;
3823
- } catch {
3824
- return false;
3825
- }
3826
- }
3827
- /** short human name: subfolder + extension stripped */
3828
- static shortName(name) {
3829
- return (name.split(/[\\/]/).pop() ?? name).replace(/\.safetensors$/, "");
3830
- }
3831
- /** tick (true) or untick (false) every lora in `names` (default: all options) */
3832
- setAll(on, names = this.options) {
3833
- const next = { ...this.value };
3834
- for (const name of names) {
3835
- const cur = next[name];
3836
- if (on) {
3837
- if (cur == null || cur === false) next[name] = this.prev[name] ?? true;
3838
- } else {
3839
- if (cur != null && cur !== false) this.prev[name] = cur;
3840
- next[name] = false;
3841
- }
3842
- }
3843
- return this.set(next);
3844
- }
3845
- display() {
3846
- const on = this.activeNames();
3847
- if (on.length === 0) return `(0/${this.options.length}) none`;
3848
- return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(", ")}`;
3849
- }
3850
- };
3851
- /** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */
3852
- const DEFAULT_SIZE_PRESETS = [
3853
- {
3854
- label: "1:1 square",
3855
- width: 1024,
3856
- height: 1024
3857
- },
3858
- {
3859
- label: "4:3 landscape",
3860
- width: 1152,
3861
- height: 896
3862
- },
3863
- {
3864
- label: "3:4 portrait",
3865
- width: 896,
3866
- height: 1152
3867
- },
3868
- {
3869
- label: "3:2 landscape",
3870
- width: 1216,
3871
- height: 832
3872
- },
3873
- {
3874
- label: "2:3 portrait",
3875
- width: 832,
3876
- height: 1216
3877
- },
3878
- {
3879
- label: "16:9 widescreen",
3880
- width: 1344,
3881
- height: 768
3882
- },
3883
- {
3884
- label: "9:16 tall",
3885
- width: 768,
3886
- height: 1344
3887
- }
3888
- ];
3889
- /** width/height picker: presets + free `WxH` entry + optionally the LIVE
3890
- * size of a linked image var (his ask 2026-07-30: the widget shows
3891
- * `WxH size of image '<name>'` as a pickable row) */
3892
- var SizeVar = class extends ComfyVar {
3893
- constructor(defaultValue = {
3894
- width: 1024,
3895
- height: 1024
3896
- }, presets = DEFAULT_SIZE_PRESETS, label, imageVar) {
3897
- super(defaultValue, label);
3898
- this.presets = presets;
3899
- this.imageVar = imageVar;
3900
- this.kind = "size";
3901
- }
3902
- /** current dimensions of the linked image var — null when no link, unset
3903
- * path, or an unreadable/undecodable file (those errors belong to the
3904
- * image var itself, the size row simply disappears) */
3905
- imageSize() {
3906
- const iv = this.imageVar;
3907
- if (iv == null || iv.value === "") return null;
3908
- try {
3909
- const abs = iv.absPath();
3910
- const meta = imageMeta(new Uint8Array(readFileSync(abs)));
3911
- if (meta.width == null || meta.height == null) return null;
3912
- return {
3913
- width: meta.width,
3914
- height: meta.height,
3915
- name: basename(abs)
3916
- };
3917
- } catch {
3918
- return null;
3919
- }
3920
- }
3921
- /** accepts '1024x768' / '1024×768' / a preset label */
3922
- parse(raw) {
3923
- const m = raw.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/);
3924
- if (m != null) {
3925
- this.set({
3926
- width: Number(m[1]),
3927
- height: Number(m[2])
3928
- });
3929
- return true;
3930
- }
3931
- const preset = this.presets.find((p) => p.label === raw.trim());
3932
- if (preset != null) {
3933
- this.set({
3934
- width: preset.width,
3935
- height: preset.height
3936
- });
3937
- return true;
3938
- }
3939
- return false;
3940
- }
3941
- display() {
3942
- const { width, height } = this.value;
3943
- const hit = this.presets.find((p) => p.width === width && p.height === height);
3944
- return `${width}×${height}${hit ? ` (${hit.label})` : ""}`;
3945
- }
3946
- };
3947
- const DEFAULT_IMAGE_EXTENSIONS = [
3948
- "png",
3949
- "jpg",
3950
- "jpeg",
3951
- "webp",
3952
- "gif"
3953
- ];
3954
- /** empty image var consumed at build time — typed so drivers surface it apart from real crashes */
3955
- var ImageVarEmptyError = class extends Error {
3956
- constructor(varName) {
3957
- super(`image var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/image.png'))`);
3958
- this.varName = varName;
3959
- }
3960
- };
3961
- /** trim + expand a leading `~/` — every ImageVar write funnels through this */
3962
- function expandUserPath(raw) {
3963
- const trimmed = raw.trim();
3964
- return trimmed.startsWith("~/") ? join(homedir(), trimmed.slice(2)) : trimmed;
3965
- }
3966
- /**
3967
- * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
3968
- * drafts persist it verbatim (toJSON = the string), hand-editable in the
3969
- * draft json. Empty = unset: outValue()/absPath() throw ImageVarEmptyError,
3970
- * so a build never runs on a silent placeholder. The TUI opens the image
3971
- * picker overlay for kind 'image'.
3972
- */
3973
- var ImageVar = class extends ComfyVar {
3974
- constructor(defaultValue, opts = {}) {
3975
- super(expandUserPath(defaultValue), opts.label);
3976
- this.opts = opts;
3977
- this.kind = "image";
3978
- }
3979
- /** what the picker lists (lowercase, no dots) */
3980
- get extensions() {
3981
- return this.opts.extensions ?? DEFAULT_IMAGE_EXTENSIONS;
3982
- }
3983
- set(value) {
3984
- return super.set(expandUserPath(value));
3985
- }
3986
- parse(raw) {
3987
- this.set(raw);
3988
- return true;
3989
- }
3990
- isSet() {
3991
- return this.value !== "";
3992
- }
3993
- emptyError() {
3994
- return new ImageVarEmptyError(this.name ?? this.label ?? "image");
3995
- }
3996
- /** the ONE resolution helper: absolute kept as-is, relative resolved against opts.folder, else cwd */
3997
- absPath() {
3998
- if (!this.isSet()) throw this.emptyError();
3999
- if (isAbsolute(this.value)) return this.value;
4000
- return resolve(this.opts.folder ?? process.cwd(), this.value);
4001
- }
4002
- /** empty = unset: the build fails LOUD here (varValues calls outValue) */
4003
- outValue() {
4004
- if (!this.isSet()) throw this.emptyError();
4005
- return this.value;
4006
- }
4007
- display() {
4008
- if (!this.isSet()) return "(unset) pick a file";
4009
- const home = homedir();
4010
- return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
4011
- }
4012
- };
4013
- /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size / v.image */
4014
- const v = {
4015
- text: (defaultValue, label) => new TextVar(defaultValue, label),
4016
- prompt: (defaultValue, opts = {}) => new PromptVar(defaultValue, opts),
4017
- int: (defaultValue, opts = {}) => new IntVar(defaultValue, opts),
4018
- float: (defaultValue, opts = {}) => new FloatVar(defaultValue, opts),
4019
- seed: (defaultValue = 0, label) => new SeedVar(defaultValue, label),
4020
- toggle: (defaultValue, label) => new ToggleVar(defaultValue, label),
4021
- choice: (choices, defaultValue, label) => new ChoiceVar(choices, defaultValue, label),
4022
- loras: (options, initial = {}, label) => new LorasVar(options, initial, label),
4023
- size: (defaultValue, opts = {}) => new SizeVar(defaultValue, opts.presets, opts.label, opts.image),
4024
- image: (defaultValue, opts = {}) => new ImageVar(defaultValue, opts)
4025
- };
4026
- function varValues(vars) {
4027
- const out = {};
4028
- for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue();
4029
- return out;
4030
- }
4031
- //#endregion
4032
- //#region src/vars/DefinedWorkflow.ts
4033
- /** type predicate (not a cast): a VarsSpec is a plain record, never callable */
4034
- function isVarsThunk(vars) {
4035
- return typeof vars === "function";
4036
- }
4037
- /**
4038
- * a re-runnable workflow definition: `build` re-executes per run with the
4039
- * current var values, so every run gets a fresh, deterministic graph.
4040
- */
4041
- var DefinedWorkflow = class {
4042
- constructor(host, spec) {
4043
- this.host = host;
4044
- this.spec = spec;
4045
- this.lastWorkflow = null;
4046
- this.lastExecution = null;
4047
- this.vars = isVarsThunk(spec.vars) ? spec.vars(v) : spec.vars;
4048
- for (const [key, varDef] of this.entries()) {
4049
- varDef.name = key;
4050
- varDef.bindHost?.(this.host);
4051
- }
4052
- }
4053
- /** [name, var] pairs, for drivers that enumerate the knobs */
4054
- entries() {
4055
- return Object.entries(this.vars);
4056
- }
4057
- /**
4058
- * build a fresh graph from the CURRENT var values (no send). `p.advance`
4059
- * (set by run()) fires each var's afterRun() right after snapshotting the
4060
- * values — atomically, before any await — so the graph uses this run's seed
4061
- * while the var moves to the next (queued runs get distinct seeds; a bare
4062
- * build() for copy/export never advances). `p.host` substitutes the host
4063
- * the graph is built against (TUI host override): node/model availability
4064
- * there surfaces as workflow.problems / server validation, by design.
4065
- */
4066
- async build(p = {}) {
4067
- const wf = (p.host ?? this.host).workflow({ id: this.spec.id });
4068
- const values = varValues(this.vars);
4069
- if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun();
4070
- await this.spec.build(wf.builder, values, wf);
4071
- this.lastWorkflow = wf;
4072
- return wf;
4073
- }
4074
- /** build a fresh graph from the current var values, send it, wait for outputs.
4075
- * connects first (idempotent) — modules can import offline from the schema cache.
4076
- * `settings.host` runs against THAT host instead of the defining one. */
4077
- async run(settings = {}) {
4078
- const host = settings.host ?? this.host;
4079
- await host.connect();
4080
- const execution = await (await this.build({
4081
- advance: true,
4082
- host
4083
- })).run({
4084
- saveFormat: settings.saveFormat,
4085
- idMode: settings.idMode,
4086
- log: settings.log,
4087
- onProgress: settings.onProgress
4088
- });
4089
- this.lastExecution = execution;
4090
- return execution;
4091
- }
4092
- };
4093
- //#endregion
4094
3526
  //#region src/host/ComfyHost.ts
4095
3527
  /** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):
4096
3528
  * 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive
@@ -5253,6 +4685,6 @@ var ComfyTS = class ComfyTS {
5253
4685
  }
5254
4686
  };
5255
4687
  //#endregion
5256
- export { PromptVar as a, readableStringify as c, ComfySchema as d, logError as f, LorasVar as i, extractErrorMessage as l, settingsPathFor as n, getLoraKeyword as o, DefinedWorkflow as r, setLoraKeyword as s, ComfyTS as t, stripAnsi as u };
4688
+ export { ComfySchema as a, stripAnsi as i, settingsPathFor as n, readableStringify as r, ComfyTS as t };
5257
4689
 
5258
- //# sourceMappingURL=state-BYbxDgfr.js.map
4690
+ //# sourceMappingURL=state-DKCPy105.js.map