comfy-ts 2.20.2 → 2.21.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 (31) hide show
  1. package/README.md +17 -1
  2. package/dist/{ServeApp-B469W26E.js → ServeApp-ByMobrWW.js} +3 -3
  3. package/dist/{ServeApp-B469W26E.js.map → ServeApp-ByMobrWW.js.map} +1 -1
  4. package/dist/cli.js +5 -5
  5. package/dist/{exampleAssets-yBLaKXLq.js → exampleAssets-B5sMqNia.js} +58 -3
  6. package/dist/exampleAssets-B5sMqNia.js.map +1 -0
  7. package/dist/{findDefinedWorkflow-B90-xFxX.js → findDefinedWorkflow-BNZgYIww.js} +2 -2
  8. package/dist/{findDefinedWorkflow-B90-xFxX.js.map → findDefinedWorkflow-BNZgYIww.js.map} +1 -1
  9. package/dist/index.cjs +87 -19
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +19 -3
  12. package/dist/index.d.ts +19 -3
  13. package/dist/index.js +87 -19
  14. package/dist/index.js.map +1 -1
  15. package/dist/{run-run-C-dDD9Dc.js → run-run-CuBSygku.js} +5 -5
  16. package/dist/{run-run-C-dDD9Dc.js.map → run-run-CuBSygku.js.map} +1 -1
  17. package/dist/{run-serve-CsEYPGm9.js → run-serve-COk_G0Qz.js} +4 -4
  18. package/dist/{run-serve-CsEYPGm9.js.map → run-serve-COk_G0Qz.js.map} +1 -1
  19. package/dist/{run-tui-bsmja4hi.js → run-tui-CB6i_x2y.js} +4 -4
  20. package/dist/{run-tui-bsmja4hi.js.map → run-tui-CB6i_x2y.js.map} +1 -1
  21. package/dist/{schemaDrift-DaWsE-mt.js → schemaDrift-CHDVYlaj.js} +32 -19
  22. package/dist/{schemaDrift-DaWsE-mt.js.map → schemaDrift-CHDVYlaj.js.map} +1 -1
  23. package/dist/web.d.ts +19 -3
  24. package/dist/web.js +87 -19
  25. package/dist/web.js.map +1 -1
  26. package/package.json +1 -1
  27. package/src/host/ComfyHost.ts +21 -0
  28. package/src/host/leastBusy.ts +37 -0
  29. package/src/state.ts +6 -0
  30. package/src/vars/DefinedWorkflow.ts +38 -21
  31. package/dist/exampleAssets-yBLaKXLq.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "2.20.2",
3
+ "version": "2.21.0",
4
4
  "description": "An efficient way to create, run, maintain and operate your ComfyUI workflows, for humans and agents. A TypeScript SDK typed from your own install, with a CLI, a terminal UI, a web panel and a guide for coding agents.",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -685,6 +685,19 @@ export class ComfyHost<ID extends string = string> {
685
685
  return previewMethodFromSystemStats(await res.json())
686
686
  }
687
687
 
688
+ /** jobs waiting or running on this host, every client counted (`GET /prompt`) */
689
+ fetchQueueSize = async (p: { timeoutMs?: number } = {}): Promise<number> => {
690
+ const res = await this.fetch('/prompt', { signal: AbortSignal.timeout(p.timeoutMs ?? 3000) })
691
+ if (!res.ok) throw new Error(`GET /prompt failed: ${res.status}`)
692
+ const size = queueRemainingOf(await res.json())
693
+ if (size == null) throw new Error(`GET /prompt: no exec_info.queue_remaining in the reply`)
694
+ return size
695
+ }
696
+
697
+ /** runs started through DefinedWorkflow.run() and not finished yet: counted from the call,
698
+ * before the prompt reaches the server queue, so runs started together spread out */
699
+ runsInFlight = 0
700
+
688
701
  /** the server's recent console buffer (entries are write CHUNKS, not lines) */
689
702
  fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {
690
703
  const res = await this.fetch('/internal/logs/raw', {}, { apiPrefix: false })
@@ -1011,3 +1024,11 @@ export class ComfyHost<ID extends string = string> {
1011
1024
  exhaust(msg)
1012
1025
  }
1013
1026
  }
1027
+
1028
+ /** `exec_info.queue_remaining` of a `GET /prompt` reply, null when the shape is not there */
1029
+ function queueRemainingOf(json: unknown): number | null {
1030
+ if (typeof json !== 'object' || json == null || !('exec_info' in json)) return null
1031
+ const info = json.exec_info
1032
+ if (typeof info !== 'object' || info == null || !('queue_remaining' in info)) return null
1033
+ return typeof info.queue_remaining === 'number' ? info.queue_remaining : null
1034
+ }
@@ -0,0 +1,37 @@
1
+ import type { ComfyHost } from 'src/host/ComfyHost.ts'
2
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
3
+
4
+ /**
5
+ * the host with the shortest queue. Score = max(server queue, our runs in flight there):
6
+ * the server counts every client, the local count sees runs not posted yet.
7
+ * Ties go to the first host listed; a host that does not answer is skipped, all down throws.
8
+ */
9
+ export async function leastBusy<H extends ComfyHost<string>>(
10
+ hosts: readonly H[],
11
+ p: { timeoutMs?: number } = {},
12
+ ): Promise<H> {
13
+ if (hosts.length === 0) throw new Error('leastBusy: no host given')
14
+ const probes = await Promise.all(
15
+ hosts.map(async (host) => {
16
+ try {
17
+ const queue = await host.fetchQueueSize({ timeoutMs: p.timeoutMs })
18
+ return { host, score: Math.max(queue, host.runsInFlight), error: null }
19
+ } catch (err) {
20
+ return { host, score: Infinity, error: extractErrorMessage(err) }
21
+ }
22
+ }),
23
+ )
24
+ let best: (typeof probes)[number] | null = null
25
+ for (const probe of probes) {
26
+ if (probe.error != null) {
27
+ console.warn(`🟡 leastBusy: host '${probe.host.data.id}' skipped: ${probe.error}`)
28
+ continue
29
+ }
30
+ if (best == null || probe.score < best.score) best = probe
31
+ }
32
+ if (best == null)
33
+ throw new Error(
34
+ `🔴 leastBusy: no host answered (${probes.map((x) => `'${x.host.data.id}': ${x.error}`).join(', ')})`,
35
+ )
36
+ return best.host
37
+ }
package/src/state.ts CHANGED
@@ -3,6 +3,7 @@ import pkgJson from '../package.json' with { type: 'json' }
3
3
  import { ComfyHost, type ComfyHostData } from 'src/host/ComfyHost.ts'
4
4
  import { namesNoAddress } from 'src/host/hostFile.ts'
5
5
  import { parseHostBase, renderHttpBase } from 'src/host/hostUrl.ts'
6
+ import { leastBusy } from 'src/host/leastBusy.ts'
6
7
  import { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
7
8
  import { type ComfyStorage, resolveComfyStorage } from 'src/storage/ComfyStorage.ts'
8
9
  import { type AbsolutePath, asAbsolutePath, type RelativePath } from 'src/types/index.ts'
@@ -82,6 +83,11 @@ export class ComfyTS {
82
83
  return created
83
84
  }
84
85
 
86
+ /** the host with the shortest queue, for `wf.run({ host: await comfy.leastBusy([a, b]) })` */
87
+ leastBusy<H extends ComfyHost<string>>(hosts: readonly H[], p: { timeoutMs?: number } = {}): Promise<H> {
88
+ return leastBusy(hosts, p)
89
+ }
90
+
85
91
  /**
86
92
  * A ComfyRegistry instance that provides access to all
87
93
  * known Comfy nodes, models, plugins, ...
@@ -158,36 +158,53 @@ export class DefinedWorkflow<ID extends string = string, V extends VarsSpec = Va
158
158
  * the graph is built against (TUI host override): node/model availability
159
159
  * there surfaces as workflow.problems / server validation, by design.
160
160
  * `p.dry` builds a graph only to read it: nothing is uploaded, lastWorkflow is left alone.
161
+ * `p.values` builds from a snapshot taken earlier (run() takes it at the call).
161
162
  */
162
- async build(p: { advance?: boolean; host?: ComfyHost<ID>; dry?: boolean } = {}): Promise<ComfyWorkflow<ID>> {
163
- const host = p.host ?? this.host
164
- const wf = host.workflow({ id: this.spec.id })
163
+ async build(
164
+ p: { advance?: boolean; host?: ComfyHost; dry?: boolean; values?: VarValues<V> } = {},
165
+ ): Promise<ComfyWorkflow<ID>> {
166
+ const host: ComfyHost = p.host ?? this.host
167
+ // cast: whitelist item 1 (agent/coding.md): another host's graph claimed as this host's
168
+ const wf = host.workflow({ id: this.spec.id }) as ComfyWorkflow<ID>
165
169
  wf.dry = p.dry === true
166
- const values = varValues(this.vars)
167
- if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun()
170
+ const values = p.values ?? this.snapshot({ advance: p.advance === true })
168
171
  await this.spec.build(wf.builder, values, wf)
169
172
  if (wf.dry) return wf
170
173
  this.lastWorkflow = wf
171
174
  return wf
172
175
  }
173
176
 
174
- /** build a fresh graph from the current var values, send it, wait for outputs.
177
+ /** the current var values; `advance` then moves each var to its next run (the seed) */
178
+ private snapshot(p: { advance: boolean }): VarValues<V> {
179
+ const values = varValues(this.vars)
180
+ if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun()
181
+ return values
182
+ }
183
+
184
+ /** build a fresh graph from the var values AT THE CALL, send it, wait for outputs:
185
+ * set a var, call run(), set it again, and each run keeps its own values.
175
186
  * connects first (idempotent) — modules can import offline from the schema cache.
176
187
  * `settings.host` runs against THAT host instead of the defining one. */
177
- async run(settings: RunSettings & { host?: ComfyHost<ID> } = {}): Promise<ComfyExecution> {
178
- const host = settings.host ?? this.host
179
- await host.connect()
180
- const wf = await this.build({ advance: true, host })
181
- const execution = await wf.run({
182
- save: settings.save,
183
- ephemeral: settings.ephemeral,
184
- scrubHistory: settings.scrubHistory,
185
- idMode: settings.idMode,
186
- log: settings.log,
187
- onProgress: settings.onProgress,
188
- onPreview: settings.onPreview,
189
- })
190
- this.lastExecution = execution
191
- return execution
188
+ async run(settings: RunSettings & { host?: ComfyHost } = {}): Promise<ComfyExecution> {
189
+ const host: ComfyHost = settings.host ?? this.host
190
+ const values = this.snapshot({ advance: true })
191
+ host.runsInFlight++
192
+ try {
193
+ await host.connect()
194
+ const wf = await this.build({ host, values })
195
+ const execution = await wf.run({
196
+ save: settings.save,
197
+ ephemeral: settings.ephemeral,
198
+ scrubHistory: settings.scrubHistory,
199
+ idMode: settings.idMode,
200
+ log: settings.log,
201
+ onProgress: settings.onProgress,
202
+ onPreview: settings.onPreview,
203
+ })
204
+ this.lastExecution = execution
205
+ return execution
206
+ } finally {
207
+ host.runsInFlight--
208
+ }
192
209
  }
193
210
  }