comfy-ts 2.1.0 → 2.2.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 (41) hide show
  1. package/README.md +65 -225
  2. package/dist/{DefinedWorkflow-CqNE_kgR.js → DefinedWorkflow-CwHInZgn.js} +4 -3
  3. package/dist/DefinedWorkflow-CwHInZgn.js.map +1 -0
  4. package/dist/{DraftsSt-C-gBk9v7.js → DraftsSt-omWuBSej.js} +2 -2
  5. package/dist/{DraftsSt-C-gBk9v7.js.map → DraftsSt-omWuBSej.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +22 -5
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +12 -2
  10. package/dist/index.d.ts +12 -2
  11. package/dist/index.js +22 -5
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-CnlN_RFH.js → run-serve-C1oo5ilG.js} +170 -126
  14. package/dist/run-serve-C1oo5ilG.js.map +1 -0
  15. package/dist/{run-tui-DXI_Jufu.js → run-tui-CuVst-nc.js} +49 -50
  16. package/dist/run-tui-CuVst-nc.js.map +1 -0
  17. package/dist/{state-DC5BcG6d.js → state-CvMt0W1-.js} +23 -7
  18. package/dist/state-CvMt0W1-.js.map +1 -0
  19. package/dist/web.d.ts +12 -2
  20. package/dist/web.js +22 -5
  21. package/dist/web.js.map +1 -1
  22. package/examples/README.md +6 -18
  23. package/examples/images/README.md +2 -6
  24. package/guide-for-agents.md +25 -84
  25. package/package.json +1 -1
  26. package/src/cli/serve/ServeApp.ts +17 -11
  27. package/src/cli/serve/applyVarPayload.ts +91 -71
  28. package/src/cli/serve/describeVar.ts +57 -28
  29. package/src/cli/tui/components/StatusBar.tsx +1 -0
  30. package/src/cli/tui/components/TextOverlay.tsx +7 -3
  31. package/src/cli/tui/components/VarsPanel.tsx +2 -2
  32. package/src/cli/tui/state/ExecSt.ts +47 -52
  33. package/src/cli/tui/state/TuiSt.ts +11 -6
  34. package/src/host/ComfyHost.ts +5 -1
  35. package/src/runner/ComfyExecution.ts +15 -7
  36. package/src/runner/outputPath.ts +11 -0
  37. package/src/vars/ComfyVars.ts +12 -2
  38. package/dist/DefinedWorkflow-CqNE_kgR.js.map +0 -1
  39. package/dist/run-serve-CnlN_RFH.js.map +0 -1
  40. package/dist/run-tui-DXI_Jufu.js.map +0 -1
  41. package/dist/state-DC5BcG6d.js.map +0 -1
@@ -63,8 +63,8 @@ const VarRow = observer(
63
63
  <Text color="cyan" wrap="truncate">
64
64
  {value.replaceAll('\n', ' ')}
65
65
  </Text>
66
- ) : p.varDef instanceof PromptVar ? (
67
- <PromptCell varDef={p.varDef} value={value} />
66
+ ) : p.varDef.kind === 'prompt' ? (
67
+ <PromptCell varDef={p.varDef as PromptVar} value={value} />
68
68
  ) : (
69
69
  <Text color="cyan" wrap="wrap">
70
70
  {value}
@@ -7,6 +7,7 @@ import type { ComfyHost } from 'src/host/ComfyHost.ts'
7
7
  import type { ExecutionProgress } from 'src/runner/ComfyExecution.ts'
8
8
  import { imageClipboardCommand, imageClipboardStdinCommand } from 'src/cli/tui/imageClipboard.ts'
9
9
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
10
+ import { importSharp } from 'src/utils/lazySharp.ts'
10
11
  import type { SeedVar } from 'src/vars/ComfyVars.ts'
11
12
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
12
13
  import type { MediaImage } from 'src/runner/MediaImage.ts'
@@ -192,6 +193,10 @@ export class ExecSt {
192
193
  this.st.mode = 'nav'
193
194
  }
194
195
 
196
+ /** makeAutoObservable already annotates this method as an action, so the
197
+ * post-await callers below need no runInAction of their own (verified
198
+ * against mobx: a TS-private prototype method called after an `await`
199
+ * opens its own action context; only a CONSTRUCTOR body does not) */
195
200
  private showCopyPopup(title: string, ok: boolean, lines: string[]): void {
196
201
  // the build is async: if the user moved into an editor meanwhile, never
197
202
  // steal their keys — degrade to the notice line instead of a popup
@@ -253,19 +258,17 @@ export class ExecSt {
253
258
  proc.on('error', () => resolve(false))
254
259
  proc.on('close', (code) => resolve(code === 0))
255
260
  }))
256
- runInAction(() => {
257
- this.showCopyPopup(
258
- 'image → clipboard',
259
- ok,
260
- ok
261
- ? [`${basename(file)} — paste the pixels anywhere`, '', `via fallback file ${file}`]
262
- : [`COPY FAILED for ${lastImg.filename}`, `could not run ${piped.cmd} — is it installed and allowed ?`],
263
- )
264
- })
261
+ this.showCopyPopup(
262
+ 'image → clipboard',
263
+ ok,
264
+ ok
265
+ ? [`${basename(file)} — paste the pixels anywhere`, '', `via fallback file ${file}`]
266
+ : [`COPY FAILED for ${lastImg.filename}`, `could not run ${piped.cmd} — is it installed and allowed ?`],
267
+ )
265
268
  }
266
269
 
267
270
  private async toPngBytes(bytes: Uint8Array): Promise<Uint8Array> {
268
- const { default: sharp } = await import('sharp')
271
+ const sharp = await importSharp('the clipboard png normalize')
269
272
  return new Uint8Array(await sharp(bytes).png().toBuffer())
270
273
  }
271
274
 
@@ -310,28 +313,24 @@ export class ExecSt {
310
313
  const json = await wf.toWorkflowJson()
311
314
  const text = JSON.stringify(json, null, 2)
312
315
  const ok = await this.toClipboard(text)
313
- runInAction(() => {
314
- this.showCopyPopup(
315
- 'workflow.json → clipboard',
316
- ok,
317
- ok
318
- ? [
319
- `${json.nodes.length} nodes · ${text.length} chars — paste into the ComfyUI editor`,
320
- '',
321
- ...jsonHead(text, 10),
322
- ]
323
- : ['CLIPBOARD COPY FAILED — is a clipboard tool available (pbcopy/clip/xclip) ?'],
324
- )
325
- })
316
+ this.showCopyPopup(
317
+ 'workflow.json → clipboard',
318
+ ok,
319
+ ok
320
+ ? [
321
+ `${json.nodes.length} nodes · ${text.length} chars — paste into the ComfyUI editor`,
322
+ '',
323
+ ...jsonHead(text, 10),
324
+ ]
325
+ : ['CLIPBOARD COPY FAILED — is a clipboard tool available (pbcopy/clip/xclip) ?'],
326
+ )
326
327
  } catch (e) {
327
- runInAction(() => {
328
- this.showCopyPopup('workflow.json copy FAILED', false, [
329
- extractErrorMessage(e),
330
- '',
331
- 'nothing was copied. i2i/i2v builds upload their input image first —',
332
- 'an unreachable host fails the build itself, not just the run.',
333
- ])
334
- })
328
+ this.showCopyPopup('workflow.json copy FAILED', false, [
329
+ extractErrorMessage(e),
330
+ '',
331
+ 'nothing was copied. i2i/i2v builds upload their input image first —',
332
+ 'an unreachable host fails the build itself, not just the run.',
333
+ ])
335
334
  } finally {
336
335
  runInAction(() => {
337
336
  this.copying = false
@@ -351,28 +350,24 @@ export class ExecSt {
351
350
  const json = wf.toApiJson('use_stringified_numbers_only')
352
351
  const text = JSON.stringify(json, null, 2)
353
352
  const ok = await this.toClipboard(text)
354
- runInAction(() => {
355
- this.showCopyPopup(
356
- 'api.json → clipboard',
357
- ok,
358
- ok
359
- ? [
360
- `${Object.keys(json).length} nodes · ${text.length} chars — the POST /prompt payload`,
361
- '',
362
- ...jsonHead(text, 10),
363
- ]
364
- : ['CLIPBOARD COPY FAILED — is a clipboard tool available (pbcopy/clip/xclip) ?'],
365
- )
366
- })
353
+ this.showCopyPopup(
354
+ 'api.json → clipboard',
355
+ ok,
356
+ ok
357
+ ? [
358
+ `${Object.keys(json).length} nodes · ${text.length} chars — the POST /prompt payload`,
359
+ '',
360
+ ...jsonHead(text, 10),
361
+ ]
362
+ : ['CLIPBOARD COPY FAILED — is a clipboard tool available (pbcopy/clip/xclip) ?'],
363
+ )
367
364
  } catch (e) {
368
- runInAction(() => {
369
- this.showCopyPopup('api.json copy FAILED', false, [
370
- extractErrorMessage(e),
371
- '',
372
- 'nothing was copied. i2i/i2v builds upload their input image first —',
373
- 'an unreachable host fails the build itself, not just the run.',
374
- ])
375
- })
365
+ this.showCopyPopup('api.json copy FAILED', false, [
366
+ extractErrorMessage(e),
367
+ '',
368
+ 'nothing was copied. i2i/i2v builds upload their input image first —',
369
+ 'an unreachable host fails the build itself, not just the run.',
370
+ ])
376
371
  } finally {
377
372
  runInAction(() => {
378
373
  this.copying = false
@@ -147,11 +147,16 @@ export class TuiSt {
147
147
  // starts unfolded so its drafts are visible in the tree
148
148
  this.drafts.activateRemembered()
149
149
  if (opts.currentFile != null) {
150
- this.tree.expandedFiles.add(opts.currentFile)
151
- // the first module loads in run-tui, BEFORE WorkflowsSt.load can record it
152
- this.workflows.recordSpecColor(opts.currentFile, wf)
153
- // whatever is on screen is what a no-arg reopen returns to
154
- this.settings.lastWorkflow = opts.currentFile
150
+ const currentFile = opts.currentFile
151
+ // settings.lastWorkflow is OBSERVED (SettingsSt's own persist reaction),
152
+ // so this constructor tail is a mobx action or it warns on every open
153
+ runInAction(() => {
154
+ this.tree.expandedFiles.add(currentFile)
155
+ // the first module loads in run-tui, BEFORE WorkflowsSt.load can record it
156
+ this.workflows.recordSpecColor(currentFile, wf)
157
+ // whatever is on screen is what a no-arg reopen returns to
158
+ this.settings.lastWorkflow = currentFile
159
+ })
155
160
  }
156
161
  // full-terminal layout: track resizes (SIGWINCH surfaces as stdout resize)
157
162
  const onResize = (): void => {
@@ -297,7 +302,7 @@ export class TuiSt {
297
302
  const sel = this.selected?.[1]
298
303
  if (sel == null) return
299
304
  if (sel.kind === 'toggle') (sel as ToggleVar).toggle()
300
- else if (sel.kind === 'text') this.editor.beginMultiline()
305
+ else if (sel.kind === 'text' || sel.kind === 'prompt') this.editor.beginMultiline()
301
306
  else if (sel.kind === 'choice') this.picker.beginChoice()
302
307
  else if (sel.kind === 'size') this.picker.beginSize()
303
308
  else if (sel.kind === 'loras') this.loras.begin()
@@ -764,7 +764,11 @@ export class ComfyHost<ID extends string = string> {
764
764
  const pending = this._pendingMsgs.get(this.activePromptID)
765
765
  if (pending != null) pending.push({ type: 'binary_preview_frame', bytes: frame.bytes, mime: frame.mime })
766
766
  }
767
- // type 1 AND the cloud's type 4 (preview + metadata) feed the same hook
767
+ // type 1 AND the cloud's type 4 (preview + metadata) feed the same hook.
768
+ // The object url REGISTRY holds a strong ref to its blob until it is
769
+ // revoked (node and browsers alike), and a sampler emits one frame per
770
+ // step: revoke the outgoing one or a long session retains every latent
771
+ if (this.latentPreview != null) URL.revokeObjectURL(this.latentPreview.url)
768
772
  const imageBlob = new Blob([frame.bytes], { type: frame.mime })
769
773
  this.latentPreview = {
770
774
  blob: imageBlob,
@@ -1,9 +1,5 @@
1
- import { localOutputPath, runTimestamp, uniquifyOutputPath } from 'src/runner/outputPath.ts'
2
-
3
- /** paths claimed by in-flight retrievals: two same-second runs on a
4
- * counter-resetting cloud host compute the same name before either writes */
5
- const CLAIMED_OUTPUT_PATHS = new Set<string>()
6
1
  import type { FormatEnum } from 'sharp'
2
+ import { localOutputPath, runTimestamp, uniquifyOutputPath, withExtension } from 'src/runner/outputPath.ts'
7
3
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
8
4
  import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
9
5
  import { importSharp } from 'src/utils/lazySharp.ts'
@@ -26,6 +22,12 @@ import type {
26
22
  } from 'src/runner/ComfyWsApi.ts'
27
23
  import { MediaImage } from 'src/runner/MediaImage.ts'
28
24
 
25
+ /** paths claimed by in-flight retrievals: two same-second runs on a
26
+ * counter-resetting cloud host compute the same name before either writes.
27
+ * A claim is released as soon as the write lands (the file itself then holds
28
+ * the name) or fails (the name is free again) — the set never accumulates */
29
+ const CLAIMED_OUTPUT_PATHS = new Set<string>()
30
+
29
31
  export type ComfyExecutionData = {
30
32
  id: PromptID
31
33
  graphID: ComfyWorkflowID
@@ -303,12 +305,18 @@ export class ComfyExecution {
303
305
  timestamp: runTimestamp(new Date(this.startedAt)),
304
306
  }),
305
307
  )
306
- if (reencode) absPath += '.' + bang(p.sf.format).split('/')[1]
308
+ if (reencode) absPath = withExtension(absPath, bang(bang(p.sf.format).split('/')[1]))
307
309
  // last-resort uniquifier: bump past files on disk AND paths claimed by
308
310
  // still-downloading retrievals — never overwrite
309
311
  const storage = getComfyStorage()
310
312
  absPath = uniquifyOutputPath({ path: absPath, exists: (x) => storage.exists(x), claimed: CLAIMED_OUTPUT_PATHS })
311
- storage.writeBytes(asAbsolutePath(absPath), bytes)
313
+ try {
314
+ storage.writeBytes(asAbsolutePath(absPath), bytes)
315
+ } finally {
316
+ // the file (or the failure) now owns the name — holding the claim
317
+ // forever would grow the set for the whole life of a `serve` process
318
+ CLAIMED_OUTPUT_PATHS.delete(absPath)
319
+ }
312
320
  return { path: asAbsolutePath(absPath), bytes }
313
321
  }
314
322
 
@@ -46,6 +46,17 @@ export const localOutputPath = (p: {
46
46
  return dir === '' ? name : `${dir}/${name}`
47
47
  }
48
48
 
49
+ /** REPLACE the extension (never append one): a re-encoded save owns its whole
50
+ * name now that local naming is ours, so `save: {format:'image/webp'}` writes
51
+ * `shot_20260731-154210_00001.webp`, not `…_00001.png.webp` — appending
52
+ * described the bytes twice and the first description was a lie */
53
+ export const withExtension = (path: string, ext: string): string => {
54
+ const slash = path.lastIndexOf('/')
55
+ const dot = path.lastIndexOf('.')
56
+ const stem = dot > slash ? path.slice(0, dot) : path
57
+ return `${stem}.${ext}`
58
+ }
59
+
49
60
  /**
50
61
  * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR
51
62
  * was already CLAIMED by a still-downloading retrieval (two same-second runs
@@ -7,7 +7,15 @@ import { basename, isAbsolute, join, resolve } from 'pathe'
7
7
  import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
8
8
  import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
9
9
 
10
- export type VarKind = 'text' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size' | 'image'
10
+ /**
11
+ * the var's CLASS, and the only safe way to discriminate one: `instanceof` compares class
12
+ * OBJECTS, and the published package hands the same class out twice — a consumer's
13
+ * `.cflow.ts` imports `comfy-ts` (dist/index.js) while `comfy-ts serve`/`tui` run from the
14
+ * cli bundle, so every `instanceof XVar` across that boundary is false (his repro
15
+ * 2026-07-31: "var 'prompt' has unsupported kind 'text'" for EVERY kind). A string tag
16
+ * crosses bundles; a class identity does not.
17
+ */
18
+ export type VarKind = 'text' | 'prompt' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size' | 'image'
11
19
 
12
20
  /**
13
21
  * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
@@ -101,7 +109,7 @@ export type PromptValue = { positive: string; negative: string }
101
109
  * `injectedKeywords()` is public so the TUI can PREVIEW the injection.
102
110
  */
103
111
  export class PromptVar extends ComfyVarBase<string, PromptValue> {
104
- readonly kind = 'text' as const
112
+ readonly kind = 'prompt' as const
105
113
  constructor(
106
114
  defaultValue: string,
107
115
  public promptOpts: { label?: string; loraKeywordsFrom?: ActiveLoraSource } = {},
@@ -516,6 +524,8 @@ export const DEFAULT_IMAGE_EXTENSIONS: readonly string[] = ['png', 'jpg', 'jpeg'
516
524
 
517
525
  /** empty image var consumed at build time — typed so drivers surface it apart from real crashes */
518
526
  export class ImageVarEmptyError extends Error {
527
+ /** name, not instanceof: the cli bundle and dist/index.js each define this class */
528
+ override readonly name = 'ImageVarEmptyError'
519
529
  constructor(public readonly varName: string) {
520
530
  super(`image var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/image.png'))`)
521
531
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"DefinedWorkflow-CqNE_kgR.js","names":["g"],"sources":["../src/utils/log.ts","../src/storage/ComfyStorage.ts","../src/utils/extractErrorMessage.ts","../src/vars/loraKeywords.ts","../src/vars/ComfyVars.ts","../src/vars/DefinedWorkflow.ts"],"sourcesContent":["// loud console logging; errors must be observable to human AND LLM.\n// COMFY_TS_QUIET=1 (set by drivers like the TUI) silences INFO chatter only —\n// errors always print.\nexport const isQuiet = (): boolean => process.env.COMFY_TS_QUIET === '1'\nexport const logInfo = (msg: string): void => {\n if (!isQuiet()) console.log(msg)\n}\nexport const logError = (msg: string): void => console.error(`[comfy-ts] 🔴 ${msg}`)\nexport const logSuccess = (msg: string): void => console.log(`[comfy-ts] 🟢 ${msg}`)\n","// the storage seam (architecture item 13): ONE sync fs-subset interface the\n// core path talks to. Node gets the real fs, the web entry an in-memory Map.\n// This file must stay browser-safe: no node imports, ever.\n\nexport type ComfyStorage = {\n /** backend name, for error messages */\n kind: string\n /** throws when missing */\n readText(path: string): string\n readTextIfExists(path: string): string | null\n /** throws when missing */\n readBytes(path: string): Uint8Array\n /** parents are created (mkdirp implied) */\n writeText(path: string, text: string): void\n /** parents are created (mkdirp implied) */\n writeBytes(path: string, bytes: Uint8Array): void\n exists(path: string): boolean\n mkdirp(path: string): void\n /** file mtime in ms; null when missing */\n mtimeMs(path: string): number | null\n homedir(): string\n cwd(): string\n}\n\n/** the fs/os surface createNodeStorageFrom needs — structural, so this file\n * never imports node types into the web graph */\nexport type NodeFsLike = {\n readFileSync(path: string, encoding?: 'utf8'): string | Uint8Array\n writeFileSync(path: string, data: string | Uint8Array): void\n existsSync(path: string): boolean\n mkdirSync(path: string, opts: { recursive: boolean }): unknown\n statSync(path: string): { mtimeMs: number; isFile(): boolean }\n}\nexport type NodeOsLike = { homedir(): string }\n\nfunction dirnameOf(path: string): string {\n const ix = path.lastIndexOf('/')\n return ix <= 0 ? '/' : path.slice(0, ix)\n}\n\n/** node backend built from INJECTED modules: nodeStorage.ts passes its static\n * imports, the autodetect below passes process.getBuiltinModule results */\nexport function createNodeStorageFrom(fs: NodeFsLike, os: NodeOsLike): ComfyStorage {\n return {\n kind: 'node',\n readText: (p) => fs.readFileSync(p, 'utf8') as string,\n readTextIfExists: (p) => (fs.existsSync(p) ? (fs.readFileSync(p, 'utf8') as string) : null),\n readBytes: (p) => new Uint8Array(fs.readFileSync(p) as Uint8Array),\n writeText: (p, text) => {\n fs.mkdirSync(dirnameOf(p), { recursive: true })\n fs.writeFileSync(p, text)\n },\n writeBytes: (p, bytes) => {\n fs.mkdirSync(dirnameOf(p), { recursive: true })\n fs.writeFileSync(p, bytes)\n },\n exists: (p) => fs.existsSync(p),\n mkdirp: (p) => void fs.mkdirSync(p, { recursive: true }),\n mtimeMs: (p) => (fs.existsSync(p) ? fs.statSync(p).mtimeMs : null),\n homedir: () => os.homedir(),\n cwd: () => process.cwd(),\n }\n}\n\n/** in-memory backend: the web default, also handy for hermetic tests.\n * Paths are LITERAL keys (no normalization — core callers resolve through\n * pathe/comfyts already). exists() knows written files and EXPLICIT mkdirp\n * dirs only, never implicit parents. Bytes are copied in AND out so neither\n * side can mutate the store. */\nexport function createMemoryStorage(p: { homedir?: string; cwd?: string } = {}): ComfyStorage {\n const files = new Map<string, Uint8Array>()\n const mtimes = new Map<string, number>()\n const dirs = new Set<string>()\n const td = new TextDecoder()\n const te = new TextEncoder()\n const write = (path: string, bytes: Uint8Array): void => {\n files.set(path, bytes.slice())\n mtimes.set(path, Date.now())\n }\n return {\n kind: 'memory',\n readText: (path) => {\n const hit = files.get(path)\n if (hit == null) throw new Error(`[memory storage] no such file: ${path}`)\n return td.decode(hit)\n },\n readTextIfExists: (path) => {\n const hit = files.get(path)\n return hit == null ? null : td.decode(hit)\n },\n readBytes: (path) => {\n const hit = files.get(path)\n if (hit == null) throw new Error(`[memory storage] no such file: ${path}`)\n return hit.slice()\n },\n writeText: (path, text) => write(path, te.encode(text)),\n writeBytes: write,\n exists: (path) => files.has(path) || dirs.has(path),\n mkdirp: (path) => void dirs.add(path),\n mtimeMs: (path) => mtimes.get(path) ?? null,\n homedir: () => p.homedir ?? '/home/web',\n cwd: () => p.cwd ?? '/',\n }\n}\n\n// ---- default resolution (architecture item 13) ------------------------------\n// explicit ComfyTS.create({storage}) → entry-installed default → node builtins\n// autodetect (node 22+/bun: no static import needed) → loud throw.\n\nlet installedDefault: ComfyStorage | null = null\n\n/** entries call this at import time: index.ts installs node, web.ts memory */\nexport function setDefaultComfyStorage(storage: ComfyStorage): void {\n installedDefault = storage\n}\n\nfunction autodetectNodeStorage(): ComfyStorage | null {\n const get = globalThis.process?.getBuiltinModule\n if (typeof get !== 'function') return null\n const fs = get('node:fs') as NodeFsLike | undefined\n const os = get('node:os') as NodeOsLike | undefined\n if (fs == null || os == null) return null\n return createNodeStorageFrom(fs, os)\n}\n\nexport function resolveComfyStorage(explicit?: ComfyStorage): ComfyStorage {\n if (explicit != null) return explicit\n if (installedDefault != null) return installedDefault\n const detected = autodetectNodeStorage()\n if (detected != null) {\n installedDefault = detected\n return detected\n }\n throw new Error(\n `no ComfyStorage available — import 'comfy-ts' (node) or 'comfy-ts/web' (browser) before creating ComfyTS, or pass ComfyTS.create({ storage })`,\n )\n}\n\n/** the ONE accessor call sites use: the instance's storage when the global\n * exists, the resolved default otherwise (vars constructed before create()) */\nexport function getComfyStorage(): ComfyStorage {\n const g = globalThis as { comfyts?: { storage?: ComfyStorage } }\n return g.comfyts?.storage ?? resolveComfyStorage()\n}\n","/** Extracts an error message from an exception stuff. */\nexport const extractErrorMessage = (error: unknown): string => {\n if (error instanceof Error) return error.message\n if (error === null) return 'null'\n if (typeof error === 'string') return error\n if (typeof error === 'object') {\n if ('message' in error && typeof error.message === 'string') return error.message\n return JSON.stringify(error)\n }\n return String(error)\n}\n","import { observable, runInAction } from 'mobx'\nimport { join } from 'pathe'\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { logError } from 'src/utils/log.ts'\n\n/**\n * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras\n * overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at\n * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data\n * and must survive a cache wipe). Observable map: overlay rows re-render on\n * assignment. Keys are the RAW lora names (folder/file.safetensors).\n */\nconst keywords = observable.map<string, string>()\nlet loaded = false\n\nfunction filePath(): string {\n return join(comfyts.baseFolder, 'lora-keywords.json')\n}\n\nfunction loadOnce(): void {\n if (loaded) return\n loaded = true\n const path = filePath()\n const text = getComfyStorage().readTextIfExists(path)\n if (text == null) return\n try {\n const raw: unknown = JSON.parse(text)\n if (raw == null || typeof raw !== 'object') return\n runInAction(() => {\n for (const [name, kw] of Object.entries(raw)) if (typeof kw === 'string') keywords.set(name, kw)\n })\n } catch (e) {\n logError(`[loraKeywords] unreadable ${path}: ${String(e)}`)\n }\n}\n\nexport function getLoraKeyword(name: string): string {\n loadOnce()\n return keywords.get(name) ?? ''\n}\n\n/** empty keyword deletes the entry; every set writes the file (tiny, rare) */\nexport function setLoraKeyword(name: string, keyword: string): void {\n loadOnce()\n const trimmed = keyword.trim()\n runInAction(() => {\n if (trimmed === '') keywords.delete(name)\n else keywords.set(name, trimmed)\n })\n const path = filePath()\n try {\n getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2))\n } catch (e) {\n logError(`[loraKeywords] write failed ${path}: ${String(e)}`)\n }\n}\n","// Vars: the standard \"tweak & re-run\" contract. A workflow defined via\n// host.defineWorkflow({ vars, build }) rebuilds its graph from current var\n// values on every run — drivers (scripts, the TUI) edit vars between runs.\nimport { imageMeta } from 'image-meta'\nimport { action, makeObservable, observable } from 'mobx'\nimport { basename, isAbsolute, join, resolve } from 'pathe'\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { getLoraKeyword } from 'src/vars/loraKeywords.ts'\n\nexport type VarKind = 'text' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size' | 'image'\n\n/**\n * full base: T is what's STORED/edited, Out what the GRAPH consumes at build\n * time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is\n * the one Out-specialized var (string in, PromptValue out); the split keeps\n * outValue() cast-free.\n */\nexport abstract class ComfyVarBase<T, Out> {\n abstract readonly kind: VarKind\n /** the vars-spec key, stamped by DefinedWorkflow at define time — error messages name the var with it */\n name?: string\n value: T\n constructor(\n public readonly defaultValue: T,\n public label?: string,\n ) {\n this.value = defaultValue\n // observable value: the TUI (mobx) re-renders when drivers mutate vars.\n // explicit makeObservable (not makeAutoObservable): base-class + subclass\n // combo. All mutators funnel through set()/reset()/parse() so they are\n // actions — subclass helpers call this.set(...) rather than assigning.\n makeObservable(this, { value: observable, set: action, reset: action, parse: action, loadJSON: action })\n }\n set(value: T): this {\n this.value = value\n return this\n }\n /** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */\n toJSON(): unknown {\n return this.value\n }\n /** what the GRAPH consumes at build time (varValues maps these return types) */\n abstract outValue(): Out\n /**\n * restore a value produced by toJSON() (drafts). The cast is sanctioned:\n * drafts are our own round-trip, subclasses re-validate via set().\n */\n loadJSON(value: unknown): this {\n return this.set(value as T)\n }\n reset(): this {\n this.value = this.defaultValue\n return this\n }\n /** parse a raw string (TUI text input) into this var's value; returns false when invalid */\n abstract parse(raw: string): boolean\n /** how the value renders in a var list */\n display(): string {\n return String(this.value)\n }\n /** the string the inline editor starts from (round-trips through parse) */\n toEditBuffer(): string {\n return String(this.value)\n }\n /** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */\n afterRun(): void {}\n}\n\n/** the standard var: the graph consumes the stored value AS-IS (Out = T) */\nexport abstract class ComfyVar<T> extends ComfyVarBase<T, T> {\n outValue(): T {\n return this.value\n }\n}\n\nexport class TextVar extends ComfyVar<string> {\n readonly kind = 'text' as const\n parse(raw: string): boolean {\n this.set(raw)\n return true\n }\n}\n\nconst commentLineRe = /^\\s*\\/\\//\nconst negativeLineRe = /^\\s*- (.*)$/\n\n/** what PromptVar needs from a loras var: covariant face, so LorasVar<'a'|'b'> fits */\nexport type ActiveLoraSource = { activeNames(): string[] }\n\n/** what a prompt CONTRIBUTES to build: `vars.prompt.positive` / `.negative` */\nexport type PromptValue = { positive: string; negative: string }\n\n/**\n * prompt text with editor comforts, all resolved at BUILD time (the editor and\n * drafts keep the raw text):\n * - `//` lines are COMMENTS — stripped\n * - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,\n * comma-joined into `.negative`\n * - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords\n * (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —\n * `injectedKeywords()` is public so the TUI can PREVIEW the injection.\n */\nexport class PromptVar extends ComfyVarBase<string, PromptValue> {\n readonly kind = 'text' as const\n constructor(\n defaultValue: string,\n public promptOpts: { label?: string; loraKeywordsFrom?: ActiveLoraSource } = {},\n ) {\n super(defaultValue, promptOpts.label)\n }\n parse(raw: string): boolean {\n this.set(raw)\n return true\n }\n static isCommentLine(line: string): boolean {\n return commentLineRe.test(line)\n }\n static isNegativeLine(line: string): boolean {\n return negativeLineRe.test(line)\n }\n /** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */\n injectedKeywords(): string[] {\n const src = this.promptOpts.loraKeywordsFrom\n if (src == null) return []\n return [\n ...new Set(\n src\n .activeNames()\n .map(getLoraKeyword)\n .filter((k) => k !== ''),\n ),\n ]\n }\n outValue(): PromptValue {\n const pos: string[] = []\n const neg: string[] = []\n for (const line of this.value.split('\\n')) {\n if (commentLineRe.test(line)) continue\n const m = negativeLineRe.exec(line)\n if (m != null) {\n const text = (m[1] ?? '').trim()\n if (text !== '') neg.push(text)\n } else pos.push(line)\n }\n const body = pos.join('\\n').trim()\n const keywords = this.injectedKeywords()\n const positive =\n keywords.length === 0 ? body : body === '' ? keywords.join(', ') : `${keywords.join(', ')}, ${body}`\n return { positive, negative: neg.join(', ') }\n }\n}\n\nexport class IntVar extends ComfyVar<number> {\n readonly kind = 'int' as const\n constructor(\n defaultValue: number,\n public opts: { min?: number; max?: number; label?: string } = {},\n ) {\n super(defaultValue, opts.label)\n }\n override set(value: number): this {\n const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)))\n return super.set(clamped)\n }\n parse(raw: string): boolean {\n const n = Number(raw)\n if (Number.isNaN(n)) return false\n this.set(n)\n return true\n }\n}\n\nexport class FloatVar extends ComfyVar<number> {\n readonly kind = 'float' as const\n constructor(\n defaultValue: number,\n public opts: { min?: number; max?: number; label?: string } = {},\n ) {\n super(defaultValue, opts.label)\n }\n override set(value: number): this {\n return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)))\n }\n parse(raw: string): boolean {\n const n = Number(raw)\n if (Number.isNaN(n)) return false\n this.set(n)\n return true\n }\n}\n\n/** '=' fixed · '+' increment each run · '-' decrement each run · '?' reroll each run */\nexport type SeedMode = '=' | '+' | '-' | '?'\n\n/**\n * a seed is a MODE + a number. `value` stays a plain number (what the graph\n * consumes); `mode` decides how it advances after each run (afterRun()):\n * `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.\n * The number shown is always the seed the NEXT run will use.\n */\nexport class SeedVar extends ComfyVar<number> {\n readonly kind = 'seed' as const\n mode: SeedMode = '='\n constructor(defaultValue: number = 0, label?: string) {\n super(defaultValue, label)\n // subclass-owned observable field (base makeObservable already ran in super)\n makeObservable(this, { mode: observable, setMode: action, randomize: action, advance: action })\n }\n setMode(mode: SeedMode): this {\n this.mode = mode\n return this\n }\n randomize(): this {\n return this.set(Math.floor(Math.random() * 2 ** 32))\n }\n override set(value: number): this {\n // seeds are unsigned: clamp at 0 so decrement can't go negative\n return super.set(Math.max(0, Math.floor(value)))\n }\n /** move the seed to what the NEXT run should use, per mode */\n advance(): this {\n if (this.mode === '+') return this.set(this.value + 1)\n if (this.mode === '-') return this.set(this.value - 1)\n if (this.mode === '?') return this.randomize()\n return this // '=' stays fixed\n }\n override afterRun(): void {\n this.advance()\n }\n /** mode is part of the seed's state: a reset must not keep a caller's `?`/`+` alive\n * ('=' is the construction default; drafts restore their own mode via loadJSON) */\n override reset(): this {\n this.setMode('=')\n return super.reset()\n }\n /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */\n parse(raw: string): boolean {\n const m = raw.trim().match(/^([+\\-=?])?\\s*(\\d+)?$/)\n if (m == null) return false\n const modeChar = m[1]\n const numStr = m[2]\n if (modeChar == null && numStr == null) return false\n this.setMode(modeChar == null ? '=' : (modeChar as SeedMode))\n if (numStr != null) this.set(Number(numStr))\n return true\n }\n override display(): string {\n return `${this.mode} ${this.value}`\n }\n override toEditBuffer(): string {\n return `${this.mode} ${this.value}`\n }\n override toJSON(): unknown {\n return { mode: this.mode, value: this.value }\n }\n override loadJSON(value: unknown): this {\n if (typeof value === 'number') return this.set(value) // legacy plain-number drafts\n if (value != null && typeof value === 'object') {\n const o = value as { mode?: unknown; value?: unknown }\n if (o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?') this.setMode(o.mode)\n if (typeof o.value === 'number') this.set(o.value)\n }\n return this\n }\n}\n\nexport class ToggleVar extends ComfyVar<boolean> {\n readonly kind = 'toggle' as const\n toggle(): this {\n return this.set(!this.value)\n }\n parse(raw: string): boolean {\n if (raw !== 'true' && raw !== 'false') return false\n this.set(raw === 'true')\n return true\n }\n override display(): string {\n return this.value ? 'ON' : 'OFF'\n }\n}\n\nexport class ChoiceVar<T extends string> extends ComfyVar<T> {\n readonly kind = 'choice' as const\n constructor(\n public readonly choices: readonly T[],\n defaultValue: T,\n label?: string,\n ) {\n super(defaultValue, label)\n }\n next(delta: number = 1): this {\n const ix = this.choices.indexOf(this.value)\n const nextIx = (ix + delta + this.choices.length) % this.choices.length\n return this.set(this.choices[nextIx] ?? this.value)\n }\n parse(raw: string): boolean {\n const hit = this.choices.find((c) => c === raw)\n if (hit == null) return false\n this.set(hit)\n return true\n }\n}\n\n/**\n * per-lora setting: false = off, true = 1/1, number = both strengths,\n * [strength_model, strength_clip] = each explicitly\n */\nexport type LoraStrength = boolean | number | [strengthModel: number, strengthClip: number]\n\nexport type ActiveLora<T extends string> = { lora_name: T; strength_model: number; strength_clip: number }\n\n/** normalize a loras record into what a standard LoraLoader chain consumes */\nexport function activeLoras<T extends string>(loras: Partial<Record<T, LoraStrength>>): ActiveLora<T>[] {\n const out: ActiveLora<T>[] = []\n for (const [lora_name, s] of Object.entries(loras) as [T, LoraStrength | undefined][]) {\n if (s == null || s === false) continue\n const [strength_model, strength_clip] = Array.isArray(s) ? s : s === true ? [1, 1] : [s, s]\n out.push({ lora_name, strength_model, strength_clip })\n }\n return out\n}\n\n/** what LorasVar.bindHost needs — structural, so ComfyVars never imports ComfyHost */\nexport type LorasHost = { schema: { getLoras(filter?: RegExp): string[] } }\n\n/**\n * multi-select lora stack over a DYNAMIC options list — a RegExp resolves\n * against the host's loras at define time (DefinedWorkflow calls bindHost),\n * or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never\n * a hardcoded inventory. Selection is empty by default.\n */\nexport class LorasVar<T extends string> extends ComfyVar<Partial<Record<T, LoraStrength>>> {\n readonly kind = 'loras' as const\n /** last non-false strength per lora, so untick → re-tick restores it */\n private prev: Partial<Record<T, LoraStrength>> = {}\n /** a RegExp source resolves lazily (bindHost) — null until then */\n private resolvedOptions: readonly T[] | null = null\n\n constructor(\n private readonly optionsSource: readonly T[] | RegExp,\n initial: Partial<Record<T, LoraStrength>> = {},\n label?: string,\n ) {\n super(initial, label)\n }\n\n get options(): readonly T[] {\n if (!(this.optionsSource instanceof RegExp)) return this.optionsSource\n if (this.resolvedOptions == null)\n throw new Error(\n `v.loras(${String(this.optionsSource)}) is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list otherwise)`,\n )\n return this.resolvedOptions\n }\n\n /** DefinedWorkflow binds the host at define time: a RegExp source resolves here.\n * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime\n * values of the SAME object_info enum the generated E_LoraName union comes from */\n bindHost(host: LorasHost): void {\n if (!(this.optionsSource instanceof RegExp)) return\n this.resolvedOptions = host.schema.getLoras(this.optionsSource) as T[]\n }\n\n get names(): T[] {\n return [...this.options]\n }\n\n /** loras currently ON (PromptVar keyword prefixing consumes this) */\n activeNames(): T[] {\n return this.names.filter((n) => this.isOn(n))\n }\n\n isOn(name: T): boolean {\n const s = this.value[name]\n return s != null && s !== false\n }\n\n toggleItem(name: T): this {\n const cur = this.value[name]\n if (cur == null || cur === false) return this.set({ ...this.value, [name]: this.prev[name] ?? true })\n this.prev[name] = cur\n return this.set({ ...this.value, [name]: false })\n }\n\n /** step both strengths by delta (true becomes 1 first); no-op when off */\n adjustItem(name: T, delta: number): this {\n const cur = this.value[name]\n if (cur == null || cur === false) return this\n const step = (n: number): number => Math.max(0, Math.round((n + delta) * 100) / 100)\n const next: LoraStrength = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur)\n return this.set({ ...this.value, [name]: next })\n }\n\n /** compact per-item strength label for lists */\n strengthLabel(name: T): string {\n const s = this.value[name]\n if (s == null || s === false) return ''\n if (s === true) return '1.00'\n if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`\n return s.toFixed(2)\n }\n\n parse(raw: string): boolean {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (typeof parsed !== 'object' || parsed == null || Array.isArray(parsed)) return false\n this.set(parsed as Partial<Record<T, LoraStrength>>)\n return true\n } catch {\n return false\n }\n }\n\n /** short human name: subfolder + extension stripped */\n static shortName(name: string): string {\n return (name.split(/[\\\\/]/).pop() ?? name).replace(/\\.safetensors$/, '')\n }\n\n /** tick (true) or untick (false) every lora in `names` (default: all options) */\n setAll(on: boolean, names: readonly T[] = this.options): this {\n const next = { ...this.value }\n for (const name of names) {\n const cur = next[name]\n if (on) {\n if (cur == null || cur === false) next[name] = this.prev[name] ?? true\n } else {\n if (cur != null && cur !== false) this.prev[name] = cur\n next[name] = false\n }\n }\n return this.set(next)\n }\n\n override display(): string {\n const on = this.activeNames()\n if (on.length === 0) return `(0/${this.options.length}) none`\n return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(', ')}`\n }\n}\n\nexport type SizeValue = { width: number; height: number }\nexport type SizePreset = { label: string; width: number; height: number }\n\n/** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */\nexport const DEFAULT_SIZE_PRESETS: SizePreset[] = [\n { label: '1:1 square', width: 1024, height: 1024 },\n { label: '4:3 landscape', width: 1152, height: 896 },\n { label: '3:4 portrait', width: 896, height: 1152 },\n { label: '3:2 landscape', width: 1216, height: 832 },\n { label: '2:3 portrait', width: 832, height: 1216 },\n { label: '16:9 widescreen', width: 1344, height: 768 },\n { label: '9:16 tall', width: 768, height: 1344 },\n]\n\n/** width/height picker: presets + free `WxH` entry + optionally the LIVE\n * size of a linked image var (his ask 2026-07-30: the widget shows\n * `WxH size of image '<name>'` as a pickable row) */\nexport class SizeVar extends ComfyVar<SizeValue> {\n readonly kind = 'size' as const\n constructor(\n defaultValue: SizeValue = { width: 1024, height: 1024 },\n public readonly presets: SizePreset[] = DEFAULT_SIZE_PRESETS,\n label?: string,\n public readonly imageVar?: ImageVar,\n ) {\n super(defaultValue, label)\n }\n\n /** current dimensions of the linked image var — null when no link, unset\n * path, or an unreadable/undecodable file (those errors belong to the\n * image var itself, the size row simply disappears) */\n imageSize(): { width: number; height: number; name: string } | null {\n const iv = this.imageVar\n if (iv == null || iv.value === '') return null\n try {\n const abs = iv.absPath()\n const meta = imageMeta(getComfyStorage().readBytes(abs))\n if (meta.width == null || meta.height == null) return null\n return { width: meta.width, height: meta.height, name: basename(abs) }\n } catch {\n return null\n }\n }\n\n /** accepts '1024x768' / '1024×768' / a preset label */\n parse(raw: string): boolean {\n const m = raw.trim().match(/^(\\d+)\\s*[x×]\\s*(\\d+)$/)\n if (m != null) {\n this.set({ width: Number(m[1]), height: Number(m[2]) })\n return true\n }\n const preset = this.presets.find((p) => p.label === raw.trim())\n if (preset != null) {\n this.set({ width: preset.width, height: preset.height })\n return true\n }\n return false\n }\n\n override display(): string {\n const { width, height } = this.value\n const hit = this.presets.find((p) => p.width === width && p.height === height)\n return `${width}×${height}${hit ? ` (${hit.label})` : ''}`\n }\n}\n\nexport type ImageVarOpts = {\n /** where the TUI picker starts browsing AND what relative values resolve against (absPath) */\n folder?: string\n /** picker listing filter, lowercase without dots; never affects the value */\n extensions?: readonly string[]\n label?: string\n}\n\nexport const DEFAULT_IMAGE_EXTENSIONS: readonly string[] = ['png', 'jpg', 'jpeg', 'webp', 'gif']\n\n/** empty image var consumed at build time — typed so drivers surface it apart from real crashes */\nexport class ImageVarEmptyError extends Error {\n constructor(public readonly varName: string) {\n super(`image var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/image.png'))`)\n }\n}\n\n/** trim + expand a leading `~/` — every ImageVar write funnels through this */\nfunction expandUserPath(raw: string): string {\n const trimmed = raw.trim()\n return trimmed.startsWith('~/') ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed\n}\n\n/**\n * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,\n * drafts persist it verbatim (toJSON = the string), hand-editable in the\n * draft json. Empty = unset: outValue()/absPath() throw ImageVarEmptyError,\n * so a build never runs on a silent placeholder. The TUI opens the image\n * picker overlay for kind 'image'.\n */\nexport class ImageVar extends ComfyVar<string> {\n readonly kind = 'image' as const\n constructor(\n defaultValue: string,\n public opts: ImageVarOpts = {},\n ) {\n super(expandUserPath(defaultValue), opts.label)\n }\n /** what the picker lists (lowercase, no dots) */\n get extensions(): readonly string[] {\n return this.opts.extensions ?? DEFAULT_IMAGE_EXTENSIONS\n }\n override set(value: string): this {\n return super.set(expandUserPath(value))\n }\n parse(raw: string): boolean {\n this.set(raw)\n return true\n }\n isSet(): boolean {\n return this.value !== ''\n }\n private emptyError(): ImageVarEmptyError {\n return new ImageVarEmptyError(this.name ?? this.label ?? 'image')\n }\n /** the ONE resolution helper: absolute kept as-is, relative resolved against opts.folder, else cwd */\n absPath(): string {\n if (!this.isSet()) throw this.emptyError()\n if (isAbsolute(this.value)) return this.value\n return resolve(this.opts.folder ?? getComfyStorage().cwd(), this.value)\n }\n /** empty = unset: the build fails LOUD here (varValues calls outValue) */\n override outValue(): string {\n if (!this.isSet()) throw this.emptyError()\n return this.value\n }\n override display(): string {\n if (!this.isSet()) return '(unset) pick a file'\n const home = getComfyStorage().homedir()\n return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value\n }\n}\n\n/** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size / v.image */\nexport const v = {\n text: (defaultValue: string, label?: string): TextVar => new TextVar(defaultValue, label),\n prompt: (defaultValue: string, opts: { label?: string; loraKeywordsFrom?: ActiveLoraSource } = {}): PromptVar =>\n new PromptVar(defaultValue, opts),\n int: (defaultValue: number, opts: { min?: number; max?: number; label?: string } = {}): IntVar =>\n new IntVar(defaultValue, opts),\n float: (defaultValue: number, opts: { min?: number; max?: number; label?: string } = {}): FloatVar =>\n new FloatVar(defaultValue, opts),\n seed: (defaultValue: number = 0, label?: string): SeedVar => new SeedVar(defaultValue, label),\n toggle: (defaultValue: boolean, label?: string): ToggleVar => new ToggleVar(defaultValue, label),\n choice: <const T extends string>(choices: readonly T[], defaultValue: T, label?: string): ChoiceVar<T> =>\n new ChoiceVar(choices, defaultValue, label),\n loras: <T extends string = string>(\n options: readonly T[] | RegExp,\n initial: Partial<Record<T, LoraStrength>> = {},\n label?: string,\n ): LorasVar<T> => new LorasVar(options, initial, label),\n size: (defaultValue?: SizeValue, opts: { presets?: SizePreset[]; label?: string; image?: ImageVar } = {}): SizeVar =>\n new SizeVar(defaultValue, opts.presets, opts.label, opts.image),\n image: (defaultValue: string, opts: ImageVarOpts = {}): ImageVar => new ImageVar(defaultValue, opts),\n}\n\n/**\n * structural face of any var: readonly `value` keeps ComfyVar<T> assignable\n * despite T-invariance on the mutable field. VarValues re-derives the exact\n * value types via infer.\n */\nexport type AnyVar = {\n readonly kind: VarKind\n readonly value: unknown\n readonly defaultValue: unknown\n readonly label?: string\n /** the vars-spec key — DefinedWorkflow writes it at define time */\n name?: string\n parse(raw: string): boolean\n loadJSON(value: unknown): unknown\n reset(): unknown\n toJSON(): unknown\n outValue(): unknown\n display(): string\n toEditBuffer(): string\n afterRun(): void\n /** host-dependent vars (LorasVar regex) resolve here — DefinedWorkflow calls it at define time */\n bindHost?(host: LorasHost): void\n}\n\nexport type VarsSpec = { [key: string]: AnyVar }\n\nexport type VarValues<V extends VarsSpec> = {\n // outValue() return type, not the stored type: PromptVar stores string, contributes PromptValue\n [K in keyof V]: V[K] extends { outValue(): infer O } ? O : never\n}\n\nexport function varValues<V extends VarsSpec>(vars: V): VarValues<V> {\n const out: Record<string, unknown> = {}\n // outValue, not value: PromptVar strips comments / prefixes lora keywords here\n for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue()\n return out as VarValues<V>\n}\n","import type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport type { ComfyExecution } from 'src/runner/ComfyExecution.ts'\nimport type { ComfyWorkflow, RunSettings } from 'src/runner/ComfyWorkflow.ts'\nimport type { SdkForHost } from 'src/types/comfy-sdk.ts'\nimport {\n type AnyVar,\n type LorasVar,\n type LoraStrength,\n v,\n type VarsSpec,\n type VarValues,\n varValues,\n} from 'src/vars/ComfyVars.ts'\n\n/** the host's generated lora-name union (plain string when no sdk is generated) */\nexport type LoraNameOf<ID extends string> = 'E_LoraName' extends keyof SdkForHost<ID>['Union']\n ? SdkForHost<ID>['Union']['E_LoraName'] & string\n : string\n\n/**\n * the `v` handed to a vars LAMBDA: the global factory, host-typed —\n * `v.loras(regex)` yields the host's lora-name union (resolved via bindHost)\n */\nexport type BoundVars<ID extends string> = Omit<typeof v, 'loras'> & {\n loras(\n options: RegExp,\n initial?: Partial<Record<LoraNameOf<ID>, LoraStrength>>,\n label?: string,\n ): LorasVar<LoraNameOf<ID>>\n loras<T extends string>(\n options: readonly T[],\n initial?: Partial<Record<T, LoraStrength>>,\n label?: string,\n ): LorasVar<T>\n}\n\nexport type DefineWorkflowSpec<ID extends string, V extends VarsSpec> = {\n /** short id; also names the workflow instances */\n id?: string\n /** optional TUI tree color (ink color name or hex); unset = the tree's\n * per-family palette (first `-` word of the module basename) */\n color?: string\n /** the tweakable knobs; drivers (scripts, TUI) edit these between runs.\n * A LAMBDA gives cross-referencing vars a scope (loras + prompt with\n * loraKeywordsFrom created inline) — resolved ONCE at define time, and it\n * RECEIVES the host-typed `v` (no import needed) */\n vars: V | ((v: BoundVars<ID>) => V)\n /** builds the graph from the CURRENT var values; re-executed on every run().\n * may be async (e.g. image uploads through the wf param) */\n build: (b: SdkForHost<ID>['Builder'], vars: VarValues<V>, wf: ComfyWorkflow<ID>) => void | Promise<void>\n}\n\n/** type predicate (not a cast): a VarsSpec is a plain record, never callable */\nfunction isVarsThunk<ID extends string, V extends VarsSpec>(\n vars: V | ((v: BoundVars<ID>) => V),\n): vars is (v: BoundVars<ID>) => V {\n return typeof vars === 'function'\n}\n\n/**\n * a re-runnable workflow definition: `build` re-executes per run with the\n * current var values, so every run gets a fresh, deterministic graph.\n */\nexport class DefinedWorkflow<ID extends string = string, V extends VarsSpec = VarsSpec> {\n /** spec.vars resolved once (may be given as a thunk) — the SAME instances for the workflow's lifetime */\n readonly vars: V\n\n constructor(\n public host: ComfyHost<ID>,\n public spec: DefineWorkflowSpec<ID, V>,\n ) {\n // cast: whitelist family 1 (agent/coding.md) — the runtime `v` IS the\n // factory BoundVars describes; the regex-loras typing claim it adds is\n // resolved from the same object_info enum via bindHost below\n this.vars = isVarsThunk(spec.vars) ? spec.vars(v as BoundVars<ID>) : spec.vars\n // define-time var wiring: the spec key becomes the var's name (error\n // messages name the var with it), host-dependent vars (v.loras(regex))\n // resolve their options\n for (const [key, varDef] of this.entries()) {\n varDef.name = key\n varDef.bindHost?.(this.host)\n }\n }\n\n /** [name, var] pairs, for drivers that enumerate the knobs */\n entries(): [string, AnyVar][] {\n return Object.entries(this.vars)\n }\n\n /** the workflow built by the latest run() (null before the first run) */\n lastWorkflow: ComfyWorkflow<ID> | null = null\n /** the latest execution (null before the first run) */\n lastExecution: ComfyExecution | null = null\n\n /**\n * build a fresh graph from the CURRENT var values (no send). `p.advance`\n * (set by run()) fires each var's afterRun() right after snapshotting the\n * values — atomically, before any await — so the graph uses this run's seed\n * while the var moves to the next (queued runs get distinct seeds; a bare\n * build() for copy/export never advances). `p.host` substitutes the host\n * the graph is built against (TUI host override): node/model availability\n * there surfaces as workflow.problems / server validation, by design.\n */\n async build(p: { advance?: boolean; host?: ComfyHost<ID> } = {}): Promise<ComfyWorkflow<ID>> {\n const host = p.host ?? this.host\n const wf = host.workflow({ id: this.spec.id })\n const values = varValues(this.vars)\n if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun()\n await this.spec.build(wf.builder, values, wf)\n this.lastWorkflow = wf\n return wf\n }\n\n /** build a fresh graph from the current var values, send it, wait for outputs.\n * connects first (idempotent) — modules can import offline from the schema cache.\n * `settings.host` runs against THAT host instead of the defining one. */\n async run(settings: RunSettings & { host?: ComfyHost<ID> } = {}): Promise<ComfyExecution> {\n const host = settings.host ?? this.host\n await host.connect()\n const wf = await this.build({ advance: true, host })\n const execution = await wf.run({\n save: settings.save,\n ephemeral: settings.ephemeral,\n scrubHistory: settings.scrubHistory,\n idMode: settings.idMode,\n log: settings.log,\n onProgress: settings.onProgress,\n })\n this.lastExecution = execution\n return execution\n }\n}\n"],"mappings":";;;;AAGA,MAAa,gBAAyB,QAAQ,IAAI,mBAAmB;AACrE,MAAa,WAAW,QAAsB;CAC3C,IAAI,CAAC,QAAQ,GAAG,QAAQ,IAAI,GAAG;AAClC;AACA,MAAa,YAAY,QAAsB,QAAQ,MAAM,iBAAiB,KAAK;AACnF,MAAa,cAAc,QAAsB,QAAQ,IAAI,iBAAiB,KAAK;;;AC2BnF,SAAS,UAAU,MAAsB;CACtC,MAAM,KAAK,KAAK,YAAY,GAAG;CAC/B,OAAO,MAAM,IAAI,MAAM,KAAK,MAAM,GAAG,EAAE;AAC1C;;;AAIA,SAAgB,sBAAsB,IAAgB,IAA8B;CACjF,OAAO;EACJ,MAAM;EACN,WAAW,MAAM,GAAG,aAAa,GAAG,MAAM;EAC1C,mBAAmB,MAAO,GAAG,WAAW,CAAC,IAAK,GAAG,aAAa,GAAG,MAAM,IAAe;EACtF,YAAY,MAAM,IAAI,WAAW,GAAG,aAAa,CAAC,CAAe;EACjE,YAAY,GAAG,SAAS;GACrB,GAAG,UAAU,UAAU,CAAC,GAAG,EAAE,WAAW,KAAK,CAAC;GAC9C,GAAG,cAAc,GAAG,IAAI;EAC3B;EACA,aAAa,GAAG,UAAU;GACvB,GAAG,UAAU,UAAU,CAA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S;GACvB,QAAQ,SAAS;GACjB,KAAK,SAAS;GACd,YAAY,SAAS;EACxB,CAAC;EACD,KAAK,gBAAgB;EACrB,OAAO;CACV;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-serve-CnlN_RFH.js","names":[],"sources":["../src/cli/serve/describeVar.ts","../src/cli/serve/applyVarPayload.ts","../src/cli/serve/ServeApp.ts","../src/cli/serve/run-serve.ts"],"sourcesContent":["// PURE var → descriptor: ONE introspection pass feeds GET /drafts (json) AND\n// the startup print (renderDescriptorLine)\nimport {\n type AnyVar,\n ChoiceVar,\n FloatVar,\n ImageVar,\n IntVar,\n LorasVar,\n PromptVar,\n SeedVar,\n SizeVar,\n type SizePreset,\n type VarKind,\n} from 'src/vars/ComfyVars.ts'\n\nexport type VarDescriptor = {\n kind: VarKind\n label?: string\n /** what a POST payload accepts for this var, human-readable */\n payload: string\n default: unknown\n choices?: readonly string[]\n /** loras: the resolved option list */\n options?: readonly string[]\n min?: number\n max?: number\n presets?: SizePreset[]\n extensions?: readonly string[]\n}\n\nfunction rangeText(opts: { min?: number; max?: number }): string {\n if (opts.min == null && opts.max == null) return ''\n return ` (${opts.min ?? '-∞'}..${opts.max ?? '∞'})`\n}\n\nexport function describeVar(varDef: AnyVar): VarDescriptor {\n const base = { kind: varDef.kind, label: varDef.label, default: varDef.defaultValue }\n if (varDef instanceof PromptVar) return { ...base, payload: 'string (\"//\" lines = comments, \"- \" lines = negative)' }\n if (varDef instanceof IntVar)\n return { ...base, payload: `integer${rangeText(varDef.opts)}`, min: varDef.opts.min, max: varDef.opts.max }\n if (varDef instanceof FloatVar)\n return { ...base, payload: `number${rangeText(varDef.opts)}`, min: varDef.opts.min, max: varDef.opts.max }\n if (varDef instanceof SeedVar)\n return {\n ...base,\n default: { mode: varDef.mode, value: varDef.defaultValue },\n payload: 'number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}',\n }\n if (varDef.kind === 'toggle') return { ...base, payload: 'true or false' }\n if (varDef instanceof ChoiceVar)\n return { ...base, payload: `one of: ${varDef.choices.join(' | ')}`, choices: varDef.choices }\n if (varDef instanceof LorasVar)\n return {\n ...base,\n payload: '{\"<lora name>\": false | true | strength | [model, clip]}',\n options: varDef.options,\n }\n if (varDef instanceof SizeVar)\n return { ...base, payload: '{\"width\":W,\"height\":H} or \"WxH\" or a preset label', presets: varDef.presets }\n if (varDef instanceof ImageVar)\n return { ...base, payload: 'local file path or http(s) url', extensions: varDef.extensions }\n return { ...base, payload: 'string' } // TextVar and future plain kinds\n}\n\n/** one aligned console line per var (startup print) */\nexport function renderDescriptorLine(name: string, d: VarDescriptor, nameWidth: number): string {\n const def = typeof d.default === 'string' ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default)\n return ` ${name.padEnd(nameWidth)} ${d.kind.padEnd(6)} ${d.payload} · default: ${truncate(def ?? 'null', 60)}`\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : s.slice(0, n - 1) + '…'\n}\n","// PURE payload → var application: one POST body value onto one var, per kind.\n// Returns an error message (nothing applied) or null. No fs here — ImageVar\n// url download + existence checks are ServeApp's job.\nimport {\n type AnyVar,\n ChoiceVar,\n FloatVar,\n ImageVar,\n IntVar,\n type LoraStrength,\n LorasVar,\n PromptVar,\n SeedVar,\n SizeVar,\n TextVar,\n ToggleVar,\n} from 'src/vars/ComfyVars.ts'\n\nfunction isFiniteNumber(x: unknown): x is number {\n return typeof x === 'number' && Number.isFinite(x)\n}\n\nfunction isLoraStrength(x: unknown): x is LoraStrength {\n if (typeof x === 'boolean') return true\n if (isFiniteNumber(x)) return true\n return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1])\n}\n\n/** cap long option lists in error messages */\nfunction listSome(items: readonly string[], cap: number = 20): string {\n if (items.length <= cap) return items.join(', ')\n return `${items.slice(0, cap).join(', ')} … +${items.length - cap} more`\n}\n\nexport function applyVarPayload(varDef: AnyVar, raw: unknown): string | null {\n const name = varDef.name ?? varDef.label ?? varDef.kind\n\n if (varDef instanceof TextVar || varDef instanceof PromptVar) {\n if (typeof raw !== 'string') return `var '${name}' expects a string`\n varDef.set(raw)\n return null\n }\n\n if (varDef instanceof IntVar || varDef instanceof FloatVar) {\n if (isFiniteNumber(raw)) {\n varDef.set(raw) // set() clamps to min/max\n return null\n }\n if (typeof raw === 'string' && varDef.parse(raw)) return null\n const o = varDef.opts\n const range = o.min == null && o.max == null ? '' : ` (${o.min ?? '-∞'}..${o.max ?? '∞'})`\n return `var '${name}' expects a number${range}`\n }\n\n if (varDef instanceof SeedVar) {\n if (isFiniteNumber(raw)) {\n // an explicit payload seed is FIXED for this request\n varDef.setMode('=')\n varDef.set(raw)\n return null\n }\n if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {\n const o = raw as { mode?: unknown; value?: unknown }\n const mode = o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?' ? o.mode : null\n if (o.mode !== undefined && mode == null) return `var '${name}': mode must be one of = + - ?`\n if (o.value !== undefined && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`\n if (mode == null && o.value === undefined) return `var '${name}': give \"mode\" and/or \"value\"`\n if (mode != null) varDef.setMode(mode)\n if (isFiniteNumber(o.value)) varDef.set(o.value)\n return null\n }\n return `var '${name}' expects a number or {\"mode\":\"=|+|-|?\",\"value\":number}`\n }\n\n if (varDef instanceof ToggleVar) {\n if (typeof raw !== 'boolean') return `var '${name}' expects true or false`\n varDef.set(raw)\n return null\n }\n\n if (varDef instanceof ChoiceVar) {\n if (typeof raw === 'string' && varDef.parse(raw)) return null\n return `var '${name}' expects one of: ${listSome(varDef.choices)}`\n }\n\n if (varDef instanceof LorasVar) {\n if (raw == null || typeof raw !== 'object' || Array.isArray(raw))\n return `var '${name}' expects {\"<lora name>\": false | true | strength | [model, clip]}`\n const record = raw as Record<string, unknown>\n const known = new Set<string>(varDef.options)\n const unknownNames = Object.keys(record).filter((k) => !known.has(k))\n if (unknownNames.length > 0)\n return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome(varDef.options)}`\n for (const [k, s] of Object.entries(record))\n if (!isLoraStrength(s)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`\n varDef.set(record as Partial<Record<string, LoraStrength>>) // every entry validated just above\n return null\n }\n\n if (varDef instanceof SizeVar) {\n if (typeof raw === 'string' && varDef.parse(raw)) return null\n if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {\n const o = raw as { width?: unknown; height?: unknown }\n if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {\n varDef.set({ width: o.width, height: o.height })\n return null\n }\n }\n return `var '${name}' expects {\"width\":W,\"height\":H}, \"WxH\", or a preset label`\n }\n\n if (varDef instanceof ImageVar) {\n if (typeof raw !== 'string') return `var '${name}' expects a file path or http(s) url string`\n varDef.set(raw)\n return null\n }\n\n return `var '${name}' has unsupported kind '${varDef.kind}'`\n}\n","// `comfy-ts serve` request handling, transport-free: run-serve owns node:http,\n// tests call handle() directly with an injected starter. Full contract:\n// agent/architecture.md item 12.\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { nanoid } from 'nanoid'\nimport { basename, dirname, extname, join, resolve } from 'pathe'\nimport { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'\nimport { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'\nimport { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'\nimport { ImageVar, ImageVarEmptyError, SeedVar } from 'src/vars/ComfyVars.ts'\nimport type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\n\nexport type ServeModule = { key: string; file: string; dw: DefinedWorkflow }\n\n/** structural face of ComfyExecution — tests inject a fake starter.\n * absPath is null for in-memory images (a ws-saver run with saving off) */\nexport type ServeExecution = {\n done: Promise<unknown>\n status: string\n images: { absPath: string | null; filename: string }[]\n data: { id: string; error?: unknown }\n}\n\nexport type ServeStarter = (mod: ServeModule) => Promise<ServeExecution>\n\nexport type ServeRequest = { method: string; url: string; accept?: string; body?: string }\nexport type ServeReply = { status: number; contentType: string; body: string | Uint8Array }\n\n/** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.\n * serve OPTS INTO local saving (library default is memory-only, architecture.md\n * item 14): the /outputs/ routes serve files, grouped per module */\nconst realStarter: ServeStarter = async (mod) => {\n await mod.dw.host.connect()\n const wf = await mod.dw.build({ advance: true })\n return await wf.start({ save: { prefix: mod.key } })\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.gif': 'image/gif',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.json': 'application/json',\n '.txt': 'text/plain',\n}\n\nfunction json(status: number, payload: unknown): ServeReply {\n return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }\n}\n\nconst USAGE = [\n 'GET /drafts — every served workflow, its drafts and var descriptors',\n 'GET /drafts/<module>/<draft> — one draft with its stored values',\n 'POST /generate/<module>/<draft> with { ...vars } — run, blocking',\n 'POST /generate/<draft> — unqualified, when unambiguous',\n 'GET /outputs/<path> — generated files',\n]\n\nexport class ServeApp {\n private starter: ServeStarter\n /** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it */\n private seedState = new Map<string, number>()\n /** per-module promise chain: vars are shared mutable state, apply→send is exclusive */\n private chains = new Map<string, Promise<unknown>>()\n\n constructor(\n public modules: ServeModule[],\n private opts: { starter?: ServeStarter; outputRoot?: string; loadErrors?: Record<string, string> } = {},\n ) {\n this.starter = opts.starter ?? realStarter\n }\n\n private get outputRoot(): string {\n return this.opts.outputRoot ?? comfyts.outputPath\n }\n\n // #region routing ----------------------------------------------------------\n async handle(req: ServeRequest): Promise<ServeReply> {\n try {\n const path = (req.url.split('?')[0] ?? '/').split('#')[0] ?? '/'\n let segs: string[]\n try {\n segs = path\n .split('/')\n .filter((s) => s !== '')\n .map(decodeURIComponent)\n } catch {\n return json(400, { error: `bad url encoding: ${path}` })\n }\n if (req.method === 'GET') {\n if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return this.replyIndex()\n if (segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyDraft(segs[1], segs[2])\n if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))\n return json(404, { error: `no route: GET ${path}`, usage: USAGE })\n }\n if (req.method === 'POST' && segs[0] === 'generate') {\n const target = this.resolveDraft(segs.slice(1))\n if ('error' in target) return json(target.status, { error: target.error })\n return await this.generate(target.mod, target.draft, req)\n }\n return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })\n } catch (e) {\n console.error('[serve] request crashed:', e)\n return json(500, { error: extractErrorMessage(e) })\n }\n }\n\n moduleByKey(key: string): ServeModule | null {\n return this.modules.find((m) => m.key === key) ?? null\n }\n\n /** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */\n draftsFor(mod: ServeModule): string[] {\n const onDisk = listDraftsForFile(mod.file)\n return ['default', ...onDisk.filter((n) => n !== 'default')]\n }\n\n private draftExists(mod: ServeModule, draft: string): boolean {\n return draft === 'default' || existsSync(join(draftsDirForFile(mod.file), `${draft}.json`))\n }\n\n private resolveDraft(segs: string[]): { mod: ServeModule; draft: string } | { error: string; status: number } {\n if (segs.length === 2 && segs[0] != null && segs[1] != null) {\n const mod = this.moduleByKey(segs[0])\n if (mod == null)\n return {\n status: 404,\n error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(', ')}`,\n }\n if (!this.draftExists(mod, segs[1]))\n return {\n status: 404,\n error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n }\n return { mod, draft: segs[1] }\n }\n if (segs.length === 1 && segs[0] != null) {\n const draft = segs[0]\n if (this.modules.length === 1 && this.modules[0] != null) {\n const mod = this.modules[0]\n if (!this.draftExists(mod, draft))\n return {\n status: 404,\n error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n }\n return { mod, draft }\n }\n const hits = this.modules.filter((m) => this.draftExists(m, draft))\n if (hits.length === 1 && hits[0] != null) return { mod: hits[0], draft }\n if (hits.length === 0) return { status: 404, error: `no module has a draft '${draft}'` }\n return {\n status: 400,\n error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(' or ')}`,\n }\n }\n return { status: 400, error: 'use POST /generate/<module>/<draft> or /generate/<draft>' }\n }\n\n // #region introspection ----------------------------------------------------\n private describeModule(mod: ServeModule): Record<string, unknown> {\n const vars: Record<string, VarDescriptor> = {}\n for (const [name, varDef] of mod.dw.entries()) vars[name] = describeVar(varDef)\n return {\n module: mod.key,\n file: mod.file,\n host: mod.dw.host.data.id,\n drafts: this.draftsFor(mod),\n routes: this.draftsFor(mod).map(\n (d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`,\n ),\n vars,\n }\n }\n\n private replyIndex(): ServeReply {\n return json(200, {\n server: 'comfy-ts serve',\n usage: USAGE,\n workflows: this.modules.map((m) => this.describeModule(m)),\n ...(this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0\n ? { loadErrors: this.opts.loadErrors }\n : {}),\n })\n }\n\n private replyDraft(modKey: string, draft: string): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n if (!this.draftExists(mod, draft))\n return json(404, {\n error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n })\n return json(200, { ...this.describeModule(mod), draft, values: this.draftValues(mod, draft) })\n }\n\n /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */\n private draftValues(mod: ServeModule, draft: string): Record<string, unknown> {\n const path = join(draftsDirForFile(mod.file), `${draft}.json`)\n if (existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default\n return out\n }\n\n // #region outputs ----------------------------------------------------------\n private replyOutput(segs: string[]): ServeReply {\n const abs = resolve(this.outputRoot, ...segs)\n // traversal guard: the resolved path must stay under the output root\n if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + '/'))\n return json(400, { error: 'path escapes the outputs root' })\n if (!existsSync(abs) || !statSync(abs).isFile())\n return json(404, { error: `no such output file: /${segs.join('/')}` })\n const contentType = CONTENT_TYPES[extname(abs).toLowerCase()] ?? 'application/octet-stream'\n return { status: 200, contentType, body: new Uint8Array(readFileSync(abs)) }\n }\n\n private outputUrl(absPath: string): string | null {\n if (!absPath.startsWith(this.outputRoot + '/')) return null\n const rel = absPath.slice(this.outputRoot.length + 1)\n return '/outputs/' + rel.split('/').map(encodeURIComponent).join('/')\n }\n\n // #region generate ---------------------------------------------------------\n private async generate(mod: ServeModule, draft: string, req: ServeRequest): Promise<ServeReply> {\n let payload: Record<string, unknown> = {}\n if (req.body != null && req.body.trim() !== '') {\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body)\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, { error: 'body must be a json object: { \"<var>\": value, … }' })\n payload = parsed as Record<string, unknown>\n }\n\n const t0 = Date.now()\n const seeds: Record<string, number> = {}\n const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds))\n if ('error' in started) return json(started.status, { error: started.error })\n\n const execution = started.execution\n console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)\n await execution.done\n const durationMs = Date.now() - t0\n\n if (execution.status === 'Failure') {\n console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`)\n return json(500, {\n ok: false,\n module: mod.key,\n draft,\n promptId: execution.data.id,\n durationMs,\n error: execution.data.error ?? 'execution failed',\n })\n }\n\n console.log(\n `[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${execution.images.length} image(s)`,\n )\n\n // Accept: image/* → first image's bytes directly (curl -o, <img src>)\n const first = execution.images[0]\n if (req.accept?.includes('image/') && first?.absPath != null) {\n const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'\n return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }\n }\n\n return json(200, {\n ok: true,\n module: mod.key,\n draft,\n promptId: execution.data.id,\n durationMs,\n seeds,\n images: execution.images.map((img) => ({\n filename: img.filename,\n url: img.absPath != null ? this.outputUrl(img.absPath) : null,\n absPath: img.absPath,\n })),\n })\n }\n\n /** everything that touches the module's SHARED vars, under the module mutex */\n private async prepareAndStart(\n mod: ServeModule,\n draft: string,\n payload: Record<string, unknown>,\n seeds: Record<string, number>,\n ): Promise<{ execution: ServeExecution } | { error: string; status: number }> {\n // 1. reset, then load the draft FRESH from disk (TUI edits between requests apply)\n for (const [, varDef] of mod.dw.entries()) varDef.reset()\n const draftPath = join(draftsDirForFile(mod.file), `${draft}.json`)\n if (existsSync(draftPath)) {\n try {\n const values = JSON.parse(readFileSync(draftPath, 'utf8')) as Record<string, unknown>\n for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k])\n } catch (e) {\n return { status: 500, error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}` }\n }\n }\n\n // 2. payload overrides (image urls download first, so the var gets a local path)\n const varMap = new Map(mod.dw.entries())\n for (const [k, rawValue] of Object.entries(payload)) {\n const varDef = varMap.get(k)\n if (varDef == null)\n return { status: 400, error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(', ')}` }\n let value = rawValue\n if (varDef instanceof ImageVar && typeof rawValue === 'string' && /^https?:\\/\\//.test(rawValue)) {\n try {\n value = await this.downloadInput(rawValue)\n } catch (e) {\n return { status: 400, error: `var '${k}': ${extractErrorMessage(e)}` }\n }\n }\n const err = applyVarPayload(varDef, value)\n if (err != null) return { status: 400, error: err }\n }\n\n // 3. image vars must point at real files BEFORE anything is queued\n for (const [k, varDef] of varMap) {\n if (varDef instanceof ImageVar && varDef.isSet() && !existsSync(varDef.absPath()))\n return { status: 400, error: `image var '${k}': file not found: ${varDef.absPath()}` }\n }\n\n // 4. seed policy (architecture item 12): payload wins; '?' rerolls;\n // '+'/'-' continue from the last SERVED value; '=' keeps the draft value\n for (const [k, varDef] of varMap) {\n if (!(varDef instanceof SeedVar)) continue\n const stateKey = `${mod.key}/${draft}/${k}`\n if (!(k in payload)) {\n if (varDef.mode === '?') varDef.randomize()\n else if (varDef.mode === '+' || varDef.mode === '-') {\n const last = this.seedState.get(stateKey)\n if (last != null) varDef.set(last + (varDef.mode === '+' ? 1 : -1))\n }\n }\n this.seedState.set(stateKey, varDef.value)\n seeds[k] = varDef.value\n }\n\n // 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex\n try {\n return { execution: await this.starter(mod) }\n } catch (e) {\n if (e instanceof ImageVarEmptyError) return { status: 400, error: e.message }\n return { status: 500, error: extractErrorMessage(e) }\n }\n }\n\n /** serialize fn per module key; the stored chain never rejects */\n private exclusive<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = this.chains.get(key) ?? Promise.resolve()\n const next = prev.then(fn)\n this.chains.set(\n key,\n next.catch(() => {}),\n )\n return next\n }\n\n /** payload image urls land as local files under outputs/serve-inputs/ */\n private async downloadInput(url: string): Promise<string> {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`download failed (http ${res.status}): ${url}`)\n const bytes = new Uint8Array(await res.arrayBuffer())\n const name = basename(new URL(url).pathname) || 'input'\n const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${name}`)\n mkdirSync(dirname(abs), { recursive: true })\n writeFileSync(abs, bytes)\n return abs\n }\n}\n","// `comfy-ts serve [dir | module.cflow.ts] [--port N] [--bind ADDR]`\n// drafts as a local HTTP generation API — agent/architecture.md item 12\nimport { statSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { pathToFileURL } from 'node:url'\nimport { resolve } from 'pathe'\nimport { scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'\nimport { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'\nimport { draftKeyForFile } from 'src/cli/tui/state/DraftsSt.ts'\nimport { describeVar, renderDescriptorLine } from 'src/cli/serve/describeVar.ts'\nimport { ServeApp, type ServeModule } from 'src/cli/serve/ServeApp.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\n\nconst DEFAULT_PORT = 8288\nconst BODY_CAP = 10_000_000\n\nfunction parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {\n let target: string | undefined\n let port = DEFAULT_PORT\n let bind = '127.0.0.1'\n for (let i = 0; i < args.length; i++) {\n const a = args[i]\n if (a === '--port') {\n const n = Number(args[++i])\n if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` }\n port = n\n } else if (a === '--bind') {\n const b = args[++i]\n if (b == null) return { error: '--bind expects an address' }\n bind = b\n } else if (a != null && a.startsWith('--')) return { error: `unknown flag '${a}'` }\n else if (a != null) {\n if (target != null) return { error: `one target only (got '${target}' and '${a}')` }\n target = a\n }\n }\n return { target, port, bind }\n}\n\n/** node:http glue around ServeApp.handle — exported so tests can drive a real socket */\nexport function makeRequestListener(app: ServeApp): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n // local bridge, no auth by design: open CORS so browser frontends can call it\n const cors = {\n 'access-control-allow-origin': '*',\n 'access-control-allow-methods': 'GET, POST, OPTIONS',\n 'access-control-allow-headers': 'content-type, accept',\n }\n const chunks: Buffer[] = []\n let size = 0\n let overflow = false\n req.on('error', (e) => console.error(`[serve] request stream error: ${extractErrorMessage(e)}`))\n req.on('data', (c: Buffer) => {\n if (overflow) return\n size += c.length\n if (size > BODY_CAP) {\n // answer NOW: a destroyed request never emits 'end'\n overflow = true\n res.writeHead(413, { 'content-type': 'application/json', ...cors })\n res.end(JSON.stringify({ error: 'payload too large' }), () => req.destroy())\n } else chunks.push(c)\n })\n req.on('end', () => {\n if (overflow) return\n if (req.method === 'OPTIONS') {\n res.writeHead(204, cors)\n res.end()\n return\n }\n app.handle({\n method: req.method ?? 'GET',\n url: req.url ?? '/',\n accept: req.headers.accept,\n body: Buffer.concat(chunks).toString('utf8'),\n })\n .then((reply) => {\n res.writeHead(reply.status, { 'content-type': reply.contentType, ...cors })\n res.end(reply.body)\n })\n .catch((e: unknown) => {\n // handle() catches internally; this guards the response write itself\n console.error(`[serve] response write failed: ${extractErrorMessage(e)}`)\n res.destroy()\n })\n })\n }\n}\n\nexport async function runServe(args: string[]): Promise<number> {\n const parsed = parseArgs(args)\n if ('error' in parsed) {\n console.error(`[comfy-ts serve] ${parsed.error}`)\n return 1\n }\n\n // discovery: explicit file → that module only; dir/no-arg → scan, WITHOUT\n // the bundled examples (serve is for the user's tuned drafts)\n const target = resolve(parsed.target ?? '.')\n let files: string[]\n try {\n files = statSync(target).isDirectory() ? scanCflowFiles(target) : [target]\n } catch {\n console.error(`[comfy-ts serve] no such file or directory: ${target}`)\n return 1\n }\n if (files.length === 0) {\n console.error(`[comfy-ts serve] no *.cflow.ts modules under ${target}`)\n return 1\n }\n\n const modules: ServeModule[] = []\n const loadErrors: Record<string, string> = {}\n for (const file of files) {\n try {\n const mod: Record<string, unknown> = await import(pathToFileURL(file).href)\n const dw = findDefinedWorkflow(mod)\n if (dw == null) throw new Error('exports no DefinedWorkflow')\n const key = draftKeyForFile(file)\n const clash = modules.find((m) => m.key === key)\n if (clash != null) throw new Error(`module key '${key}' already taken by ${clash.file}`)\n modules.push({ key, file, dw })\n } catch (e) {\n loadErrors[file] = extractErrorMessage(e)\n console.error(`[comfy-ts serve] ✗ ${file}: ${loadErrors[file]}`)\n }\n }\n if (modules.length === 0) {\n console.error('[comfy-ts serve] every module failed to load — nothing to serve')\n return 1\n }\n\n const app = new ServeApp(modules, { loadErrors })\n printStartup(app, parsed.bind, parsed.port)\n\n const server = createServer(makeRequestListener(app))\n\n server.on('error', (e) => {\n console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`)\n process.exitCode = 1\n server.close()\n })\n server.listen(parsed.port, parsed.bind)\n\n // stays up until the process is interrupted or the server dies\n return new Promise<number>((resolveExit) => {\n server.on('close', () => resolveExit(typeof process.exitCode === 'number' ? process.exitCode : 0))\n })\n}\n\nfunction printStartup(app: ServeApp, bind: string, port: number): void {\n const base = `http://${bind}:${port}`\n console.log(`comfy-ts serve · ${app.modules.length} workflow(s) · ${base}/`)\n if (bind !== '127.0.0.1' && bind !== 'localhost')\n console.log(`⚠️ bound to ${bind} — this API has NO AUTH and runs workflows on your ComfyUI host`)\n for (const mod of app.modules) {\n console.log(`\\n${mod.key} (host: ${mod.dw.host.data.id})`)\n for (const draft of app.draftsFor(mod))\n console.log(` POST ${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(draft)}`)\n const entries = mod.dw.entries()\n const nameWidth = Math.max(...entries.map(([n]) => n.length), 4)\n for (const [name, varDef] of entries) console.log(renderDescriptorLine(name, describeVar(varDef), nameWidth))\n }\n const firstMod = app.modules[0]\n if (firstMod != null)\n console.log(\n `\\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`,\n )\n console.log(`docs: GET ${base}/drafts (json index of everything above)`)\n}\n"],"mappings":";;;;;;;;AA+BA,SAAS,UAAU,MAA8C;CAC9D,IAAI,KAAK,OAAO,QAAQ,KAAK,OAAO,MAAM,OAAO;CACjD,OAAO,KAAK,KAAK,OAAO,KAAK,IAAI,KAAK,OAAO,IAAI;AACpD;AAEA,SAAgB,YAAY,QAA+B;CACxD,MAAM,OAAO;EAAE,MAAM,OAAO;EAAM,OAAO,OAAO;EAAO,SAAS,OAAO;CAAa;CACpF,IAAI,kBAAkB,WAAW,OAAO;E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