comfy-ts 0.3.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +349 -255
  2. package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
  3. package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
  4. package/dist/cli.js +3969 -128
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1208 -170
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +449 -115
  9. package/dist/index.d.ts +449 -115
  10. package/dist/index.js +1200 -171
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-Io8Xea0L.js → run-tui-BFhba_oG.js} +744 -665
  13. package/dist/run-tui-BFhba_oG.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +66 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +67 -0
  19. package/examples/comfy-cloud/sdk.d.ts +122674 -0
  20. package/guide-for-agents.md +166 -0
  21. package/package.json +7 -3
  22. package/src/cli/comfy-ts-cli.ts +19 -2
  23. package/src/cli/gen.ts +21 -12
  24. package/src/cli/tui/components/Header.tsx +5 -0
  25. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +52 -7
  27. package/src/cli/tui/components/StatusBar.tsx +10 -4
  28. package/src/cli/tui/components/TreePanel.tsx +15 -2
  29. package/src/cli/tui/components/TuiApp.tsx +26 -3
  30. package/src/cli/tui/discoverWorkflows.ts +79 -0
  31. package/src/cli/tui/protocolImagePainter.ts +54 -18
  32. package/src/cli/tui/run-tui.tsx +55 -24
  33. package/src/cli/tui/state/ExecSt.ts +4 -1
  34. package/src/cli/tui/state/HostSt.ts +123 -1
  35. package/src/cli/tui/state/LogsSt.ts +107 -0
  36. package/src/cli/tui/state/PreviewSt.ts +173 -23
  37. package/src/cli/tui/state/SettingsSt.ts +48 -21
  38. package/src/cli/tui/state/TreeSt.ts +30 -6
  39. package/src/cli/tui/state/TuiSt.ts +27 -3
  40. package/src/cli/tui/state/WorkflowsSt.ts +16 -1
  41. package/src/host/ComfyHost.ts +241 -71
  42. package/src/host/ComfyManager.ts +10 -9
  43. package/src/host/ComfyUploader.ts +1 -2
  44. package/src/host/ResilientWebsocket.ts +3 -1
  45. package/src/host/hostUrl.ts +59 -0
  46. package/src/host/loraManagerApi.ts +5 -4
  47. package/src/index.ts +20 -1
  48. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  49. package/src/litegraph/LiteGraphGroup.ts +9 -7
  50. package/src/litegraph/LiteGraphJSON.ts +34 -13
  51. package/src/litegraph/LiteGraphLink.ts +32 -2
  52. package/src/litegraph/LiteGraphNode.ts +18 -33
  53. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  54. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  55. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  56. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  57. package/src/litegraph/expandSubgraphs.ts +352 -0
  58. package/src/litegraph/normalizeWorkflow.ts +141 -0
  59. package/src/runner/ComfyExecution.ts +4 -5
  60. package/src/runner/ComfyWorkflow.ts +2 -2
  61. package/src/runner/ComfyWsApi.ts +12 -1
  62. package/src/runner/wsBinaryFrame.ts +48 -0
  63. package/src/sdk-generator/Primitives.ts +6 -24
  64. package/src/sdk-generator/comfy-api-json.ts +3 -1
  65. package/src/sdk-generator/inputWidgetKind.ts +179 -0
  66. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  67. package/src/ssh-host-manager/ssh-manager.ts +0 -15
  68. package/src/state.ts +13 -2
  69. package/src/utils/ansi.ts +7 -0
  70. package/src/utils/mojibake.ts +60 -0
  71. package/dist/log-CdfgILde.js +0 -10
  72. package/dist/log-CdfgILde.js.map +0 -1
  73. package/dist/run-tui-Io8Xea0L.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -39,7 +39,597 @@ node_https = __toESM(node_https, 1);
39
39
  let node_process = require("node:process");
40
40
  let fs = require("fs");
41
41
  //#region package.json
42
- var version = "0.3.0";
42
+ var version = "1.0.0";
43
+ //#endregion
44
+ //#region src/litegraph/LiteGraphLinkID.ts
45
+ const asLiteGraphLinkID = (id) => id;
46
+ const LiteGraphLinkID_ = arktype.type.number.atLeast(0).as();
47
+ //#endregion
48
+ //#region src/utils/bang.ts
49
+ /** assertNotNull */
50
+ const bang = (x, msg = "") => {
51
+ if (x == null) {
52
+ console.error(`[🔴] BANG FAILED`, msg);
53
+ throw new Error("bang: " + (msg ?? "no message"));
54
+ }
55
+ return x;
56
+ };
57
+ //#endregion
58
+ //#region src/litegraph/expandSubgraphs.ts
59
+ /** boundary sentinel ids inside definition link tables */
60
+ const SUBGRAPH_INPUT_NODE_ID = -10;
61
+ const SUBGRAPH_OUTPUT_NODE_ID = -20;
62
+ /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
63
+ const MAX_EXPANSION_PASSES = 32;
64
+ /**
65
+ * widget-kind fallback when a def input slot has no boundary target carrying a
66
+ * widget marker: these litegraph slot types carry widget values. LOCAL copy on
67
+ * purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here
68
+ * (the io-widget era serializes exactly one value per exposed widget slot).
69
+ */
70
+ const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
71
+ "INT",
72
+ "FLOAT",
73
+ "STRING",
74
+ "BOOLEAN",
75
+ "COMBO"
76
+ ]);
77
+ /**
78
+ * inline every subgraph instance (node whose `type` is a definition uuid) into
79
+ * the root graph: fresh numeric ids, boundary links rewired, instance widget
80
+ * values promoted into the inner nodes' `named` overrides. Iterative so nested
81
+ * definitions expand on the next pass. Muted instances are dropped (their
82
+ * consumers resolve unconnected); bypassed instances stay for the converter's
83
+ * passthrough walk, which needs no interior.
84
+ */
85
+ const expandSubgraphs = (wf, defs) => {
86
+ let passes = 0;
87
+ while (true) {
88
+ const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
89
+ if (expandable.length === 0) return wf;
90
+ if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
91
+ for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
92
+ else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
93
+ }
94
+ };
95
+ /** converter mute semantics applied early: after expansion there is no single node left to skip */
96
+ const dropMutedInstance = (wf, instance) => {
97
+ const dead = /* @__PURE__ */ new Set();
98
+ for (const link of wf.links) if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id);
99
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
100
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
101
+ pruneDeadLinkRefs(wf, dead);
102
+ };
103
+ const pruneDeadLinkRefs = (wf, dead) => {
104
+ if (dead.size === 0) return;
105
+ for (const node of wf.nodes) {
106
+ for (const input of node.inputs) if (input.link != null && dead.has(input.link)) input.link = null;
107
+ for (const output of node.outputs) output.links = output.links.filter((id) => !dead.has(id));
108
+ }
109
+ };
110
+ const expandOneInstance = (wf, instance, def) => {
111
+ let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id));
112
+ let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id));
113
+ const newNodeIds = /* @__PURE__ */ new Map();
114
+ for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId);
115
+ const remapNodeId = (id) => newNodeIds.get(id) ?? null;
116
+ const defSlotOfInstanceSlot = /* @__PURE__ */ new Map();
117
+ for (const [k, input] of instance.inputs.entries()) {
118
+ const defSlot = def.inputs.findIndex((d) => d.name === input.name);
119
+ if (defSlot < 0) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): input "${input.name}" (slot ${k}) matches no definition input (defined: ${def.inputs.map((d) => d.name).join(", ")})`);
120
+ defSlotOfInstanceSlot.set(k, defSlot);
121
+ }
122
+ const outerLinkIntoDefSlot = /* @__PURE__ */ new Map();
123
+ for (const link of wf.links) {
124
+ if (link.targetId !== instance.id) continue;
125
+ const defSlot = defSlotOfInstanceSlot.get(link.targetSlot);
126
+ if (defSlot == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`);
127
+ outerLinkIntoDefSlot.set(defSlot, link);
128
+ }
129
+ const newLinkIds = /* @__PURE__ */ new Map();
130
+ const splicedLinks = [];
131
+ const producerByOutSlot = /* @__PURE__ */ new Map();
132
+ const passthroughOutSlot = /* @__PURE__ */ new Map();
133
+ const boundaryTargetsByInSlot = /* @__PURE__ */ new Map();
134
+ for (const link of def.links) {
135
+ const fromInputBoundary = link.originId === SUBGRAPH_INPUT_NODE_ID;
136
+ const toOutputBoundary = link.targetId === SUBGRAPH_OUTPUT_NODE_ID;
137
+ if (fromInputBoundary && toOutputBoundary) {
138
+ passthroughOutSlot.set(link.targetSlot, link.originSlot);
139
+ continue;
140
+ }
141
+ if (toOutputBoundary) {
142
+ const producerId = remapNodeId(link.originId);
143
+ if (producerId != null && !producerByOutSlot.has(link.targetSlot)) producerByOutSlot.set(link.targetSlot, {
144
+ nodeId: producerId,
145
+ slot: link.originSlot
146
+ });
147
+ continue;
148
+ }
149
+ if (fromInputBoundary) {
150
+ const targetId = remapNodeId(link.targetId);
151
+ if (targetId == null) continue;
152
+ const target = {
153
+ nodeId: targetId,
154
+ slot: link.targetSlot
155
+ };
156
+ const targets = boundaryTargetsByInSlot.get(link.originSlot) ?? [];
157
+ targets.push(target);
158
+ boundaryTargetsByInSlot.set(link.originSlot, targets);
159
+ const outer = outerLinkIntoDefSlot.get(link.originSlot);
160
+ if (outer == null) continue;
161
+ const fresh = asLiteGraphLinkID(++nextLinkId);
162
+ newLinkIds.set(link.id, fresh);
163
+ splicedLinks.push({
164
+ id: fresh,
165
+ originId: outer.originId,
166
+ originSlot: outer.originSlot,
167
+ targetId: target.nodeId,
168
+ targetSlot: target.slot,
169
+ type: link.type
170
+ });
171
+ wf.nodes.find((n) => n.id === outer.originId)?.outputs[outer.originSlot]?.links.push(fresh);
172
+ continue;
173
+ }
174
+ const interiorOrigin = remapNodeId(link.originId);
175
+ const interiorTarget = remapNodeId(link.targetId);
176
+ if (interiorOrigin == null || interiorTarget == null) continue;
177
+ const fresh = asLiteGraphLinkID(++nextLinkId);
178
+ newLinkIds.set(link.id, fresh);
179
+ splicedLinks.push({
180
+ id: fresh,
181
+ originId: interiorOrigin,
182
+ originSlot: link.originSlot,
183
+ targetId: interiorTarget,
184
+ targetSlot: link.targetSlot,
185
+ type: link.type
186
+ });
187
+ }
188
+ const splicedNodes = def.nodes.map((inner) => ({
189
+ id: bang(newNodeIds.get(inner.id)),
190
+ type: inner.type,
191
+ title: inner.title,
192
+ mode: inner.mode,
193
+ isVirtualNode: inner.isVirtualNode,
194
+ inputs: inner.inputs.map((i) => ({
195
+ name: i.name,
196
+ type: i.type,
197
+ link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
198
+ widgetName: i.widgetName
199
+ })),
200
+ outputs: inner.outputs.map((o) => ({
201
+ name: o.name,
202
+ type: o.type,
203
+ links: o.links.map((id) => newLinkIds.get(id)).filter((id) => id != null)
204
+ })),
205
+ widgets: {
206
+ positional: [...inner.widgets.positional],
207
+ named: { ...inner.widgets.named }
208
+ },
209
+ pos: [inner.pos[0], inner.pos[1]],
210
+ size: [inner.size[0], inner.size[1]],
211
+ properties: { ...inner.properties }
212
+ }));
213
+ const dead = /* @__PURE__ */ new Set();
214
+ for (const link of wf.links) {
215
+ if (link.targetId === instance.id) {
216
+ dead.add(link.id);
217
+ continue;
218
+ }
219
+ if (link.originId !== instance.id) continue;
220
+ const producer = producerByOutSlot.get(link.originSlot);
221
+ if (producer != null) {
222
+ link.originId = producer.nodeId;
223
+ link.originSlot = producer.slot;
224
+ splicedNodes.find((n) => n.id === producer.nodeId)?.outputs[producer.slot]?.links.push(link.id);
225
+ continue;
226
+ }
227
+ const passthroughInSlot = passthroughOutSlot.get(link.originSlot);
228
+ const outer = passthroughInSlot != null ? outerLinkIntoDefSlot.get(passthroughInSlot) : null;
229
+ if (outer != null) {
230
+ link.originId = outer.originId;
231
+ link.originSlot = outer.originSlot;
232
+ continue;
233
+ }
234
+ dead.add(link.id);
235
+ }
236
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
237
+ pruneDeadLinkRefs(wf, dead);
238
+ promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
239
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
240
+ wf.nodes.push(...splicedNodes);
241
+ wf.links.push(...splicedLinks);
242
+ };
243
+ /**
244
+ * instance widget values land in inner nodes' `named` overrides. TWO eras for
245
+ * the POSITIONAL values:
246
+ * - proxyWidgets era: `properties.proxyWidgets` pairs [innerNodeId, widgetName]
247
+ * zip against the instance's positional values (incl. `control_after_generate`
248
+ * phantom pairs — written to `named` and simply never read, no schema input
249
+ * has that name).
250
+ * - io-widget era (no proxyWidgets): positional values zip against the def's
251
+ * widget-kind input slots in def order, one value per slot (no phantom —
252
+ * corpus-verified). An outer link into the same slot wins in the converter;
253
+ * the named override is still written, matching ComfyUI.
254
+ * PLUS, in both eras, NAMED overrides on the instance keyed by def-input name:
255
+ * that is how a NESTED instance receives its outer values (the previous pass
256
+ * wrote them to `named`), so they must forward through THIS expansion too —
257
+ * named wins over positional, same precedence as the converter.
258
+ */
259
+ const promoteInstanceWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot) => {
260
+ const promoteToSlotTargets = (slot, value) => {
261
+ for (const t of boundaryTargetsByInSlot.get(slot) ?? []) {
262
+ const target = splicedNodes.find((n) => n.id === t.nodeId);
263
+ const input = innerInputAt(splicedNodes, t);
264
+ if (target == null || input == null) continue;
265
+ target.widgets.named[input.name] = value;
266
+ }
267
+ };
268
+ promotePositionalWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets);
269
+ for (const [slot, io] of def.inputs.entries()) {
270
+ if (!Object.hasOwn(instance.widgets.named, io.name)) continue;
271
+ promoteToSlotTargets(slot, instance.widgets.named[io.name]);
272
+ }
273
+ };
274
+ const promotePositionalWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets) => {
275
+ const values = instance.widgets.positional;
276
+ if (values.length === 0) return;
277
+ const proxy = instance.properties["proxyWidgets"];
278
+ if (Array.isArray(proxy) && proxy.length > 0) {
279
+ const count = Math.min(values.length, proxy.length);
280
+ for (let k = 0; k < count; k++) {
281
+ const pair = proxy[k];
282
+ if (!Array.isArray(pair) || pair.length !== 2) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): malformed proxyWidgets entry ${JSON.stringify(pair)}`);
283
+ const innerId = Number(pair[0]);
284
+ const widgetName = String(pair[1]);
285
+ if (innerId < 0) {
286
+ const slot = def.inputs.findIndex((d) => d.name === widgetName);
287
+ if (slot < 0) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names io widget "${widgetName}" but no definition input matches`);
288
+ promoteToSlotTargets(slot, values[k]);
289
+ continue;
290
+ }
291
+ const target = splicedNodes.find((n) => n.id === newNodeIds.get(innerId));
292
+ if (target == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names unknown inner node ${String(pair[0])}`);
293
+ target.widgets.named[widgetName] = values[k];
294
+ }
295
+ return;
296
+ }
297
+ let valueIndex = 0;
298
+ for (const [slot, io] of def.inputs.entries()) {
299
+ const targets = boundaryTargetsByInSlot.get(slot) ?? [];
300
+ if (!(targets.length > 0 ? targets.some((t) => innerInputAt(splicedNodes, t)?.widgetName != null) : PRIMITIVE_WIDGET_TYPES.has(io.type))) continue;
301
+ if (valueIndex >= values.length) break;
302
+ promoteToSlotTargets(slot, values[valueIndex++]);
303
+ }
304
+ };
305
+ const innerInputAt = (splicedNodes, t) => {
306
+ return splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot] ?? null;
307
+ };
308
+ //#endregion
309
+ //#region src/litegraph/LiteGraphGroup.ts
310
+ const LiteGraphGroup_ark = (0, arktype.type)({
311
+ "id?": "number",
312
+ title: "string",
313
+ bounding: (0, arktype.type)([
314
+ "number",
315
+ "number",
316
+ "number",
317
+ "number"
318
+ ]),
319
+ "color?": "string",
320
+ "font_size?": "number",
321
+ "flags?": arktype.type.Record("string", "unknown").as()
322
+ });
323
+ //#endregion
324
+ //#region src/litegraph/LiteGraphLink.ts
325
+ const LiteGraphLinkTuple_ark = (0, arktype.type)([
326
+ LiteGraphLinkID_,
327
+ "number",
328
+ "number",
329
+ "number",
330
+ "number",
331
+ "string"
332
+ ]);
333
+ const LiteGraphLinkObject_ark = (0, arktype.type)({
334
+ id: LiteGraphLinkID_,
335
+ origin_id: "number",
336
+ origin_slot: "number",
337
+ target_id: "number",
338
+ target_slot: "number",
339
+ type: "string",
340
+ "parentId?": "number"
341
+ });
342
+ const LiteGraphLink_ark = LiteGraphLinkTuple_ark.or(LiteGraphLinkObject_ark);
343
+ //#endregion
344
+ //#region src/litegraph/LiteGraphNodeInput.ts
345
+ const LiteGraphNodeInput_ark = (0, arktype.type)({
346
+ name: "string",
347
+ type: "string",
348
+ "link?": LiteGraphLinkID_.or(arktype.type.null),
349
+ "shape?": "number",
350
+ "label?": "string",
351
+ "widget?": (0, arktype.type)({
352
+ name: "string",
353
+ "config?": "unknown"
354
+ })
355
+ });
356
+ //#endregion
357
+ //#region src/litegraph/LiteGraphSlotIndex.ts
358
+ const asLiteGraphSlotIndex = (id) => id;
359
+ const LiteGraphSlotIndex_ = arktype.type.number.atLeast(0).as();
360
+ //#endregion
361
+ //#region src/litegraph/LiteGraphNodeOutput.ts
362
+ const LiteGraphNodeOutput_ark = (0, arktype.type)({
363
+ name: "string",
364
+ type: "string",
365
+ "links?": LiteGraphLinkID_.array().or(arktype.type.null),
366
+ "shape?": "number",
367
+ "slot_index?": LiteGraphSlotIndex_
368
+ });
369
+ //#endregion
370
+ //#region src/litegraph/LiteGraphNode.ts
371
+ const LiteGraphNode_ark = (0, arktype.type)({
372
+ id: "number",
373
+ type: "string",
374
+ "title?": "string",
375
+ "color?": "string",
376
+ "bgcolor?": "string",
377
+ pos: {
378
+ "0": "number",
379
+ "1": "number"
380
+ },
381
+ size: {
382
+ "0": "number",
383
+ "1": "number"
384
+ },
385
+ "flags?": arktype.type.Record("string", "unknown"),
386
+ "order?": "number",
387
+ "mode?": "number",
388
+ "inputs?": LiteGraphNodeInput_ark.array(),
389
+ "outputs?": LiteGraphNodeOutput_ark.array(),
390
+ "isVirtualNode?": "boolean",
391
+ "properties?": arktype.type.Record("string", "unknown"),
392
+ "widgets_values?": (0, arktype.type)("unknown[]").or(arktype.type.Record("string", "unknown"))
393
+ });
394
+ //#endregion
395
+ //#region src/litegraph/LiteGraphSubgraphDef.ts
396
+ const LiteGraphSubgraphIO_ark = (0, arktype.type)({
397
+ id: "string",
398
+ name: "string",
399
+ type: "string",
400
+ "linkIds?": LiteGraphLinkID_.array(),
401
+ "label?": "string",
402
+ "localized_name?": "string",
403
+ "pos?": {
404
+ "0": "number",
405
+ "1": "number"
406
+ },
407
+ "shape?": "number"
408
+ });
409
+ const LiteGraphSubgraphDef_ark = (0, arktype.type)({
410
+ id: "string",
411
+ name: "string",
412
+ version: "number",
413
+ "state?": arktype.type.Record("string", "unknown"),
414
+ "revision?": "number",
415
+ "config?": arktype.type.Record("string", "unknown").as(),
416
+ "extra?": "unknown",
417
+ nodes: LiteGraphNode_ark.array(),
418
+ links: LiteGraphLinkObject_ark.array(),
419
+ "groups?": LiteGraphGroup_ark.array(),
420
+ inputNode: {
421
+ id: "number",
422
+ bounding: "number[]"
423
+ },
424
+ outputNode: {
425
+ id: "number",
426
+ bounding: "number[]"
427
+ },
428
+ inputs: LiteGraphSubgraphIO_ark.array(),
429
+ outputs: LiteGraphSubgraphIO_ark.array(),
430
+ widgets: "unknown[]"
431
+ });
432
+ //#endregion
433
+ //#region src/litegraph/LiteGraphJSON.ts
434
+ const LiteGraphJSON_ark = (0, arktype.type)({
435
+ "id?": "string",
436
+ "revision?": "number",
437
+ "last_node_id?": "number",
438
+ "last_link_id?": "number",
439
+ "state?": arktype.type.Record("string", "unknown"),
440
+ nodes: LiteGraphNode_ark.array(),
441
+ links: LiteGraphLink_ark.array(),
442
+ "groups?": LiteGraphGroup_ark.array(),
443
+ "config?": arktype.type.Record("never", "never"),
444
+ "extra?": { "ds?": {
445
+ scale: "number",
446
+ offset: {
447
+ "0": "number",
448
+ "1": "number"
449
+ }
450
+ } },
451
+ "models?": "unknown[]",
452
+ "definitions?": { subgraphs: LiteGraphSubgraphDef_ark.array() },
453
+ "reroutes?": "unknown[]",
454
+ "floatingLinks?": "unknown[]",
455
+ version: "0.4 | 1"
456
+ });
457
+ //#endregion
458
+ //#region src/litegraph/normalizeWorkflow.ts
459
+ /** a workflow JSON we cannot turn into a CanonicalWorkflow — loud, typed, never a cast */
460
+ var WorkflowNormalizeError = class extends Error {
461
+ constructor(code, message, detail) {
462
+ super(`[workflow ${code}] ${message}`);
463
+ this.code = code;
464
+ this.detail = detail;
465
+ this.name = "WorkflowNormalizeError";
466
+ }
467
+ };
468
+ /**
469
+ * THE one entry for foreign workflow JSON (files, clipboard, imports):
470
+ * tolerant ark validation, then normalization to the strict canonical shape.
471
+ */
472
+ const parseWorkflowJson = (json) => {
473
+ const out = LiteGraphJSON_ark(json);
474
+ if (out instanceof arktype.type.errors) throw new WorkflowNormalizeError("schema-reject", out.summary, out);
475
+ return normalizeWorkflow(out);
476
+ };
477
+ /**
478
+ * loose wire document → strict canonical document. Defaults filled, both link
479
+ * eras unified, cosmetic fields dropped, subgraph definitions expanded away
480
+ * (see expandSubgraphs.ts — def interiors go through the SAME per-shape
481
+ * normalizers, they are v1 bodies).
482
+ */
483
+ const normalizeWorkflow = (raw) => {
484
+ const wf = {
485
+ nodes: raw.nodes.map(normalizeNode),
486
+ links: raw.links.map(normalizeLink),
487
+ groups: (raw.groups ?? []).map(normalizeGroup)
488
+ };
489
+ const rawDefs = raw.definitions?.subgraphs ?? [];
490
+ if (rawDefs.length === 0) return wf;
491
+ const defs = /* @__PURE__ */ new Map();
492
+ for (const d of rawDefs) defs.set(d.id, normalizeSubgraphDef(d));
493
+ return expandSubgraphs(wf, defs);
494
+ };
495
+ const normalizeSubgraphDef = (d) => {
496
+ return {
497
+ id: d.id,
498
+ name: d.name,
499
+ inputs: d.inputs.map((io) => ({
500
+ name: io.name,
501
+ type: io.type
502
+ })),
503
+ outputs: d.outputs.map((io) => ({
504
+ name: io.name,
505
+ type: io.type
506
+ })),
507
+ nodes: d.nodes.map(normalizeNode),
508
+ links: d.links.map(normalizeLink)
509
+ };
510
+ };
511
+ const normalizeMode = (mode) => {
512
+ if (mode === 2) return "muted";
513
+ if (mode === 4) return "bypassed";
514
+ return "normal";
515
+ };
516
+ const normalizeNode = (n) => {
517
+ return {
518
+ id: n.id,
519
+ type: n.type,
520
+ title: n.title ?? null,
521
+ mode: normalizeMode(n.mode),
522
+ isVirtualNode: n.isVirtualNode ?? false,
523
+ inputs: (n.inputs ?? []).map(normalizeInput),
524
+ outputs: (n.outputs ?? []).map(normalizeOutput),
525
+ widgets: normalizeWidgetValues(n.widgets_values),
526
+ pos: [n.pos[0], n.pos[1]],
527
+ size: [n.size[0], n.size[1]],
528
+ properties: { ...n.properties }
529
+ };
530
+ };
531
+ const normalizeInput = (i) => {
532
+ return {
533
+ name: i.name,
534
+ type: i.type,
535
+ link: i.link ?? null,
536
+ widgetName: i.widget?.name ?? null
537
+ };
538
+ };
539
+ const normalizeOutput = (o) => {
540
+ return {
541
+ name: o.name,
542
+ type: o.type,
543
+ links: [...o.links ?? []]
544
+ };
545
+ };
546
+ const normalizeWidgetValues = (wv) => {
547
+ if (wv == null) return {
548
+ positional: [],
549
+ named: {}
550
+ };
551
+ if (Array.isArray(wv)) return {
552
+ positional: [...wv],
553
+ named: {}
554
+ };
555
+ return {
556
+ positional: [],
557
+ named: { ...wv }
558
+ };
559
+ };
560
+ const normalizeLink = (l) => {
561
+ if (Array.isArray(l)) return {
562
+ id: l[0],
563
+ originId: l[1],
564
+ originSlot: l[2],
565
+ targetId: l[3],
566
+ targetSlot: l[4],
567
+ type: l[5]
568
+ };
569
+ return {
570
+ id: l.id,
571
+ originId: l.origin_id,
572
+ originSlot: l.origin_slot,
573
+ targetId: l.target_id,
574
+ targetSlot: l.target_slot,
575
+ type: l.type
576
+ };
577
+ };
578
+ const normalizeGroup = (g) => {
579
+ return {
580
+ title: g.title,
581
+ bounding: [
582
+ g.bounding[0],
583
+ g.bounding[1],
584
+ g.bounding[2],
585
+ g.bounding[3]
586
+ ],
587
+ color: g.color ?? "#3f789e",
588
+ fontSize: g.font_size ?? 24
589
+ };
590
+ };
591
+ //#endregion
592
+ //#region src/runner/wsBinaryFrame.ts
593
+ function parseBinaryWsFrame(data) {
594
+ const view = new DataView(data);
595
+ const eventType = view.getUint32(0);
596
+ if (eventType === 1) {
597
+ const imageType = view.getUint32(4);
598
+ return {
599
+ kind: "preview",
600
+ bytes: new Uint8Array(data.slice(8)),
601
+ mime: imageType === 2 ? "image/png" : "image/jpeg",
602
+ metadata: null
603
+ };
604
+ }
605
+ if (eventType === 3) {
606
+ const nodeIdLen = view.getUint32(4);
607
+ const decoder = new TextDecoder();
608
+ return {
609
+ kind: "text",
610
+ nodeId: decoder.decode(data.slice(8, 8 + nodeIdLen)),
611
+ text: decoder.decode(data.slice(8 + nodeIdLen))
612
+ };
613
+ }
614
+ if (eventType === 4) {
615
+ const metadataLen = view.getUint32(4);
616
+ let metadata = null;
617
+ try {
618
+ metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)));
619
+ } catch {}
620
+ const bytes = new Uint8Array(data.slice(8 + metadataLen));
621
+ return {
622
+ kind: "preview",
623
+ bytes,
624
+ mime: bytes[0] === 137 && bytes[1] === 80 ? "image/png" : "image/jpeg",
625
+ metadata
626
+ };
627
+ }
628
+ return {
629
+ kind: "unknown",
630
+ eventType
631
+ };
632
+ }
43
633
  //#endregion
44
634
  //#region src/sdk-generator/Primitives.ts
45
635
  const ComfyPrimitiveMapping = {
@@ -50,20 +640,8 @@ const ComfyPrimitiveMapping = {
50
640
  };
51
641
  const ComfyPrimitives = Object.keys(ComfyPrimitiveMapping);
52
642
  /**
53
- * when a litegraph node has no input for a given ComfyUI node input
54
- * (e.g. a seed or an enum that has not been turned into a primitive)
55
- */
56
- const howManyWidgetValuesForThisSchemaType = (input) => {
57
- if (input.typeName === "INT") {
58
- if (input.nameInComfy === "seed" || input.nameInComfy === "noise_seed") return 2;
59
- }
60
- if (input.isPrimitive) return 1;
61
- if (input.typeName.startsWith("E_")) return 1;
62
- return 0;
63
- };
64
- /**
65
- * then a litegraph node has an input entry, some convoluted logic seems to be necessary
66
- * to determine how many Field_values need to be consumed for this input
643
+ * when a litegraph node has an input entry with a widget marker, the
644
+ * serialized TYPE string decides how many widgets_values it consumed in that era
67
645
  */
68
646
  const howManyWidgetValuesForThisInputType = (type, nameInComfy) => {
69
647
  if (type === "INT") {
@@ -91,94 +669,433 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
91
669
  output_node: false,
92
670
  python_module: "nodes"
93
671
  };
94
- var UnknownCustomNode = class extends Error {
95
- constructor(node) {
96
- super(`❌ node ${node.id}(${node.type}) has no known schema; you probably need to install some custom node`);
97
- this.node = node;
672
+ //#endregion
673
+ //#region src/sdk-generator/inputWidgetKind.ts
674
+ const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
675
+ /**
676
+ * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.
677
+ * The frontend creates the control widget on truthiness, and real 2026 hosts
678
+ * spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,
679
+ * SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed
680
+ * heuristic applies.
681
+ */
682
+ const controlConsumes = (o, typeName, name) => {
683
+ if (o != null && "control_after_generate" in o) return o["control_after_generate"] ? 2 : 1;
684
+ if (typeName === "INT" && (name === "seed" || name === "noise_seed")) return 2;
685
+ return 1;
686
+ };
687
+ const flattenInputSections = (inputs) => {
688
+ const out = [];
689
+ for (const section of ["required", "optional"]) {
690
+ const sec = inputs[section];
691
+ if (!isRecord(sec)) continue;
692
+ for (const [name, spec] of Object.entries(sec)) {
693
+ if (!Array.isArray(spec) || spec.length === 0) continue;
694
+ const t = spec[0];
695
+ if (typeof t !== "string" && !Array.isArray(t)) continue;
696
+ out.push({
697
+ name,
698
+ type: t,
699
+ opts: spec[1],
700
+ required: section === "required"
701
+ });
702
+ }
98
703
  }
704
+ return out;
705
+ };
706
+ /** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */
707
+ const parseDynamicOptions = (options) => {
708
+ if (options.length === 0) return null;
709
+ const out = [];
710
+ for (const entry of options) {
711
+ if (!isRecord(entry)) return null;
712
+ const key = entry["key"];
713
+ const inputs = entry["inputs"];
714
+ if (typeof key !== "string" || !isRecord(inputs)) return null;
715
+ out.push({
716
+ key,
717
+ inputs: flattenInputSections(inputs)
718
+ });
719
+ }
720
+ return out;
721
+ };
722
+ /**
723
+ * autogrow (`template` WITH a nested `input` section): instances are always
724
+ * link slots named `decl.<name_i>` (the backend force-inputs widget
725
+ * templates), the first `min` of them required WHEN the template input
726
+ * section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.
727
+ */
728
+ const parseContainer = (template) => {
729
+ const input = template["input"];
730
+ const min = typeof template["min"] === "number" ? template["min"] : 1;
731
+ const prefix = typeof template["prefix"] === "string" ? template["prefix"] : "";
732
+ const max = typeof template["max"] === "number" ? template["max"] : 100;
733
+ const rawNames = template["names"];
734
+ const names = Array.isArray(rawNames) ? rawNames.filter((n) => typeof n === "string") : Array.from({ length: max }, (_, i) => `${prefix}${i}`);
735
+ return {
736
+ kind: "dynamic-container",
737
+ instanceNames: names,
738
+ requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
739
+ };
740
+ };
741
+ const classifyWidgetInput = (p) => {
742
+ const o = isRecord(p.opts) ? p.opts : null;
743
+ if (o?.["forceInput"] === true) return { kind: "slot" };
744
+ if (Array.isArray(p.type) || p.isEnumUnion === true) {
745
+ const tn = typeof p.type === "string" ? p.type : "COMBO";
746
+ return {
747
+ kind: "widget",
748
+ consumes: controlConsumes(o, tn, p.name),
749
+ strictValues: true
750
+ };
751
+ }
752
+ if (typeof p.type !== "string") return { kind: "slot" };
753
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
754
+ if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
755
+ kind: "widget",
756
+ consumes: controlConsumes(o, widgetTypeName, p.name),
757
+ strictValues: true
758
+ };
759
+ const options = o?.["options"];
760
+ if (Array.isArray(options)) {
761
+ const dynOptions = parseDynamicOptions(options);
762
+ if (dynOptions != null) {
763
+ const first = dynOptions[0];
764
+ if (first == null) return { kind: "slot" };
765
+ return {
766
+ kind: "dynamic-combo",
767
+ options: dynOptions,
768
+ defaultKey: typeof o?.["default"] === "string" ? o["default"] : first.key
769
+ };
770
+ }
771
+ return {
772
+ kind: "widget",
773
+ consumes: controlConsumes(o, p.type, p.name),
774
+ strictValues: true
775
+ };
776
+ }
777
+ const template = o?.["template"];
778
+ if (isRecord(template)) {
779
+ if (isRecord(template["input"])) return parseContainer(template);
780
+ return { kind: "slot" };
781
+ }
782
+ if (o?.["socketless"] === true) return {
783
+ kind: "widget",
784
+ consumes: 1,
785
+ strictValues: false
786
+ };
787
+ return { kind: "slot" };
788
+ };
789
+ const classifySchemaInput = (input) => classifyWidgetInput({
790
+ name: input.nameInComfy,
791
+ type: input.typeName,
792
+ opts: input.opts,
793
+ isEnumUnion: input.isEnum
794
+ });
795
+ /** how many widgets_values entries this schema input consumes (export path + positional walks) */
796
+ const howManyWidgetValuesForThisSchemaType = (input) => {
797
+ const kind = classifySchemaInput(input);
798
+ return kind.kind === "widget" ? kind.consumes : 0;
799
+ };
800
+ /**
801
+ * what ComfyUI's frontend gives a widget created with no serialized value
802
+ * (`getWidgetDefaultValue` semantics), used when a positional array is
803
+ * shorter than the schema's widget list. `null` for custom widgets — the
804
+ * backend accepts an explicit null but errors on an ABSENT required key.
805
+ */
806
+ const defaultValueForWidget = (p) => {
807
+ const o = isRecord(p.opts) ? p.opts : null;
808
+ if (o != null && o["default"] !== void 0) return o["default"];
809
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
810
+ if (widgetTypeName === "INT" || widgetTypeName === "FLOAT") return 0;
811
+ if (widgetTypeName === "BOOLEAN") return false;
812
+ if (widgetTypeName === "STRING") return "";
813
+ const options = o?.["options"];
814
+ if (Array.isArray(options) && options.length > 0) {
815
+ const first = options[0];
816
+ if (typeof first === "string" || typeof first === "number" || typeof first === "boolean") return first;
817
+ }
818
+ if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0];
819
+ return null;
99
820
  };
100
821
  //#endregion
101
822
  //#region src/sdk-generator/litegraphToApiRequestPayload.ts
823
+ /** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */
824
+ var WorkflowConvertError = class extends Error {
825
+ constructor(code, message, node) {
826
+ super(`[workflow ${code}] ${message}`);
827
+ this.code = code;
828
+ this.node = node;
829
+ this.name = "WorkflowConvertError";
830
+ }
831
+ };
102
832
  /**
103
- * convert a saved ComfyUI workflow.json (litegraph format) into the api.json
104
- * (prompt format) ComfyUI's POST /prompt takes.
105
- * Handles: muted nodes, Note/Reroute/PrimitiveNode virtual nodes (reroutes
106
- * unwrapped, primitives inlined into their consumers), widget-value offsets
107
- * (incl. the phantom `control_after_generate` value after seeds).
833
+ * closed set: frontend-only node types that NEVER execute. PrimitiveString /
834
+ * PrimitiveInt / PrimitiveBoolean etc are REAL backend nodes — do not add them.
835
+ */
836
+ const VIRTUAL_NODE_TYPES = /* @__PURE__ */ new Set([
837
+ "Note",
838
+ "MarkdownNote",
839
+ "Reroute",
840
+ "PrimitiveNode"
841
+ ]);
842
+ const isNeverExecuted = (node) => node.isVirtualNode || VIRTUAL_NODE_TYPES.has(node.type);
843
+ /** exact match, or `*` wildcard on either side (Reroute-style slots) */
844
+ /** frontend isValidConnection parity: exact, `*` wildcard, or any member of a comma-separated multi-type */
845
+ const linkTypeMatches = (a, b) => {
846
+ if (a === b || a === "*" || b === "*") return true;
847
+ if (!a.includes(",") && !b.includes(",")) return false;
848
+ const as = a.split(",");
849
+ const bs = b.split(",");
850
+ return as.some((x) => bs.includes(x));
851
+ };
852
+ /** what an inlined PrimitiveNode may contribute: scalar widget values only */
853
+ const isPromptScalar = (v) => v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean";
854
+ /**
855
+ * convert a normalized workflow (CanonicalWorkflow — see parseWorkflowJson)
856
+ * into the api.json (prompt format) ComfyUI's POST /prompt takes.
857
+ * Handles: muted nodes (skipped, consumers resolve unconnected), bypassed
858
+ * nodes (mode 4: link resolution walks through to the first type-matching
859
+ * input), Note/MarkdownNote/Reroute/PrimitiveNode virtual nodes (reroutes
860
+ * unwrapped, primitives inlined into their consumers), widget values both
861
+ * positional (with the phantom `control_after_generate` offset after seeds)
862
+ * and named (object-form widgets_values + subgraph promotion overrides —
863
+ * named wins, but a live link wins over both). Widget-ness is decided from
864
+ * the input CONFIG (inputWidgetKind.ts): V3 string-spelled widget types
865
+ * (COMBO options, dynamic combos, autogrow containers, socketless customs)
866
+ * and 2024-era enums go through ONE classifier; a positional array shorter
867
+ * than the schema's widget list fills schema defaults, never throws
868
+ * (agent/architecture.md owns both decisions).
108
869
  */
109
870
  const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
110
871
  const prompt = {};
111
872
  const LOG = opts.verbose ? (...args) => console.log("[🔥] converter:", ...args) : () => {};
112
873
  const PRIMITIVE_VALUES = {};
113
- for (const node of workflow.nodes) if (node.type === "PrimitiveNode") {
114
- const widgetValues = node.widgets_values;
115
- if (widgetValues == null || widgetValues.length === 0) throw new Error(`PrimitiveNode#${node.id} has no widget values`);
116
- PRIMITIVE_VALUES[node.id] = widgetValues[0];
874
+ for (const node of workflow.nodes) {
875
+ if (node.type !== "PrimitiveNode") continue;
876
+ if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0];
877
+ else if (Object.hasOwn(node.widgets.named, "value")) PRIMITIVE_VALUES[node.id] = node.widgets.named["value"];
117
878
  }
118
879
  for (const node of workflow.nodes) {
119
- if (node.isVirtualNode) continue;
120
- if (node.mode === 2) continue;
121
- if (node.type === "Reroute") continue;
122
- if (node.type === "Note") continue;
123
- if (node.type === "PrimitiveNode") continue;
880
+ if (isNeverExecuted(node)) continue;
881
+ if (node.mode !== "normal") continue;
124
882
  const inputs = {};
125
- const fieldNamesWithLinks = new Set((node.inputs ?? []).map((i) => i.name));
883
+ const fieldNamesPresent = new Set(node.inputs.map((i) => i.name));
126
884
  const nodeSchema_ = schema.nodesByNameInComfy[node.type];
127
- if (nodeSchema_ == null) throw new UnknownCustomNode(node);
885
+ if (nodeSchema_ == null) throw new WorkflowConvertError("unknown-node", `node ${node.id}(${node.type}) has no schema on this host; a custom node is missing`, node);
128
886
  const nodeSchema = nodeSchema_;
129
887
  let offset = 0;
130
- const inputsInNodeJSON = node.inputs ?? [];
888
+ const positional = node.widgets.positional;
889
+ const named = node.widgets.named;
890
+ const widgetFallback = /* @__PURE__ */ new Map();
891
+ const inputsInNodeJSON = node.inputs;
131
892
  const inputsInNodeSchema = nodeSchema.inputs;
893
+ /** arrays ride wrapped (a bare 2-list is a link server-side); objects pass only in lax (custom-widget) domains */
894
+ const toPromptValue = (value, p) => {
895
+ if (value == null) return null;
896
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
897
+ if (Array.isArray(value)) return { __value__: value };
898
+ if (!p.strict && isRecord(value)) return value;
899
+ throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
900
+ };
901
+ /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
902
+ const resolveWidgetValue = (p) => {
903
+ let value;
904
+ let has = false;
905
+ if (Object.hasOwn(named, p.promptName)) {
906
+ value = named[p.promptName];
907
+ has = true;
908
+ } else if (offset < positional.length) {
909
+ value = positional[offset];
910
+ has = true;
911
+ }
912
+ if (positional.length > 0) offset += p.consumes;
913
+ return {
914
+ value,
915
+ filled: !has
916
+ };
917
+ };
918
+ const consumePlainWidget = (p) => {
919
+ const r = resolveWidgetValue({
920
+ promptName: p.promptName,
921
+ consumes: p.consumes
922
+ });
923
+ const raw = r.filled ? defaultValueForWidget({
924
+ type: p.typeName,
925
+ opts: p.opts,
926
+ enumValues: p.enumValues ?? schema.knownUnionByName.get(p.typeName)?.values
927
+ }) : r.value;
928
+ const value = toPromptValue(raw, {
929
+ promptName: p.promptName,
930
+ strict: p.strict
931
+ });
932
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.promptName} = ${JSON.stringify(value)} (schema-default fill)`);
933
+ if (p.linkedInput?.link != null) widgetFallback.set(p.promptName, value);
934
+ else inputs[p.promptName] = value;
935
+ };
936
+ /** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */
937
+ const consumeDynamicCombo = (p) => {
938
+ const r = resolveWidgetValue({
939
+ promptName: p.path,
940
+ consumes: 1
941
+ });
942
+ const key = r.filled ? p.defaultKey : r.value;
943
+ 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);
944
+ const opt = p.options.find((o) => o.key === key);
945
+ if (opt == null) throw new WorkflowConvertError("unknown-dynamic-combo-option", `node ${node.id}(${node.type}): "${key}" is not an option of dynamic combo "${p.path}" (options: ${p.options.map((o) => o.key).join(", ")})`, node);
946
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.path} = ${key} (schema-default fill)`);
947
+ inputs[p.path] = key;
948
+ for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
949
+ };
950
+ const consumeBranchInput = (subPath, sub) => {
951
+ const kind = classifyWidgetInput({
952
+ name: sub.name,
953
+ type: sub.type,
954
+ opts: sub.opts
955
+ });
956
+ if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
957
+ if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
958
+ path: subPath,
959
+ options: kind.options,
960
+ defaultKey: kind.defaultKey
961
+ });
962
+ const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
963
+ consumePlainWidget({
964
+ promptName: subPath,
965
+ typeName: typeof sub.type === "string" ? sub.type : "COMBO",
966
+ opts: sub.opts,
967
+ consumes: kind.consumes,
968
+ strict: kind.strictValues,
969
+ enumValues: inlineEnum,
970
+ linkedInput: inputsInNodeJSON.find((i) => i.name === subPath)
971
+ });
972
+ };
132
973
  for (const field of inputsInNodeSchema) {
133
974
  const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy);
134
- const MUST_CONSUME = input?.type ? howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) : howManyWidgetValuesForThisSchemaType(field);
135
- if (MUST_CONSUME > 0) {
136
- if (node.widgets_values == null) throw new Error(`node ${node.id}(${node.type}) has no widgets_values but "${field.nameInComfy}" needs one`);
137
- if (node.widgets_values.length < offset + 1) throw new Error(`node ${node.id}(${node.type}) has not enough widgets_values for "${field.nameInComfy}"`);
138
- const _value = node.widgets_values[offset];
139
- LOG(`${node.type}#${node.id}.${field.nameInComfy} = ${_value} (widget, consumes ${MUST_CONSUME})`);
140
- if (!isValidValue(_value)) throw new Error(`node ${node.id}(${node.type}) has an invalid widget value for "${field.nameInComfy}": ${JSON.stringify(_value)}`);
141
- inputs[field.nameInComfy] = _value;
142
- offset += MUST_CONSUME;
143
- } else if (!fieldNamesWithLinks.has(field.nameInComfy)) {
144
- if (field.required) throw new Error(`node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`);
975
+ let kind = classifySchemaInput(field);
976
+ if (kind.kind === "slot" && input?.widgetName != null) kind = {
977
+ kind: "widget",
978
+ consumes: howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) === 2 ? 2 : 1,
979
+ strictValues: true
980
+ };
981
+ if (kind.kind === "widget") consumePlainWidget({
982
+ promptName: field.nameInComfy,
983
+ typeName: field.typeName,
984
+ opts: field.opts,
985
+ consumes: kind.consumes,
986
+ strict: kind.strictValues,
987
+ linkedInput: input
988
+ });
989
+ else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
990
+ path: field.nameInComfy,
991
+ options: kind.options,
992
+ defaultKey: kind.defaultKey
993
+ });
994
+ else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
995
+ const iname = `${field.nameInComfy}.${instName}`;
996
+ if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
997
+ }
998
+ else if (!fieldNamesPresent.has(field.nameInComfy)) {
999
+ if (field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
145
1000
  }
146
1001
  }
147
1002
  const getParentNode = (linkId) => {
148
- const link = workflow.links.find((link) => link[0] === linkId);
149
- if (link == null) throw new Error(`Node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`);
150
- const parentId = link[1];
151
- const parentNode = workflow.nodes.find((n) => n.id === parentId);
152
- if (parentNode == null) throw new Error(`link ${linkId} references a non-existent parent node ${parentId}`);
1003
+ const link = workflow.links.find((link) => link.id === linkId);
1004
+ if (link == null) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`, node);
1005
+ const parentNode = workflow.nodes.find((n) => n.id === link.originId);
1006
+ if (parentNode == null) throw new WorkflowConvertError("dangling-link", `link ${linkId} references a non-existent parent node ${link.originId}`, node);
153
1007
  return {
154
1008
  node: parentNode,
155
1009
  link
156
1010
  };
157
1011
  };
158
- INPT: for (const ipt of node.inputs ?? []) {
159
- if (howManyWidgetValuesForThisInputType(ipt.type, ipt.name) > 0) continue;
1012
+ const pickBypassInput = (p) => {
1013
+ const sameSlot = p.inputs[p.outSlot];
1014
+ if (p.consumerType === "*" || p.consumerType === "") return sameSlot ?? p.inputs[0] ?? null;
1015
+ if (sameSlot != null && linkTypeMatches(sameSlot.type, p.outputType) && linkTypeMatches(sameSlot.type, p.consumerType)) return sameSlot;
1016
+ const exact = p.inputs.find((i) => i.type === p.consumerType);
1017
+ if (exact != null) return exact;
1018
+ return p.inputs.find((i) => linkTypeMatches(i.type, p.outputType) && linkTypeMatches(i.type, p.consumerType)) ?? null;
1019
+ };
1020
+ const resolveThroughParents = (startLink, consumerType) => {
1021
+ const visited = /* @__PURE__ */ new Set();
1022
+ let linkId = startLink;
1023
+ let effectiveType = consumerType;
1024
+ while (true) {
1025
+ const parent = getParentNode(linkId);
1026
+ if (visited.has(parent.node.id)) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}): link resolution loops through node ${parent.node.id}`, node);
1027
+ visited.add(parent.node.id);
1028
+ if (parent.node.type === "Reroute") {
1029
+ const rerouteIn = parent.node.inputs[0]?.link;
1030
+ if (rerouteIn == null) return {
1031
+ kind: "unconnected",
1032
+ reason: "reroute chain ends on an empty slot"
1033
+ };
1034
+ linkId = rerouteIn;
1035
+ continue;
1036
+ }
1037
+ if (parent.node.mode === "muted") return {
1038
+ kind: "unconnected",
1039
+ reason: `parent ${parent.node.id}(${parent.node.type}) is muted`
1040
+ };
1041
+ if (parent.node.mode === "bypassed") {
1042
+ const outputType = parent.node.outputs[parent.link.originSlot]?.type ?? parent.link.type;
1043
+ const through = pickBypassInput({
1044
+ inputs: parent.node.inputs,
1045
+ outSlot: parent.link.originSlot,
1046
+ outputType,
1047
+ consumerType: effectiveType
1048
+ });
1049
+ if (through?.link == null) return {
1050
+ kind: "unconnected",
1051
+ reason: `bypassed parent ${parent.node.id}(${parent.node.type}) has no connected ${effectiveType} input to pass through`
1052
+ };
1053
+ linkId = through.link;
1054
+ effectiveType = through.type;
1055
+ continue;
1056
+ }
1057
+ if (parent.node.type === "PrimitiveNode") {
1058
+ if (!(parent.node.id in PRIMITIVE_VALUES)) return {
1059
+ kind: "unconnected",
1060
+ reason: `PrimitiveNode#${parent.node.id} has no widget value`
1061
+ };
1062
+ return {
1063
+ kind: "primitive",
1064
+ nodeId: parent.node.id
1065
+ };
1066
+ }
1067
+ return {
1068
+ kind: "link",
1069
+ nodeId: parent.node.id,
1070
+ slot: parent.link.originSlot
1071
+ };
1072
+ }
1073
+ };
1074
+ for (const ipt of node.inputs) {
160
1075
  if (ipt.link == null) {
161
- LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (fine when optional)`);
1076
+ LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (widget-backed or optional)`);
162
1077
  continue;
163
1078
  }
164
- let parent = getParentNode(ipt.link);
165
- let max = 100;
166
- while (parent != null && parent.node.type === "Reroute" && max-- > 0) {
167
- const firstParentInput = parent.node.inputs?.[0];
168
- if (firstParentInput?.link == null) {
169
- LOG(`${node.type}#${node.id}.${ipt.name}: reroute chain ends on an empty slot`);
170
- continue INPT;
171
- }
172
- parent = getParentNode(firstParentInput.link);
1079
+ const resolved = resolveThroughParents(ipt.link, ipt.type);
1080
+ if (resolved.kind === "primitive") {
1081
+ const pv = PRIMITIVE_VALUES[resolved.nodeId];
1082
+ if (!isPromptScalar(pv)) throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): PrimitiveNode#${resolved.nodeId} value is not a scalar: ${JSON.stringify(pv)}`, node);
1083
+ inputs[ipt.name] = pv;
1084
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${pv} (inlined primitive)`);
1085
+ continue;
1086
+ }
1087
+ if (resolved.kind === "link") {
1088
+ LOG(`${node.type}#${node.id}.${ipt.name} = [${resolved.nodeId}, ${resolved.slot}] (link)`);
1089
+ inputs[ipt.name] = [String(resolved.nodeId), resolved.slot];
1090
+ continue;
173
1091
  }
174
- if (parent == null) throw new Error(`no parent found for ${node.id}.${ipt.name}`);
175
- if (parent.node.type === "PrimitiveNode") {
176
- inputs[ipt.name] = PRIMITIVE_VALUES[parent.node.id];
177
- LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (inlined primitive)`);
1092
+ if (widgetFallback.has(ipt.name)) {
1093
+ inputs[ipt.name] = widgetFallback.get(ipt.name) ?? null;
1094
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (widget fallback, ${resolved.reason})`);
178
1095
  continue;
179
1096
  }
180
- LOG(`${node.type}#${node.id}.${ipt.name} = [${parent.node.id}, ${parent.link[2]}] (link)`);
181
- inputs[ipt.name] = [String(parent.node.id), parent.link[2]];
1097
+ if (inputsInNodeSchema.find((f) => f.nameInComfy === ipt.name)?.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${ipt.name}" resolves unconnected (${resolved.reason}) and no widget value covers it`, node);
1098
+ LOG(`${node.type}#${node.id}.${ipt.name}: resolves unconnected (${resolved.reason})`);
182
1099
  }
183
1100
  prompt[String(node.id)] = {
184
1101
  inputs,
@@ -187,14 +1104,6 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
187
1104
  }
188
1105
  return prompt;
189
1106
  };
190
- function isValidValue(value) {
191
- if (value == null) return true;
192
- if (typeof value === "string") return true;
193
- if (typeof value === "number") return true;
194
- if (typeof value === "boolean") return true;
195
- if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number") return true;
196
- return false;
197
- }
198
1107
  //#endregion
199
1108
  //#region src/errors/InvalidPromptError.ts
200
1109
  var InvalidPromptError = class extends Error {
@@ -543,24 +1452,6 @@ var ComfyWorkflowBuilder = class {
543
1452
  }
544
1453
  };
545
1454
  //#endregion
546
- //#region src/utils/bang.ts
547
- /** assertNotNull */
548
- const bang = (x, msg = "") => {
549
- if (x == null) {
550
- console.error(`[🔴] BANG FAILED`, msg);
551
- throw new Error("bang: " + (msg ?? "no message"));
552
- }
553
- return x;
554
- };
555
- //#endregion
556
- //#region src/litegraph/LiteGraphLinkID.ts
557
- const asLiteGraphLinkID = (id) => id;
558
- arktype.type.number.atLeast(0).as();
559
- //#endregion
560
- //#region src/litegraph/LiteGraphSlotIndex.ts
561
- const asLiteGraphSlotIndex = (id) => id;
562
- arktype.type.number.atLeast(0).as();
563
- //#endregion
564
1455
  //#region src/litegraph/convertFlowToLiteGraphJSON.ts
565
1456
  const convertFlowToLiteGraphJSON = (graph) => {
566
1457
  const ctx = new LiteGraphCtx(graph);
@@ -573,7 +1464,7 @@ const convertFlowToLiteGraphJSON = (graph) => {
573
1464
  const n = xx.liteGraphNode;
574
1465
  n.pos[0] = bang(xx.comfyNode.x);
575
1466
  n.pos[1] = bang(xx.comfyNode.y);
576
- for (const o of n.outputs) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
1467
+ for (const o of n.outputs ?? []) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
577
1468
  }
578
1469
  return {
579
1470
  last_node_id,
@@ -803,6 +1694,18 @@ const types$1 = (0, arktype.scope)({
803
1694
  type: "'manager-terminal-feedback'",
804
1695
  data: "WSMsgManagerFeedbackData"
805
1696
  },
1697
+ LogEntry: {
1698
+ t: "string",
1699
+ m: "string"
1700
+ },
1701
+ _WsMsgLogsData: {
1702
+ entries: "LogEntry[]",
1703
+ "size?": "unknown"
1704
+ },
1705
+ WsMsgLogs: {
1706
+ type: "'logs'",
1707
+ data: "_WsMsgLogsData"
1708
+ },
806
1709
  WsMsgProgress: {
807
1710
  type: "'progress'",
808
1711
  data: "NodeProgress"
@@ -816,11 +1719,12 @@ const types$1 = (0, arktype.scope)({
816
1719
  data: "_WsMsgProgressStateData"
817
1720
  },
818
1721
  PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
819
- WsMsg: "WsMsgStatus | WSMsgManagerFeedback | PromptRelated_WsMsg"
1722
+ WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
820
1723
  }).export();
821
1724
  const PromptInfo_ark = (0, arktype.type)({ prompt_id: types$1.PromptID }).as();
822
1725
  const WsMsg_ark = types$1.WsMsg;
823
1726
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
1727
+ const WsMsgLogsData_ark = types$1._WsMsgLogsData;
824
1728
  (0, arktype.type)({
825
1729
  comfyHostHttpURL: "string",
826
1730
  comfyImageInfo: ComfyImageInfo_ark
@@ -1045,7 +1949,7 @@ var ComfyExecution = class {
1045
1949
  const promptNode = this.workflow.data.apiJson?.[promptNodeID];
1046
1950
  const promptMeta = this.workflow.data.metadata?.[promptNodeID];
1047
1951
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
1048
- const imgUrl = this.host.getServerHostHTTP() + "/view?" + new URLSearchParams(comfyImageInfo).toString();
1952
+ const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
1049
1953
  const sf = this.saveFormat;
1050
1954
  let absPath = comfyts.resolveFromOutput((0, pathe.join)(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename));
1051
1955
  if (sf?.format && sf.format !== "raw") {
@@ -1055,10 +1959,7 @@ var ComfyExecution = class {
1055
1959
  (0, node_fs.mkdirSync)((0, pathe.dirname)(absPath), { recursive: true });
1056
1960
  let img;
1057
1961
  if (sf && sf.format !== "raw") {
1058
- const buff = await (await fetch(imgUrl, {
1059
- headers: { "Content-Type": "image/png" },
1060
- method: "GET"
1061
- })).arrayBuffer();
1962
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1062
1963
  let textChunk = {};
1063
1964
  try {
1064
1965
  const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
@@ -1081,10 +1982,7 @@ var ComfyExecution = class {
1081
1982
  }
1082
1983
  });
1083
1984
  } else {
1084
- const buff = await (await fetch(imgUrl, {
1085
- headers: { "Content-Type": "image/png" },
1086
- method: "GET"
1087
- })).arrayBuffer();
1985
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1088
1986
  const uint8arr = new Uint8Array(buff);
1089
1987
  (0, node_fs.writeFileSync)(absPath, uint8arr);
1090
1988
  img = new MediaImage({
@@ -1456,9 +2354,9 @@ var ComfyWorkflow = class {
1456
2354
  comfy_ts_version: comfyts.version
1457
2355
  } }
1458
2356
  };
1459
- const promptEndpoint = `${this.host.getServerHostHTTP()}/prompt`;
1460
- const res = await fetch(promptEndpoint, {
2357
+ const res = await this.host.fetch("/prompt", {
1461
2358
  method: "POST",
2359
+ headers: { "Content-Type": "application/json" },
1462
2360
  body: JSON.stringify(out)
1463
2361
  });
1464
2362
  const promptInfo = softValidate(PromptInfo_ark, await res.json());
@@ -2324,8 +3222,7 @@ var ComfyManager = class {
2324
3222
  }
2325
3223
  };
2326
3224
  this.fetchPost = async (endpoint, body, validator) => {
2327
- const url = this.host.getServerHostHTTP() + endpoint;
2328
- const response = await fetch(url, {
3225
+ const response = await this.host.fetch(endpoint, {
2329
3226
  method: "POST",
2330
3227
  headers: { "Content-Type": "application/json" },
2331
3228
  body: JSON.stringify(body)
@@ -2336,16 +3233,14 @@ var ComfyManager = class {
2336
3233
  return status;
2337
3234
  };
2338
3235
  this.fetchGetJSON = async (endpoint, validator) => {
2339
- const url = this.host.getServerHostHTTP() + endpoint;
2340
- const response = await fetch(url);
3236
+ const response = await this.host.fetch(endpoint);
2341
3237
  if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
2342
3238
  const jsonResult = await response.json();
2343
3239
  if (validator) return softValidate(validator, jsonResult);
2344
3240
  return jsonResult;
2345
3241
  };
2346
3242
  this.fetchGetText = async (endopint) => {
2347
- const url = this.host.getServerHostHTTP() + endopint;
2348
- return await (await fetch(url)).text();
3243
+ return await (await this.host.fetch(endopint)).text();
2349
3244
  };
2350
3245
  }
2351
3246
  get registry() {
@@ -2363,11 +3258,10 @@ var ComfyManager = class {
2363
3258
  no();
2364
3259
  }
2365
3260
  if (abortCtrl) abortCtrl.abort();
2366
- const url = this.host.getServerHostHTTP();
2367
3261
  abortCtrl = new AbortController();
2368
3262
  try {
2369
3263
  console.log(` - trying...`);
2370
- await fetch(url, { signal: abortCtrl.signal });
3264
+ await this.host.fetch("/", { signal: abortCtrl.signal }, { apiPrefix: false });
2371
3265
  clearInterval(interval);
2372
3266
  yes(true);
2373
3267
  } catch {}
@@ -2405,8 +3299,7 @@ var ComfyUploader = class {
2405
3299
  if (p.type) form.set("type", p.type);
2406
3300
  if (p.override ?? true) form.set("override", "true");
2407
3301
  if (p.subfolder) form.set("subfolder", p.subfolder);
2408
- const uploadURL = this.host.getServerHostHTTP() + "/upload/image";
2409
- const resp = await fetch(uploadURL, {
3302
+ const resp = await this.host.fetch("/upload/image", {
2410
3303
  method: "POST",
2411
3304
  body: form
2412
3305
  });
@@ -2422,6 +3315,51 @@ var ComfyUploader = class {
2422
3315
  }
2423
3316
  };
2424
3317
  //#endregion
3318
+ //#region src/host/hostUrl.ts
3319
+ /** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */
3320
+ function parseHostBase(p) {
3321
+ const hasLegacy = p.host != null || p.port != null || p.https != null;
3322
+ if (p.url != null && hasLegacy) throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`);
3323
+ if (p.url == null) {
3324
+ if (p.host == null || p.port == null) throw new Error(`host '${p.id}': needs either url, or host AND port (got host=${p.host}, port=${p.port})`);
3325
+ return {
3326
+ scheme: p.https ? "https" : "http",
3327
+ host: p.host,
3328
+ port: p.port,
3329
+ basePath: ""
3330
+ };
3331
+ }
3332
+ let parsed;
3333
+ try {
3334
+ parsed = new URL(p.url);
3335
+ } catch {
3336
+ throw new Error(`host '${p.id}': unparseable url '${p.url}'`);
3337
+ }
3338
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`host '${p.id}': url scheme must be http or https, got '${parsed.protocol}' in '${p.url}'`);
3339
+ if (parsed.search !== "" || parsed.hash !== "") throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`);
3340
+ const scheme = parsed.protocol === "https:" ? "https" : "http";
3341
+ const port = parsed.port !== "" ? Number(parsed.port) : scheme === "https" ? 443 : 80;
3342
+ const basePath = parsed.pathname.replace(/\/+$/, "");
3343
+ return {
3344
+ scheme,
3345
+ host: parsed.hostname,
3346
+ port,
3347
+ basePath
3348
+ };
3349
+ }
3350
+ /** http(s) base, port omitted when it is the scheme default */
3351
+ function renderHttpBase(p) {
3352
+ return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3353
+ }
3354
+ /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3355
+ function renderWsUrl(p) {
3356
+ return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3357
+ }
3358
+ function renderPort(p) {
3359
+ const schemeDefault = p.scheme === "https" ? 443 : 80;
3360
+ return p.port === schemeDefault ? "" : `:${p.port}`;
3361
+ }
3362
+ //#endregion
2425
3363
  //#region src/host/ResilientWebsocket.ts
2426
3364
  var ResilientWebSocketClient = class {
2427
3365
  addInfo(msg) {
@@ -2466,7 +3404,7 @@ var ResilientWebSocketClient = class {
2466
3404
  this.addInfo("Previous WebSocket discarded");
2467
3405
  prevWS.close();
2468
3406
  }
2469
- const ws$1 = new ws.default(this.url);
3407
+ const ws$1 = new ws.default(this.url, { headers: this.options.headers?.() });
2470
3408
  ws$1.binaryType = "arraybuffer";
2471
3409
  this.currentWS = ws$1;
2472
3410
  if (this.options.onMessage) ws$1.onmessage = (event) => {
@@ -3076,6 +4014,17 @@ var DefinedWorkflow = class {
3076
4014
  };
3077
4015
  //#endregion
3078
4016
  //#region src/host/ComfyHost.ts
4017
+ /** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):
4018
+ * 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive
4019
+ * (or plain rate limiting on non-cloud hosts). The key value never appears here. */
4020
+ var ComfyHostAuthError = class extends Error {
4021
+ constructor(code, hostId, message) {
4022
+ super(message);
4023
+ this.code = code;
4024
+ this.hostId = hostId;
4025
+ this.name = "ComfyHostAuthError";
4026
+ }
4027
+ };
3079
4028
  var ComfyHost = class {
3080
4029
  constructor(data) {
3081
4030
  this.data = data;
@@ -3131,7 +4080,48 @@ var ComfyHost = class {
3131
4080
  return this.manager.installPlugin(customNode);
3132
4081
  };
3133
4082
  this.getWSUrl = () => {
3134
- return `${this.data.https ? "wss" : "ws"}://${this.data.host}:${this.data.port}/ws`;
4083
+ return renderWsUrl(this.base);
4084
+ };
4085
+ this._apiPrefix = null;
4086
+ this.fetch = async (route, init = {}, p = {}) => {
4087
+ const base = this.getServerHostHTTP();
4088
+ const headers = new Headers(init.headers);
4089
+ for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v);
4090
+ const send = (prefixed) => fetch(`${base}${prefixed ? "/api" : ""}${route}`, {
4091
+ ...init,
4092
+ headers
4093
+ });
4094
+ const missed = (res) => res.status === 404 || res.status === 405;
4095
+ let res;
4096
+ if (p.apiPrefix === false) res = await send(false);
4097
+ else if (this._apiPrefix != null) {
4098
+ res = await send(this._apiPrefix);
4099
+ if (missed(res)) {
4100
+ const alt = await send(!this._apiPrefix);
4101
+ if (!missed(alt)) res = alt;
4102
+ }
4103
+ } else {
4104
+ res = await send(true);
4105
+ if (missed(res)) {
4106
+ const bare = await send(false);
4107
+ if (!missed(bare)) {
4108
+ this._apiPrefix = false;
4109
+ res = bare;
4110
+ }
4111
+ } else this._apiPrefix = true;
4112
+ }
4113
+ this.throwOnAuthError(res, route);
4114
+ return res;
4115
+ };
4116
+ this.fetchFile = async (route) => {
4117
+ const res = await this.fetch(route, { redirect: "manual" });
4118
+ if (res.status >= 300 && res.status < 400) {
4119
+ const location = res.headers.get("location");
4120
+ if (location == null) throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`);
4121
+ res.body?.cancel();
4122
+ return fetch(new URL(location, this.getServerHostHTTP()));
4123
+ }
4124
+ return res;
3135
4125
  };
3136
4126
  this.schemaRetrievalLogs = [];
3137
4127
  this.resetLog = () => {
@@ -3147,7 +4137,8 @@ var ComfyHost = class {
3147
4137
  return new DefinedWorkflow(this, spec);
3148
4138
  };
3149
4139
  this.importWorkflowJson = (json, p = {}) => {
3150
- const apiJson = convertLiteGraphToPrompt(this.schema, json);
4140
+ const canonical = parseWorkflowJson(json);
4141
+ const apiJson = convertLiteGraphToPrompt(this.schema, canonical);
3151
4142
  return this.importApiJson(apiJson, p);
3152
4143
  };
3153
4144
  this.importApiJson = (json, p = {}) => {
@@ -3187,13 +4178,12 @@ var ComfyHost = class {
3187
4178
  this.schemaUpdateResult = null;
3188
4179
  this._schemaFromCache = null;
3189
4180
  this.postJSON_ = async (route, body) => {
3190
- const base = this.getServerHostHTTP();
3191
- for (const url of [`${base}/api${route}`, `${base}${route}`]) if ((await fetch(url, {
4181
+ const res = await this.fetch(route, {
3192
4182
  method: "POST",
3193
4183
  headers: { "Content-Type": "application/json" },
3194
4184
  body: JSON.stringify(body)
3195
- })).ok) return;
3196
- throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`);
4185
+ });
4186
+ if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
3197
4187
  };
3198
4188
  this.clearQueue = () => {
3199
4189
  return this.postJSON_("/queue", { clear: true });
@@ -3201,15 +4191,35 @@ var ComfyHost = class {
3201
4191
  this.interrupt = () => {
3202
4192
  return this.postJSON_("/interrupt", {});
3203
4193
  };
4194
+ this.fetchRawLogs = async () => {
4195
+ const res = await this.fetch("/internal/logs/raw", {}, { apiPrefix: false });
4196
+ if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`);
4197
+ const json = await res.json();
4198
+ const checked = WsMsgLogsData_ark(json);
4199
+ if (checked instanceof arktype.type.errors) {
4200
+ console.log(`[🔴] /!\\ /internal/logs/raw payload does not match schema.`);
4201
+ printArkResultInConsole(checked);
4202
+ }
4203
+ return json;
4204
+ };
4205
+ this.subscribeLogs = async (p) => {
4206
+ const res = await this.fetch("/internal/logs/subscribe", {
4207
+ method: "PATCH",
4208
+ headers: { "Content-Type": "application/json" },
4209
+ body: JSON.stringify({
4210
+ enabled: p.enabled,
4211
+ clientId: p.clientId
4212
+ })
4213
+ }, { apiPrefix: false });
4214
+ if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`);
4215
+ };
3204
4216
  this.fetchJSON_ = async (route) => {
3205
4217
  const base = this.getServerHostHTTP();
3206
- for (const url of [`${base}/api${route}`, `${base}${route}`]) {
3207
- const res = await fetch(url, { method: "GET" });
3208
- if (!res.ok) continue;
3209
- if (!(res.headers.get("content-type") ?? "").includes("json")) continue;
3210
- return await res.json();
3211
- }
3212
- throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`);
4218
+ const res = await this.fetch(route);
4219
+ if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`);
4220
+ const contentType = res.headers.get("content-type") ?? "";
4221
+ if (!contentType.includes("json")) throw new Error(`GET ${route} on ${base} answered '${contentType || "no content-type"}' instead of json`);
4222
+ return await res.json();
3213
4223
  };
3214
4224
  this.fetchAndUpdateSchema = async () => {
3215
4225
  try {
@@ -3249,8 +4259,12 @@ var ComfyHost = class {
3249
4259
  this.latentPreview = null;
3250
4260
  this.onLatentPreview = null;
3251
4261
  this.onStatus = null;
4262
+ this.onSession = null;
4263
+ this.onLogs = null;
3252
4264
  this.comfySessionId = "temp";
4265
+ this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
3253
4266
  this.status = null;
4267
+ this.base = parseHostBase(this.data);
3254
4268
  /** folder where file related to the host config will be cached */
3255
4269
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
3256
4270
  if (!(0, node_fs.existsSync)(this.cacheFolder)) {
@@ -3276,7 +4290,19 @@ var ComfyHost = class {
3276
4290
  return value;
3277
4291
  }
3278
4292
  getServerHostHTTP() {
3279
- return `${this.data.https ? "https" : "http"}://${this.data.host}:${this.data.port}`;
4293
+ return renderHttpBase(this.base);
4294
+ }
4295
+ /** extra headers + X-API-Key, for every http request AND the ws upgrade */
4296
+ authHeaders() {
4297
+ const out = {};
4298
+ if (this.data.headers != null) Object.assign(out, this.data.headers);
4299
+ if (this.data.apiKey != null) out["X-API-Key"] = this.data.apiKey;
4300
+ return out;
4301
+ }
4302
+ throwOnAuthError(res, route) {
4303
+ if (res.status === 401) throw new ComfyHostAuthError(401, this.data.id, this.data.apiKey != null ? `host '${this.data.id}': 401 on ${route} — API key invalid or expired` : `host '${this.data.id}': 401 on ${route} — host requires authentication, no apiKey configured`);
4304
+ if (res.status === 402) throw new ComfyHostAuthError(402, this.data.id, `host '${this.data.id}': 402 on ${route} — insufficient credits`);
4305
+ if (res.status === 429) throw new ComfyHostAuthError(429, this.data.id, `host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`);
3280
4306
  }
3281
4307
  get isConnected() {
3282
4308
  return this.ws?.isOpen ?? false;
@@ -3292,6 +4318,7 @@ var ComfyHost = class {
3292
4318
  this._readyReject = null;
3293
4319
  }
3294
4320
  async writeSDKToDisk() {
4321
+ if (this.data.sdkAutoWrite === false) return;
3295
4322
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
3296
4323
  if ((0, node_fs.existsSync)(this.sdkDTSPath) && (0, node_fs.readFileSync)(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
3297
4324
  await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
@@ -3338,6 +4365,7 @@ var ComfyHost = class {
3338
4365
  },
3339
4366
  onMessage: (e) => this.onMessage(e),
3340
4367
  url: () => this.getWSUrl(),
4368
+ headers: () => this.authHeaders(),
3341
4369
  onClose: () => {
3342
4370
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
3343
4371
  }
@@ -3351,8 +4379,16 @@ var ComfyHost = class {
3351
4379
  this._isUpdatingSchema = v;
3352
4380
  }
3353
4381
  /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
3354
- * idempotent like connect(): N co-imported modules parse the ~4MB cache once */
4382
+ * idempotent like connect(): N co-imported modules parse the ~4MB cache once.
4383
+ * A MISSING cache degrades LOUDLY to the base types instead of failing the
4384
+ * module import (a fresh consumer project has no cache yet — the bundled
4385
+ * examples must still open in the TUI; run() fetches the real schema through
4386
+ * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
3355
4387
  loadSchemaFromCache() {
4388
+ if (this._schemaFromCache == null && !(0, node_fs.existsSync)(this.comfyJSONPath)) {
4389
+ logError(`no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \`comfy-ts gen --id ${this.data.id} --host <url>\` or connect() once to create it`);
4390
+ return Promise.resolve();
4391
+ }
3356
4392
  this._schemaFromCache ??= (async () => {
3357
4393
  const object_info_json = comfyts.readJSON_(this.comfyJSONPath);
3358
4394
  const embeddings_json = comfyts.readJSON_(this.embeddingsPath, []);
@@ -3383,40 +4419,23 @@ var ComfyHost = class {
3383
4419
  onMessage(e) {
3384
4420
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
3385
4421
  if (e.data instanceof ArrayBuffer) {
3386
- const eventType = new DataView(e.data).getUint32(0);
3387
- const buffer = e.data.slice(4);
3388
- switch (eventType) {
3389
- case 1: {
3390
- const imageType = new DataView(e.data).getUint32(4);
3391
- let imageMime;
3392
- switch (imageType) {
3393
- case 1:
3394
- imageMime = "image/jpeg";
3395
- break;
3396
- case 2:
3397
- imageMime = "image/png";
3398
- break;
3399
- default:
3400
- imageMime = "image/jpeg";
3401
- break;
3402
- }
3403
- const imageBytes = buffer.slice(4);
3404
- const imageBlob = new Blob([imageBytes], { type: imageMime });
3405
- const imagePreview = URL.createObjectURL(imageBlob);
3406
- this.latentPreview = {
3407
- blob: imageBlob,
3408
- url: imagePreview,
3409
- receivedAt: Date.now(),
3410
- promptID: this.activePromptID
3411
- };
3412
- this.onLatentPreview?.({
3413
- bytes: new Uint8Array(imageBytes),
3414
- mime: imageMime,
3415
- promptID: this.activePromptID
3416
- });
3417
- break;
3418
- }
3419
- default: throw new Error(`Unknown binary websocket message of type ${eventType}`);
4422
+ const frame = parseBinaryWsFrame(e.data);
4423
+ if (frame.kind === "preview") {
4424
+ const imageBlob = new Blob([frame.bytes], { type: frame.mime });
4425
+ this.latentPreview = {
4426
+ blob: imageBlob,
4427
+ url: URL.createObjectURL(imageBlob),
4428
+ receivedAt: Date.now(),
4429
+ promptID: this.activePromptID
4430
+ };
4431
+ this.onLatentPreview?.({
4432
+ bytes: frame.bytes,
4433
+ mime: frame.mime,
4434
+ promptID: this.activePromptID
4435
+ });
4436
+ } else if (frame.kind === "unknown" && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
4437
+ this._unknownBinaryFrameTypes.add(frame.eventType);
4438
+ console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`);
3420
4439
  }
3421
4440
  return;
3422
4441
  }
@@ -3432,9 +4451,11 @@ var ComfyHost = class {
3432
4451
  const msg = msg_;
3433
4452
  if (msg.type === "status") {
3434
4453
  if (msg.data.sid) {
4454
+ const sidChanged = msg.data.sid !== this.comfySessionId;
3435
4455
  this.comfySessionId = msg.data.sid;
3436
4456
  this._sessionResolve?.();
3437
4457
  this._sessionResolve = null;
4458
+ if (sidChanged) this.onSession?.(msg.data.sid);
3438
4459
  }
3439
4460
  this.status = msg.data.status;
3440
4461
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -3457,6 +4478,10 @@ var ComfyHost = class {
3457
4478
  this.addLog(msg.data.data);
3458
4479
  return;
3459
4480
  }
4481
+ if (msg.type === "logs") {
4482
+ this.onLogs?.(msg.data);
4483
+ return;
4484
+ }
3460
4485
  console.log("❌", "Unknown message:", msg);
3461
4486
  logError("Unknown message type: " + JSON.stringify(msg.type));
3462
4487
  }
@@ -4020,7 +5045,11 @@ var ComfyTS = class ComfyTS {
4020
5045
  host(data) {
4021
5046
  const existing = this.hosts.get(data.id);
4022
5047
  if (existing != null) {
4023
- if (existing.data.host !== data.host || existing.data.port !== data.port || existing.data.https !== data.https) throw new Error(`host id '${data.id}' already registered at ${existing.data.host}:${existing.data.port} — refusing ${data.host}:${data.port}`);
5048
+ const incoming = parseHostBase(data);
5049
+ const cur = existing.base;
5050
+ const sameBase = cur.scheme === incoming.scheme && cur.host === incoming.host && cur.port === incoming.port && cur.basePath === incoming.basePath;
5051
+ const sameAuth = existing.data.apiKey == null === (data.apiKey == null);
5052
+ if (!sameBase || !sameAuth) throw new Error(`host id '${data.id}' already registered at ${renderHttpBase(cur)}${existing.data.apiKey != null ? " (authed)" : ""} — refusing ${renderHttpBase(incoming)}${data.apiKey != null ? " (authed)" : ""}`);
4024
5053
  return existing;
4025
5054
  }
4026
5055
  const created = new ComfyHost(data);
@@ -4082,6 +5111,7 @@ function loraTag(name, strength = 1, clipStrength) {
4082
5111
  exports.ChoiceVar = ChoiceVar;
4083
5112
  exports.ComfyExecution = ComfyExecution;
4084
5113
  exports.ComfyHost = ComfyHost;
5114
+ exports.ComfyHostAuthError = ComfyHostAuthError;
4085
5115
  exports.ComfyManager = ComfyManager;
4086
5116
  exports.ComfyNode = ComfyNode;
4087
5117
  exports.ComfyNodeOutput = ComfyNodeOutput;
@@ -4105,6 +5135,8 @@ exports.SeedVar = SeedVar;
4105
5135
  exports.SizeVar = SizeVar;
4106
5136
  exports.TextVar = TextVar;
4107
5137
  exports.ToggleVar = ToggleVar;
5138
+ exports.WorkflowConvertError = WorkflowConvertError;
5139
+ exports.WorkflowNormalizeError = WorkflowNormalizeError;
4108
5140
  exports.__FAIL = __FAIL;
4109
5141
  exports.__OK = __OK;
4110
5142
  exports.activeLoras = activeLoras;
@@ -4116,10 +5148,16 @@ exports.auto = auto;
4116
5148
  exports.auto_ = auto_;
4117
5149
  exports.codegenSDK = codegenSDK;
4118
5150
  exports.convertFlowToLiteGraphJSON = convertFlowToLiteGraphJSON;
5151
+ exports.convertLiteGraphToPrompt = convertLiteGraphToPrompt;
4119
5152
  exports.getLoraKeyword = getLoraKeyword;
4120
5153
  exports.hostIdToNamespace = hostIdToNamespace;
4121
5154
  exports.isTuiActive = isTuiActive;
4122
5155
  exports.loraTag = loraTag;
5156
+ exports.normalizeWorkflow = normalizeWorkflow;
5157
+ exports.parseHostBase = parseHostBase;
5158
+ exports.parseWorkflowJson = parseWorkflowJson;
5159
+ exports.renderHttpBase = renderHttpBase;
5160
+ exports.renderWsUrl = renderWsUrl;
4123
5161
  exports.resultFailure = resultFailure;
4124
5162
  exports.resultSuccess = resultSuccess;
4125
5163
  exports.setLoraKeyword = setLoraKeyword;