comfy-ts 2.22.0 → 2.24.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 (99) hide show
  1. package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-fsHtW5zG.js} +51 -17
  2. package/dist/ServeApp-fsHtW5zG.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-DZynSkZm.js} +405 -39
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +428 -46
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +147 -1
  11. package/dist/index.d.ts +147 -1
  12. package/dist/index.js +428 -47
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Y5ZI48vV.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve-CICU_wTL.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve-CICU_wTL.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-CViJXsHL.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-CViJXsHL.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BGYJZGMD.js} +18 -3
  21. package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/serve-web.js +46 -43
  23. package/dist/web.d.ts +147 -1
  24. package/dist/web.js +428 -47
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +1 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +6 -56
  29. package/examples/depth-explorer/serve.ts +12 -133
  30. package/examples/depth-explorer/web/App.tsx +20 -91
  31. package/examples/depth-explorer/web/index.html +1 -0
  32. package/examples/depth-explorer/web/state.ts +26 -109
  33. package/examples/depth-explorer/web/styles.css +1 -286
  34. package/examples/explorer-kit/catalog.ts +80 -0
  35. package/examples/explorer-kit/server.ts +167 -0
  36. package/examples/explorer-kit/web/base.css +289 -0
  37. package/examples/explorer-kit/web/runs.ts +160 -0
  38. package/examples/explorer-kit/web/ui.tsx +125 -0
  39. package/examples/rvion/17-relight.cflow.ts +2 -1
  40. package/examples/rvion/18-world.cflow.ts +101 -0
  41. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  42. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  43. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  44. package/examples/rvion/flythroughChain.ts +171 -0
  45. package/examples/rvion/flythroughColmap.ts +157 -0
  46. package/examples/rvion/flythroughFuse.ts +199 -0
  47. package/examples/rvion/flythroughGuide.ts +300 -0
  48. package/examples/rvion/flythroughPalette.ts +310 -0
  49. package/examples/rvion/flythroughPath.ts +177 -0
  50. package/examples/rvion/flythroughSplat.ts +73 -0
  51. package/examples/rvion/grow-splat/align.ts +114 -0
  52. package/examples/rvion/grow-splat/grow.ts +198 -0
  53. package/examples/rvion/grow-splat/ply.ts +166 -0
  54. package/examples/rvion/grow-splat/raster.ts +207 -0
  55. package/examples/rvion/grow-splat/sharp.ts +45 -0
  56. package/examples/rvion/splatDataset.ts +80 -0
  57. package/examples/rvion/splatEval.ts +380 -0
  58. package/examples/upscale-explorer/models.ts +341 -0
  59. package/examples/upscale-explorer/serve.ts +19 -0
  60. package/examples/upscale-explorer/web/App.tsx +250 -0
  61. package/examples/upscale-explorer/web/compare.tsx +285 -0
  62. package/examples/upscale-explorer/web/index.html +15 -0
  63. package/examples/upscale-explorer/web/main.tsx +12 -0
  64. package/examples/upscale-explorer/web/state.ts +279 -0
  65. package/examples/upscale-explorer/web/styles.css +241 -0
  66. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  67. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  68. package/examples/world-explorer/serve.ts +171 -0
  69. package/examples/world-explorer/web/index.html +14 -0
  70. package/examples/world-explorer/web/main.tsx +200 -0
  71. package/examples/world-explorer/web/state.ts +212 -0
  72. package/examples/world-explorer/web/styles.css +131 -0
  73. package/examples/world-explorer/web/thumb.ts +21 -0
  74. package/examples/world-explorer/web/tsconfig.json +11 -0
  75. package/examples/world-explorer/world-state.ts +40 -0
  76. package/package.json +7 -8
  77. package/src/cli/serve/ServeApp.ts +27 -2
  78. package/src/cli/serve/resultHistory.ts +22 -4
  79. package/src/cli/serve/thumbs.ts +19 -8
  80. package/src/cli/serve/web/api.ts +4 -0
  81. package/src/cli/serve/web/components/Gallery.tsx +24 -1
  82. package/src/cli/serve/web/styles.ts +3 -0
  83. package/src/coreExports.ts +6 -0
  84. package/src/graph/ComfyNode.ts +12 -2
  85. package/src/host/ComfyHost.ts +159 -2
  86. package/src/host/ResilientWebsocket.ts +10 -0
  87. package/src/manager/script-update-manager.bun.ts +0 -7
  88. package/src/runner/ComfyExecution.ts +185 -23
  89. package/src/runner/ComfyWorkflow.ts +22 -0
  90. package/src/runner/ComfyWsApi.ts +3 -1
  91. package/src/runner/comfyOrgApiKey.ts +44 -0
  92. package/src/runner/historyReplay.ts +53 -0
  93. package/src/runner/outputs3d.ts +18 -0
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  96. package/src/state.ts +2 -0
  97. package/src/vars/DefinedWorkflow.ts +1 -0
  98. package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
  99. package/dist/exampleAssets-1NHndnNB.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { X as ansi, a as DefinedWorkflow, at as importSharp, ct as getComfyStorage, dt as logError, ft as logInfo, gt as extractErrorMessage, ht as sha1HexOfString, it as hashArrayBuffer, lt as resolveComfyStorage, mt as statelessRegex, n as diffSchemas, nt as isVideoFilename, ot as isRecord$1, pt as logSuccess, rt as mediaMime, st as bang, t as MODEL_LISTS, ut as isQuiet } from "./schemaDrift-CzjaIwZX.js";
1
+ import { X as ansi, _t as sha1HexOfString, a as DefinedWorkflow, at as mediaMime, ct as isRecord$1, dt as resolveComfyStorage, et as model3dMime, ft as isQuiet, gt as statelessRegex, ht as logSuccess, it as isVideoFilename, lt as bang, mt as logInfo, n as diffSchemas, ot as hashArrayBuffer, pt as logError, rt as extensionOf, st as importSharp, t as MODEL_LISTS, ut as getComfyStorage, vt as extractErrorMessage } from "./schemaDrift-BGYJZGMD.js";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { basename, dirname, join } from "pathe";
@@ -695,7 +695,12 @@ function codegenSDK(opts) {
695
695
  p(`INVALID_null: any`);
696
696
  p("");
697
697
  p("// named slot types: everything an input of that type accepts");
698
- for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
698
+ const slotTypeNames = new Set(slotTypes.map((t) => t.comfyType));
699
+ for (const t of slotTypes) {
700
+ const own = `${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`;
701
+ const anyOf = (t.comfyType.includes(",") ? t.comfyType.split(",").map((s) => s.trim()) : []).map((part) => slotTypeNames.has(part) ? `Accepts['${part}']` : `ComfyNodeOutput<'${part}'>`);
702
+ p(`${escapeJSKey(t.comfyType)}: ${[own, ...anyOf].join(" | ")}`);
703
+ }
699
704
  p("");
700
705
  p("// enum unions: literal values or an output carrying one");
701
706
  for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
@@ -1003,7 +1008,7 @@ var ComfySchema = class {
1003
1008
  };
1004
1009
  //#endregion
1005
1010
  //#region package.json
1006
- var version = "2.22.0";
1011
+ var version = "2.24.0";
1007
1012
  //#endregion
1008
1013
  //#region src/litegraph/LiteGraphLinkID.ts
1009
1014
  const asLiteGraphLinkID = (id) => id;
@@ -2495,13 +2500,14 @@ var ComfyNode = class ComfyNode {
2495
2500
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
2496
2501
  }
2497
2502
  _getOutputForTypeOrCrash(type) {
2498
- const i = this.$schema.outputs.find((i) => i.typeName === type);
2503
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
2504
+ if (i == null) throw new Error(`🔴 ${this.$schema.nodeKey} has no output of type ${type}: link one of its outputs by name instead`);
2499
2505
  const val = this.outputs[i.outKey];
2500
2506
  if (val instanceof ComfyNodeOutput) return val;
2501
2507
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
2502
2508
  }
2503
2509
  _getOutputForTypeOrNull(type) {
2504
- const i = this.$schema.outputs.find((i) => i.typeName === type);
2510
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
2505
2511
  if (i == null) return null;
2506
2512
  const val = this.outputs[i.outKey];
2507
2513
  if (val == null) return null;
@@ -2509,6 +2515,11 @@ var ComfyNode = class ComfyNode {
2509
2515
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
2510
2516
  }
2511
2517
  };
2518
+ /** an input typed `MESH,FILE_3D_GLB` takes an output of ANY listed type (ComfyUI's SaveGLB) */
2519
+ function slotTypeAccepts(inputType, outputType) {
2520
+ if (inputType === outputType) return true;
2521
+ return inputType.includes(",") && inputType.split(",").some((part) => part.trim() === outputType);
2522
+ }
2512
2523
  //#endregion
2513
2524
  //#region src/host/ComfyWorkflowBuilder.ts
2514
2525
  var ComfyWorkflowBuilder = class {
@@ -2843,7 +2854,10 @@ const types$1 = scope({
2843
2854
  Timestamp: "number",
2844
2855
  ApiPromptInput: {
2845
2856
  client_id: "string",
2846
- extra_data: { extra_pnginfo: "unknown" },
2857
+ extra_data: {
2858
+ extra_pnginfo: "unknown",
2859
+ "api_key_comfy_org?": "string"
2860
+ },
2847
2861
  prompt: "unknown"
2848
2862
  },
2849
2863
  NodeProgress: {
@@ -2898,6 +2912,7 @@ const types$1 = scope({
2898
2912
  "audio?": "ComfyImageInfo[]",
2899
2913
  "video?": "ComfyImageInfo[]",
2900
2914
  "gifs?": "ComfyImageInfo[]",
2915
+ "3d?": "ComfyImageInfo[]",
2901
2916
  "text?": "unknown[]"
2902
2917
  },
2903
2918
  WsMsgExecuted: {
@@ -3192,6 +3207,66 @@ var MediaImage = class MediaImage {
3192
3207
  }
3193
3208
  };
3194
3209
  //#endregion
3210
+ //#region src/runner/historyReplay.ts
3211
+ const END_TYPES = /* @__PURE__ */ new Set([
3212
+ "execution_success",
3213
+ "execution_error",
3214
+ "execution_interrupted"
3215
+ ]);
3216
+ /** a prompt's `GET /history/<id>` reply as the ws messages a client missed. Null while the host has no
3217
+ * entry for it: queued, running, or lost */
3218
+ function historyReplay(json, promptId) {
3219
+ const entry = field(json, promptId);
3220
+ if (entry == null) return null;
3221
+ const problems = [];
3222
+ const valid = (raw) => {
3223
+ const res = types$1.PromptRelated_WsMsg(raw);
3224
+ if (!(res instanceof type.errors)) return res;
3225
+ problems.push(`${JSON.stringify(raw).slice(0, 200)}: ${res.summary}`);
3226
+ return null;
3227
+ };
3228
+ const executed = [];
3229
+ const outputs = field(entry, "outputs");
3230
+ if (typeof outputs === "object" && outputs != null) for (const [node, output] of Object.entries(outputs)) {
3231
+ const msg = valid({
3232
+ type: "executed",
3233
+ data: {
3234
+ node,
3235
+ output,
3236
+ prompt_id: promptId
3237
+ }
3238
+ });
3239
+ if (msg != null) executed.push(msg);
3240
+ }
3241
+ const status = field(entry, "status");
3242
+ const list = field(status, "messages");
3243
+ let end = null;
3244
+ for (const m of Array.isArray(list) ? list : []) {
3245
+ if (!Array.isArray(m) || typeof m[0] !== "string" || !END_TYPES.has(m[0])) continue;
3246
+ end = valid({
3247
+ type: m[0],
3248
+ data: m[1]
3249
+ });
3250
+ }
3251
+ const statusStr = field(status, "status_str");
3252
+ if (end == null && (status == null || statusStr === "success")) end = valid({
3253
+ type: "execution_success",
3254
+ data: {
3255
+ prompt_id: promptId,
3256
+ timestamp: Date.now()
3257
+ }
3258
+ });
3259
+ return {
3260
+ executed,
3261
+ end,
3262
+ problems
3263
+ };
3264
+ }
3265
+ function field(x, key) {
3266
+ if (typeof x !== "object" || x == null) return null;
3267
+ return Reflect.get(x, key) ?? null;
3268
+ }
3269
+ //#endregion
3195
3270
  //#region src/runner/ComfyExecution.ts
3196
3271
  /** paths claimed by in-flight retrievals: two same-second runs on a
3197
3272
  * counter-resetting cloud host compute the same name before either writes.
@@ -3218,6 +3293,9 @@ var ComfyExecution = class {
3218
3293
  this._resolve = resolve;
3219
3294
  });
3220
3295
  this.onPromptRelatedMessage = (msg) => {
3296
+ if (this.ended) return;
3297
+ this.heard();
3298
+ if (msg.type === "execution_success" || msg.type === "execution_error" || msg.type === "execution_interrupted") this.ended = true;
3221
3299
  const graph = this.workflow;
3222
3300
  if (msg.type === "binary_preview_frame") {
3223
3301
  if (this.wsOutputNodeExecuting) this.onWsImageOutput({
@@ -3248,6 +3326,7 @@ var ComfyExecution = class {
3248
3326
  this.workflow.onExecuting(msg);
3249
3327
  };
3250
3328
  this.onExecutionSuccess = async (_msg) => {
3329
+ if (this.mayHaveMissedEvents) await this.retrieveMissedOutputs();
3251
3330
  await Promise.all(this.pendingPromises);
3252
3331
  return this._finish({ status: "Success" });
3253
3332
  };
@@ -3261,6 +3340,7 @@ var ComfyExecution = class {
3261
3340
  };
3262
3341
  this.onExecuted = (msg) => {
3263
3342
  const promptNodeID = msg.data.node;
3343
+ this.heardExecuted.add(promptNodeID);
3264
3344
  for (const entry of msg.data.output?.text ?? []) {
3265
3345
  if (typeof entry !== "string") continue;
3266
3346
  const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null;
@@ -3276,7 +3356,7 @@ var ComfyExecution = class {
3276
3356
  ...out?.video ?? [],
3277
3357
  ...out?.gifs ?? []
3278
3358
  ].filter((f) => f.type !== "input");
3279
- for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile("video", video, promptNodeID).catch((e) => {
3359
+ for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile(video, promptNodeID, mediaMime(video.filename)).then((o) => void this.videos.push(o), (e) => {
3280
3360
  console.error(`🔴 failed to retrieve ${video.filename}:`, e);
3281
3361
  this.videoErrors.push({
3282
3362
  video,
@@ -3291,35 +3371,118 @@ var ComfyExecution = class {
3291
3371
  error: e
3292
3372
  });
3293
3373
  }));
3294
- for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile("audio", audio, promptNodeID).catch((e) => {
3374
+ for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile(audio, promptNodeID, mediaMime(audio.filename)).then((o) => void this.audios.push(o), (e) => {
3295
3375
  console.error(`🔴 failed to retrieve ${audio.filename}:`, e);
3296
3376
  this.audioErrors.push({
3297
3377
  audio,
3298
3378
  error: e
3299
3379
  });
3300
3380
  }));
3381
+ for (const model3d of (out?.["3d"] ?? []).filter((f) => f.type !== "input")) this.pendingPromises.push(this.retrieveFile(model3d, promptNodeID, model3dMime(model3d.filename)).then((o) => void this.models3d.push({
3382
+ ...o,
3383
+ format: extensionOf(o.filename)
3384
+ }), (e) => {
3385
+ console.error(`🔴 failed to retrieve ${model3d.filename}:`, e);
3386
+ this.models3dErrors.push({
3387
+ model3d,
3388
+ error: e
3389
+ });
3390
+ }));
3301
3391
  };
3302
3392
  this.pendingPromises = [];
3393
+ this.ended = false;
3394
+ this.heardExecuted = /* @__PURE__ */ new Set();
3395
+ this.mayHaveMissedEvents = false;
3396
+ this.historyRetry = {
3397
+ tries: 5,
3398
+ ms: 400
3399
+ };
3400
+ this.retrieveMissedOutputs = async () => {
3401
+ const id = this.data.id;
3402
+ for (let i = 0; i < this.historyRetry.tries; i++) {
3403
+ if (this.host.reconcileOff != null) return;
3404
+ if (i > 0) await new Promise((r) => setTimeout(r, this.historyRetry.ms));
3405
+ try {
3406
+ const replay = historyReplay(await this.host.fetchHistory(id), id);
3407
+ if (replay == null) continue;
3408
+ return this.replayUnheardOutputs(replay);
3409
+ } catch (e) {
3410
+ if (this.host.noteReconcileFailure(e)) return;
3411
+ return logError(`run ${id}: its history did not answer (${extractErrorMessage(e)}); an output sent while the socket was down may be missing`);
3412
+ }
3413
+ }
3414
+ logError(`run ${id}: no history entry after its end; an output sent while the socket was down may be missing`);
3415
+ };
3416
+ this.lastHeardAt = Date.now();
3417
+ this.reconciling = false;
3418
+ this.loggedReconcileProblems = /* @__PURE__ */ new Set();
3419
+ this.reconcile = async (queued) => {
3420
+ const id = this.data.id;
3421
+ const hostId = this.host.data.id;
3422
+ try {
3423
+ if (this.ended || queued?.has(id) === true) return "waiting";
3424
+ let replay;
3425
+ try {
3426
+ replay = historyReplay(await this.host.fetchHistory(id), id);
3427
+ } catch (e) {
3428
+ if (!this.host.noteReconcileFailure(e)) this.logReconcileOnce(`the history of host '${hostId}' did not answer (${extractErrorMessage(e)}); waiting for its events`);
3429
+ return "waiting";
3430
+ }
3431
+ if (this.ended) return "waiting";
3432
+ if (replay == null) {
3433
+ if (queued == null) return "waiting";
3434
+ const reason = `host '${hostId}' has it neither in its queue nor in its history (cancelled, or the host restarted)`;
3435
+ logError(`run ${id}: ${reason}; the run fails`);
3436
+ this.ended = true;
3437
+ await this._finish({
3438
+ status: "Failure",
3439
+ error: null,
3440
+ reason
3441
+ });
3442
+ return "lost";
3443
+ }
3444
+ const sinceHeard = Date.now() - this.lastHeardAt;
3445
+ if (!this.mayHaveMissedEvents && this.sendsWsFrames && sinceHeard < this.host.runSilenceMaxMs) return "waiting";
3446
+ logInfo(`run ${id}: ended on host '${hostId}' without its end reaching the socket, finishing from its history`);
3447
+ for (const p of replay.problems) logError(`run ${id}: a history entry does not match the ws schemas, skipped: ${p}`);
3448
+ this.replayUnheardOutputs(replay);
3449
+ if (this.ephemeral) logError(`run ${id}: SaveImageWebsocket frames sent while the socket did not hear are lost (they never reach the server disk)`);
3450
+ if (replay.end != null) {
3451
+ this.onPromptRelatedMessage(replay.end);
3452
+ return "history";
3453
+ }
3454
+ const reason = `its history entry on host '${hostId}' carries no end message`;
3455
+ logError(`run ${id}: ${reason}; the run fails`);
3456
+ this.ended = true;
3457
+ await this._finish({
3458
+ status: "Failure",
3459
+ error: null,
3460
+ reason
3461
+ });
3462
+ return "history";
3463
+ } finally {
3464
+ this.reconciling = false;
3465
+ }
3466
+ };
3303
3467
  this.audioErrors = [];
3304
3468
  this.audios = [];
3305
3469
  this.videoErrors = [];
3306
3470
  this.videos = [];
3307
- this.retrieveFile = async (kind, info, promptNodeID) => {
3471
+ this.models3dErrors = [];
3472
+ this.models3d = [];
3473
+ this.retrieveFile = async (info, promptNodeID, mime) => {
3308
3474
  const response = await this.host.fetchFile("/view?" + new URLSearchParams(info).toString());
3309
3475
  const bytes = new Uint8Array(await response.arrayBuffer());
3310
- const mime = mediaMime(info.filename);
3311
- const list = kind === "audio" ? this.audios : this.videos;
3476
+ const tags = this.tagsOf(promptNodeID);
3312
3477
  const sf = this.save;
3313
- if (sf == null) {
3314
- list.push({
3315
- nodeId: promptNodeID,
3316
- filename: info.filename,
3317
- mime,
3318
- bytes,
3319
- absPath: null
3320
- });
3321
- return;
3322
- }
3478
+ if (sf == null) return {
3479
+ nodeId: promptNodeID,
3480
+ filename: info.filename,
3481
+ mime,
3482
+ bytes,
3483
+ absPath: null,
3484
+ tags
3485
+ };
3323
3486
  const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs["filename_prefix"];
3324
3487
  const written = await this.encodeAndWrite({
3325
3488
  bytes,
@@ -3331,13 +3494,14 @@ var ComfyExecution = class {
3331
3494
  subfolder: info.subfolder,
3332
3495
  filename: info.filename
3333
3496
  });
3334
- list.push({
3497
+ return {
3335
3498
  nodeId: promptNodeID,
3336
3499
  filename: info.filename,
3337
3500
  mime,
3338
3501
  bytes,
3339
- absPath: written.path
3340
- });
3502
+ absPath: written.path,
3503
+ tags
3504
+ };
3341
3505
  };
3342
3506
  this.imageErrors = [];
3343
3507
  this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
@@ -3415,6 +3579,7 @@ var ComfyExecution = class {
3415
3579
  };
3416
3580
  };
3417
3581
  this.onWsImageOutput = (p) => {
3582
+ this.heard();
3418
3583
  const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
3419
3584
  this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
3420
3585
  console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
@@ -3477,7 +3642,7 @@ var ComfyExecution = class {
3477
3642
  this.onProgress = init.onProgress ?? null;
3478
3643
  this.onPreview = init.onPreview ?? null;
3479
3644
  this.logProgress = init.logProgress ?? false;
3480
- this.host.executions.set(data.id, this);
3645
+ this.host.trackExecution(this);
3481
3646
  this.onCreate();
3482
3647
  }
3483
3648
  get progress() {
@@ -3513,6 +3678,7 @@ var ComfyExecution = class {
3513
3678
  const outputs = [`${this.images.length} image(s)`];
3514
3679
  if (this.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`);
3515
3680
  if (this.videos.length > 0) outputs.push(`${this.videos.length} video(s)`);
3681
+ if (this.models3d.length > 0) outputs.push(`${this.models3d.length} 3d model(s)`);
3516
3682
  if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`);
3517
3683
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${outputs.join(" · ")}`;
3518
3684
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
@@ -3541,13 +3707,39 @@ var ComfyExecution = class {
3541
3707
  get status() {
3542
3708
  return this.data.status ?? "New";
3543
3709
  }
3710
+ replayUnheardOutputs(replay) {
3711
+ for (const msg of replay.executed) if (msg.type === "executed" && !this.heardExecuted.has(msg.data.node)) this.onExecuted(msg);
3712
+ }
3713
+ heard() {
3714
+ this.lastHeardAt = Date.now();
3715
+ }
3716
+ logReconcileOnce(msg) {
3717
+ if (this.loggedReconcileProblems.has(msg)) return;
3718
+ this.loggedReconcileProblems.add(msg);
3719
+ logError(`run ${this.data.id}: ${msg}`);
3720
+ }
3721
+ /** @internal called before the host reads its queue. After a reconnect the run may have lost events,
3722
+ * so its end reads /history for them; the flag is set before any await, so a live end that lands
3723
+ * during the reads still looks. A check for silence alone does not set it: a quiet run lost nothing */
3724
+ beginReconcile(why) {
3725
+ this.reconciling = true;
3726
+ if (why === "reconnect") this.mayHaveMissedEvents = true;
3727
+ }
3544
3728
  /** accumulate an output on the prompt; tags from node metadata ride along */
3545
3729
  pushImage(img, promptNodeID) {
3546
- const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
3547
- if (promptMeta?.tag) img.tags.push(promptMeta.tag);
3548
- if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
3730
+ img.tags.push(...this.tagsOf(promptNodeID));
3549
3731
  this.images.push(img);
3550
3732
  }
3733
+ /** the tags an output node was built with (`{ tag }` / `{ tags }` metadata) */
3734
+ tagsOf(promptNodeID) {
3735
+ const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
3736
+ return [...promptMeta?.tag ? [promptMeta.tag] : [], ...promptMeta?.tags ?? []];
3737
+ }
3738
+ /** the sent graph saves through SaveImageWebsocket: those outputs exist only as ws frames */
3739
+ get sendsWsFrames() {
3740
+ const apiJson = this.snapshot?.apiJson ?? this.workflow.apiJson;
3741
+ return Object.values(apiJson).some((n) => n?.class_type === "SaveImageWebsocket");
3742
+ }
3551
3743
  /** true while the currently executing node is a SaveImageWebsocket in the
3552
3744
  * SENT snapshot (the ephemeral rewrite only touches the snapshot, so the
3553
3745
  * live graph may still say SaveImage) — binary frames are then OUTPUTS */
@@ -3559,6 +3751,7 @@ var ComfyExecution = class {
3559
3751
  /** @internal a live preview frame of this run; never an output (the host routes ws saver frames
3560
3752
  * to onWsImageOutput before they get here) */
3561
3753
  onPreviewFrame(p) {
3754
+ this.heard();
3562
3755
  const listener = this.onPreview;
3563
3756
  if (listener == null) return;
3564
3757
  const current = this.workflow.currentExecutingNode;
@@ -3580,6 +3773,7 @@ var ComfyExecution = class {
3580
3773
  }
3581
3774
  /** @internal a live-text frame for one node */
3582
3775
  onProgressText(p) {
3776
+ this.heard();
3583
3777
  this.progressTexts.set(p.nodeId, p.text);
3584
3778
  this.progressText = p.text;
3585
3779
  this.emitProgress();
@@ -3593,6 +3787,35 @@ var ComfyExecution = class {
3593
3787
  }
3594
3788
  };
3595
3789
  //#endregion
3790
+ //#region src/runner/comfyOrgApiKey.ts
3791
+ /** the prompt holds a paid partner node and no Comfy account key was set */
3792
+ var ComfyOrgApiKeyMissingError = class extends Error {
3793
+ constructor(hostId, nodes) {
3794
+ const list = nodes.map((n) => `${n.classType} #${n.id}`).join(", ");
3795
+ super(`🔴 host '${hostId}': the prompt holds partner API node(s) ${list}, which bill a Comfy account, and no Comfy account key is set. Set it with \`comfy.host({ id: '${hostId}', comfyOrgApiKey })\` or \`run({ comfyOrgApiKey })\` (a string or a thunk; the key comes from platform.comfy.org). Nothing was sent.`);
3796
+ this.hostId = hostId;
3797
+ this.nodes = nodes;
3798
+ this.name = "ComfyOrgApiKeyMissingError";
3799
+ }
3800
+ };
3801
+ /** the nodes of a prompt whose schema says `api_node: true` */
3802
+ const partnerApiNodes = (apiJson, schema) => {
3803
+ const out = [];
3804
+ for (const [id, node] of Object.entries(apiJson)) if (schema.nodesByNameInComfy[node.class_type]?.raw.api_node === true) out.push({
3805
+ id,
3806
+ classType: node.class_type
3807
+ });
3808
+ return out;
3809
+ };
3810
+ /** the first source set wins; an empty string counts as unset */
3811
+ const resolveComfyOrgApiKey = async (sources) => {
3812
+ for (const src of sources) {
3813
+ if (src == null) continue;
3814
+ const key = typeof src === "string" ? src : await src();
3815
+ if (key != null && key !== "") return key;
3816
+ }
3817
+ };
3818
+ //#endregion
3596
3819
  //#region src/runner/ephemeral.ts
3597
3820
  /**
3598
3821
  * the `ephemeral: true` rewrite (architecture.md item 14): every SaveImage
@@ -3729,6 +3952,8 @@ function comfyWorkflowAutoLayout(p) {
3729
3952
  }
3730
3953
  //#endregion
3731
3954
  //#region src/runner/ComfyWorkflow.ts
3955
+ /** a Comfy Cloud host's X-API-Key is a platform.comfy.org key, the one partner nodes bill to */
3956
+ const COMFY_CLOUD_HOST = "cloud.comfy.org";
3732
3957
  const asComfyWorkflowID = (x) => x;
3733
3958
  var ComfyWorkflow = class {
3734
3959
  constructor(host, data) {
@@ -3859,14 +4084,29 @@ var ComfyWorkflow = class {
3859
4084
  const hasWsSaver = Object.values(snapshot.apiJson).some((n) => n.class_type === "SaveImageWebsocket");
3860
4085
  if (rewritten === 0 && !hasWsSaver) console.warn(`🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`);
3861
4086
  }
4087
+ const partners = partnerApiNodes(snapshot.apiJson, this.schema);
4088
+ let comfyOrgApiKey;
4089
+ if (partners.length > 0) {
4090
+ const data = this.host.data;
4091
+ const cloudKey = data.apiKey != null && this.host.base.host === COMFY_CLOUD_HOST ? data.apiKey : void 0;
4092
+ comfyOrgApiKey = await resolveComfyOrgApiKey([
4093
+ p.comfyOrgApiKey,
4094
+ data.comfyOrgApiKey,
4095
+ cloudKey
4096
+ ]);
4097
+ if (comfyOrgApiKey == null) throw new ComfyOrgApiKeyMissingError(data.id, partners);
4098
+ }
3862
4099
  const out = {
3863
4100
  client_id: this.host.comfySessionId,
3864
4101
  prompt: snapshot.apiJson,
3865
- extra_data: { extra_pnginfo: {
3866
- workflow: snapshot.workflowJson,
3867
- comfy_ts_workflow_id: this.id,
3868
- comfy_ts_version: comfyts.version
3869
- } }
4102
+ extra_data: {
4103
+ extra_pnginfo: {
4104
+ workflow: snapshot.workflowJson,
4105
+ comfy_ts_workflow_id: this.id,
4106
+ comfy_ts_version: comfyts.version
4107
+ },
4108
+ ...comfyOrgApiKey != null ? { api_key_comfy_org: comfyOrgApiKey } : {}
4109
+ }
3870
4110
  };
3871
4111
  const res = await this.host.fetch("/prompt", {
3872
4112
  method: "POST",
@@ -3973,7 +4213,8 @@ const types = scope({
3973
4213
  output_node: "boolean",
3974
4214
  "output_tooltips?": "(string | null)[]",
3975
4215
  "deprecated?": "boolean",
3976
- "experimental?": "boolean"
4216
+ "experimental?": "boolean",
4217
+ "api_node?": "boolean"
3977
4218
  },
3978
4219
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3979
4220
  ComfyInputSpecAlt2: ["ComfyInputType"],
@@ -4839,6 +5080,12 @@ var ResilientWebSocketClient = class {
4839
5080
  }
4840
5081
  }, ms);
4841
5082
  }
5083
+ /** close the socket cleanly, then reconnect as after any close: the server ends its handler first */
5084
+ reconnect() {
5085
+ if (this.permanentlyClosed || this.currentWS == null) return;
5086
+ this.addInfo("closing the socket to reconnect");
5087
+ this.currentWS.close();
5088
+ }
4842
5089
  /** close and stop reconnecting (lets a script exit cleanly) */
4843
5090
  disconnectPermanently() {
4844
5091
  this.permanentlyClosed = true;
@@ -4860,6 +5107,7 @@ var ResilientWebSocketClient = class {
4860
5107
  }
4861
5108
  async connect() {
4862
5109
  this.isOpen = false;
5110
+ this.url = this.options.url();
4863
5111
  const prevWS = this.currentWS;
4864
5112
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
4865
5113
  this.stopHeartbeat();
@@ -4929,10 +5177,17 @@ var ResilientWebSocketClient = class {
4929
5177
  };
4930
5178
  //#endregion
4931
5179
  //#region src/host/ComfyHost.ts
4932
- /** the host never came up within ConnectOptions.timeoutMs */
4933
- var ComfyHostUnreachableError = class extends Error {
5180
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
5181
+ var HostRouteUnusableError = class extends Error {
4934
5182
  constructor(..._args) {
4935
5183
  super(..._args);
5184
+ this.name = "HostRouteUnusableError";
5185
+ }
5186
+ };
5187
+ /** the host never came up within ConnectOptions.timeoutMs */
5188
+ var ComfyHostUnreachableError = class extends Error {
5189
+ constructor(..._args2) {
5190
+ super(..._args2);
4936
5191
  this.name = "ComfyHostUnreachableError";
4937
5192
  }
4938
5193
  };
@@ -5105,6 +5360,7 @@ var ComfyHost = class {
5105
5360
  this._connectTimer = null;
5106
5361
  this.disconnect = () => {
5107
5362
  this.clearConnectTimer();
5363
+ this.stopWatchdog();
5108
5364
  this.ws?.disconnectPermanently();
5109
5365
  this.ws = null;
5110
5366
  this._ready = null;
@@ -5124,6 +5380,50 @@ var ComfyHost = class {
5124
5380
  });
5125
5381
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
5126
5382
  };
5383
+ this.fetchReconcileJSON_ = async (route) => {
5384
+ const res = await this.fetch(route);
5385
+ const contentType = res.headers.get("content-type") ?? "";
5386
+ if (res.ok && contentType.includes("json")) return res.json();
5387
+ res.body?.cancel();
5388
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || "no content-type"}`);
5389
+ };
5390
+ this.fetchHistory = (promptId) => {
5391
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`);
5392
+ };
5393
+ this.fetchQueuedPromptIds = async () => {
5394
+ const json = await this.fetchReconcileJSON_("/queue");
5395
+ const ids = /* @__PURE__ */ new Set();
5396
+ for (const key of ["queue_running", "queue_pending"]) {
5397
+ const list = typeof json === "object" && json != null ? Reflect.get(json, key) : null;
5398
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`);
5399
+ for (const item of list) {
5400
+ if (!Array.isArray(item) || typeof item[1] !== "string") throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`);
5401
+ ids.add(item[1]);
5402
+ }
5403
+ }
5404
+ return ids;
5405
+ };
5406
+ this.reconcileOff = null;
5407
+ this.fetchQueuedPromptIdsOrNull = async () => {
5408
+ try {
5409
+ return await this.fetchQueuedPromptIds();
5410
+ } catch (e) {
5411
+ if (this.noteReconcileFailure(e)) return null;
5412
+ const msg = extractErrorMessage(e);
5413
+ if (!this._loggedQueueProblems.has(msg)) {
5414
+ this._loggedQueueProblems.add(msg);
5415
+ logError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`);
5416
+ }
5417
+ return null;
5418
+ }
5419
+ };
5420
+ this._loggedQueueProblems = /* @__PURE__ */ new Set();
5421
+ this.runSilenceMs = 1e3;
5422
+ this.runSilenceMaxMs = 3e4;
5423
+ this._silenceWaitMs = null;
5424
+ this._lastCheckAt = 0;
5425
+ this._checking = false;
5426
+ this._watchdog = null;
5127
5427
  this.clearQueue = () => {
5128
5428
  return this.postJSON_("/queue", { clear: true });
5129
5429
  };
@@ -5253,6 +5553,7 @@ var ComfyHost = class {
5253
5553
  this.comfySessionId = "temp";
5254
5554
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
5255
5555
  this._unknownWsEventTypes = /* @__PURE__ */ new Set();
5556
+ this._socketIsNew = false;
5256
5557
  this.status = null;
5257
5558
  this.lastWsMessageAt = null;
5258
5559
  /** folder where file related to the host config will be cached */
@@ -5358,6 +5659,8 @@ var ComfyHost = class {
5358
5659
  this.ws = new ResilientWebSocketClient({
5359
5660
  onConnectOrReconnect: async () => {
5360
5661
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`);
5662
+ this._socketIsNew = true;
5663
+ this.reconcileRuns([...this.executions.values()], "reconnect");
5361
5664
  if (this.shouldUseSchemaCache()) try {
5362
5665
  await this.loadSchemaFromCache();
5363
5666
  await this.waitForSession();
@@ -5371,7 +5674,7 @@ var ComfyHost = class {
5371
5674
  this.markReady();
5372
5675
  },
5373
5676
  onMessage: (e) => this.onMessage(e),
5374
- url: () => this.getWSUrl(),
5677
+ url: () => this.comfySessionId === "temp" ? this.getWSUrl() : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
5375
5678
  headers: () => this.authHeaders(),
5376
5679
  onTransportDead: (e) => this.markFailed(e),
5377
5680
  onFirstConnectFailed: (e) => this.markFailed(new ComfyHostUnreachableError(`host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`)),
@@ -5413,6 +5716,65 @@ var ComfyHost = class {
5413
5716
  });
5414
5717
  return this._schemaFromCache;
5415
5718
  }
5719
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
5720
+ * stop for good, said once), false for a passing failure the caller reports */
5721
+ noteReconcileFailure(e) {
5722
+ if (!(e instanceof Error) || e.name !== "HostRouteUnusableError") return false;
5723
+ if (this.reconcileOff == null) {
5724
+ this.reconcileOff = e.message;
5725
+ this.stopWatchdog();
5726
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`);
5727
+ }
5728
+ return true;
5729
+ }
5730
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
5731
+ trackExecution(execution) {
5732
+ this.executions.set(execution.data.id, execution);
5733
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return;
5734
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs));
5735
+ this._watchdog.unref?.();
5736
+ }
5737
+ stopWatchdog() {
5738
+ if (this._watchdog != null) clearInterval(this._watchdog);
5739
+ this._watchdog = null;
5740
+ }
5741
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
5742
+ * quiet node: ask. A run queued behind a talking host is never asked about */
5743
+ watchdogTick() {
5744
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog();
5745
+ if (this._checking) return;
5746
+ const now = Date.now();
5747
+ const wait = this._silenceWaitMs ?? this.runSilenceMs;
5748
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return;
5749
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs);
5750
+ if (due.length === 0) return;
5751
+ this._checking = true;
5752
+ this.reconcileRuns(due, "silence").finally(() => {
5753
+ this._checking = false;
5754
+ this._lastCheckAt = Date.now();
5755
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs);
5756
+ });
5757
+ }
5758
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
5759
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
5760
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
5761
+ * the new socket of the same session. A clean close lets the server end that handler first */
5762
+ async reconcileRuns(runs, why) {
5763
+ if (this.reconcileOff != null) return;
5764
+ const todo = runs.filter((r) => !r.reconciling);
5765
+ if (todo.length === 0) return;
5766
+ for (const r of todo) r.beginReconcile(why);
5767
+ const queued = await this.fetchQueuedPromptIdsOrNull();
5768
+ if (this.reconcileOff != null) {
5769
+ for (const r of todo) r.reconciling = false;
5770
+ return;
5771
+ }
5772
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)));
5773
+ if (why === "silence" && verdicts.includes("history") && this.ws?.isOpen === true) {
5774
+ logError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`);
5775
+ this.ws.reconnect();
5776
+ }
5777
+ }
5416
5778
  /** method to either execute or buffer the incoming message */
5417
5779
  routeOrBuffer(prompt_id, msg) {
5418
5780
  this.activePromptID = prompt_id;
@@ -5474,6 +5836,7 @@ var ComfyHost = class {
5474
5836
  }
5475
5837
  onMessage(e) {
5476
5838
  this.lastWsMessageAt = Date.now();
5839
+ this._silenceWaitMs = null;
5477
5840
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
5478
5841
  if (e.data instanceof ArrayBuffer) {
5479
5842
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data);
@@ -5525,10 +5888,12 @@ var ComfyHost = class {
5525
5888
  if (msg.type === "status") {
5526
5889
  if (msg.data.sid) {
5527
5890
  const sidChanged = msg.data.sid !== this.comfySessionId;
5891
+ const socketIsNew = this._socketIsNew;
5892
+ this._socketIsNew = false;
5528
5893
  this.comfySessionId = msg.data.sid;
5529
5894
  this._sessionResolve?.();
5530
5895
  this._sessionResolve = null;
5531
- if (sidChanged) {
5896
+ if (sidChanged || socketIsNew) {
5532
5897
  this._unknownWsEventTypes.clear();
5533
5898
  this._unknownBinaryFrameTypes.clear();
5534
5899
  this.onSession?.(msg.data.sid);
@@ -6214,6 +6579,7 @@ var ComfyTS = class ComfyTS {
6214
6579
  const authed = (p) => p.apiKey != null ? " (authed)" : "";
6215
6580
  throw new Error(`host id '${data.id}' already registered ${cur == null ? "with no address" : `at ${renderHttpBase(cur)}`}${authed(existing.data)} — refusing ${incoming == null ? "the id alone" : renderHttpBase(incoming)}${authed(data)}`);
6216
6581
  }
6582
+ if (data.comfyOrgApiKey != null) existing.data.comfyOrgApiKey = data.comfyOrgApiKey;
6217
6583
  return existing;
6218
6584
  }
6219
6585
  const created = new ComfyHost(data);
@@ -6305,4 +6671,4 @@ function comfyTsPackageDir(moduleUrl = import.meta.url) {
6305
6671
  //#endregion
6306
6672
  export { readableStringify as a, renderHttpBase as c, settingsPathFor as i, comfyTsPackageDir as n, ComfySchema as o, ComfyTS as r, writeHostFile as s, bundledExamplesDir as t };
6307
6673
 
6308
- //# sourceMappingURL=exampleAssets-1NHndnNB.js.map
6674
+ //# sourceMappingURL=exampleAssets-DZynSkZm.js.map