comfy-ts 2.6.0 → 2.8.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 (101) hide show
  1. package/README.md +22 -13
  2. package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
  3. package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
  4. package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
  5. package/dist/LogsSt-DFxzQfDc.js.map +1 -0
  6. package/dist/cli.js +8 -6
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +288 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +128 -7
  11. package/dist/index.d.ts +128 -7
  12. package/dist/index.js +286 -37
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-_nrvJYyt.js +1948 -0
  15. package/dist/run-serve-_nrvJYyt.js.map +1 -0
  16. package/dist/{run-tui-idFhdO4f.js → run-tui-BPw-SZYW.js} +107 -158
  17. package/dist/run-tui-BPw-SZYW.js.map +1 -0
  18. package/dist/serve-web.js +434 -81
  19. package/dist/{state-C90kdjtB.js → state-B-boDz-Z.js} +184 -45
  20. package/dist/state-B-boDz-Z.js.map +1 -0
  21. package/dist/web.d.ts +112 -7
  22. package/dist/web.js +239 -36
  23. package/dist/web.js.map +1 -1
  24. package/examples/README.md +1 -0
  25. package/examples/comfy-cloud/sdk.d.ts +4066 -321
  26. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
  27. package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
  28. package/examples/web/tsconfig.json +7 -1
  29. package/extra/README.md +32 -0
  30. package/extra/comfyui-textgen-stream/README.md +35 -0
  31. package/extra/comfyui-textgen-stream/__init__.py +166 -0
  32. package/extra/scripts/fetch_text_encoder.py +137 -0
  33. package/package.json +6 -3
  34. package/src/cli/comfy-ts-cli.ts +4 -2
  35. package/src/cli/serve/ServeApp.ts +825 -43
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  39. package/src/cli/serve/run-serve.ts +58 -29
  40. package/src/cli/serve/serveSettings.ts +86 -0
  41. package/src/cli/serve/startupPrint.ts +111 -0
  42. package/src/cli/serve/web/api.ts +120 -1
  43. package/src/cli/serve/web/components/App.tsx +61 -22
  44. package/src/cli/serve/web/components/Gallery.tsx +243 -30
  45. package/src/cli/serve/web/components/Icon.tsx +160 -0
  46. package/src/cli/serve/web/components/PromptEnhancer.tsx +85 -38
  47. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  48. package/src/cli/serve/web/components/VarsForm.tsx +440 -80
  49. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  50. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  51. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  52. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  53. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  54. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  55. package/src/cli/serve/web/llm.ts +254 -0
  56. package/src/cli/serve/web/logWeb.ts +6 -0
  57. package/src/cli/serve/web/state/EnhancerSt.ts +261 -157
  58. package/src/cli/serve/web/state/FormSt.ts +70 -18
  59. package/src/cli/serve/web/state/RunSt.ts +22 -1
  60. package/src/cli/serve/web/state/WebSt.ts +542 -13
  61. package/src/cli/serve/web/state/lightbox.ts +44 -0
  62. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  63. package/src/cli/serve/web/state/payload.ts +44 -2
  64. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  65. package/src/cli/serve/web/styles.ts +415 -57
  66. package/src/cli/serve/web/tsconfig.json +4 -0
  67. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  68. package/src/cli/tui/components/StatusBar.tsx +14 -1
  69. package/src/cli/tui/components/TuiApp.tsx +5 -2
  70. package/src/cli/tui/state/HostSt.ts +3 -2
  71. package/src/cli/tui/state/PickerSt.ts +48 -2
  72. package/src/cli/tui/state/TreeSt.ts +1 -1
  73. package/src/cli/tui/state/TuiSt.ts +2 -1
  74. package/src/coreExports.ts +8 -1
  75. package/src/graph/ComfyNode.ts +58 -1
  76. package/src/host/ComfyHost.ts +13 -2
  77. package/src/host/ComfyManager.ts +31 -13
  78. package/src/host/loraInfoCache.ts +35 -1
  79. package/src/host/loraManagerApi.ts +94 -0
  80. package/src/index.ts +2 -0
  81. package/src/promptEnhancers.ts +102 -0
  82. package/src/runner/ComfyExecution.ts +61 -6
  83. package/src/runner/ComfyWorkflow.ts +18 -4
  84. package/src/runner/ComfyWsApi.ts +3 -0
  85. package/src/runner/describePromptRejection.ts +34 -0
  86. package/src/sdk-generator/ComfySchema.ts +17 -4
  87. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  88. package/src/state.ts +6 -0
  89. package/src/utils/ansi.ts +13 -0
  90. package/src/utils/matchesRegex.ts +13 -0
  91. package/src/utils/safeName.ts +29 -0
  92. package/src/utils/stringMap.ts +9 -0
  93. package/src/vars/ComfyVars.ts +61 -10
  94. package/src/vars/presets.ts +17 -0
  95. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  96. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  97. package/dist/run-serve-CVu39RNd.js +0 -1002
  98. package/dist/run-serve-CVu39RNd.js.map +0 -1
  99. package/dist/run-tui-idFhdO4f.js.map +0 -1
  100. package/dist/state-C90kdjtB.js.map +0 -1
  101. package/src/cli/serve/web/openrouter.ts +0 -142
@@ -0,0 +1,102 @@
1
+ // the master prompts of the web ui's prompt enhancer, as FILES:
2
+ // `.comfy-ts/prompt-enhancers/<name>.md`, the drafts model applied to prose.
3
+ // markdown, not json: these are hand-edited paragraphs, and a json string field
4
+ // would be one escaped line. The FILENAME is the identity (a rename is a write
5
+ // plus a delete); validStoreName is the same gate the draft routes use.
6
+ // NODE-ONLY (fs): the web entry never touches this folder, and a workflow reads
7
+ // it through promptEnhancerPresets() to offer the same texts as var presets.
8
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
9
+ import { join } from 'pathe'
10
+ import { validStoreName } from 'src/utils/safeName.ts'
11
+ import type { VarPresetSpec } from 'src/vars/presets.ts'
12
+
13
+ const EXT = '.md'
14
+
15
+ export type PromptEnhancer = { name: string; text: string }
16
+
17
+ export function promptEnhancersDir(): string {
18
+ return comfyts.resolveFromPromptEnhancers('')
19
+ }
20
+
21
+ function promptEnhancerPath(name: string): string | null {
22
+ const safe = validStoreName(name)
23
+ return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`)
24
+ }
25
+
26
+ /** the shipped starting point. It is a FILE from the first read on, so it can be edited
27
+ * on disk like everything else, the browser ships no copy of this text */
28
+ const SEED: PromptEnhancer = {
29
+ name: 'refine-krea2-prompt',
30
+ text: `You rewrite image prompts for krea2 turbo, a distilled 8 step text to image model whose text encoder reads flowing natural language. Long detailed prompts give it the best images. Your job is to serve the VISION behind the user's line: take what they wrote and expand it into the picture they were already imagining but did not type.
31
+
32
+ Rewrite it into ONE paragraph a reader could picture with their eyes closed:
33
+
34
+ - every subject, action, color and spatial relation the user wrote survives, in their own words wherever those words already work. Nothing is dropped, nothing is swapped for something easier.
35
+ - expand the vision, never replace it. Add the visual facts a camera would have to resolve anyway: what each subject looks like, lighting, palette, material and texture, camera angle and distance, framing and composition, background, depth of field, mood, and the signature of the medium itself (visible brushstrokes, film grain, cel shading, stippling, halftone, airbrush gradients, paper texture).
36
+ - choose the style before you write, and keep the choosing invisible. Weigh two or three mediums and lighting setups, pick the one that best serves the input, then write only the result. If they named a medium (photo of, illustration of, 3D render of, painting of, sketch of), that medium is fixed.
37
+ - attach every attribute to its own subject, so nothing bleeds: one clause per figure carrying its features, clothes, pose and action. Spatial words stay grounded: left foreground, upper center, behind, resting on, knee deep in.
38
+ - an input that is already dense gets polished and finished, not inflated. Keep its phrasing and its direction, add only what is genuinely missing.
39
+ - plain descriptive english. Flowing sentences and comma separated descriptive clauses both read well; disconnected keyword soup does not. No praise words, never "masterpiece", "8k", "highly detailed", "award winning", "trending on". The model is steered by what you name, not by what you forbid.
40
+ - text that must appear inside the image is spelled out in "quotes", exactly as it should be rendered.
41
+ - roughly 60 to 150 words, one paragraph, no lists, no headings, no quotes around the result itself.
42
+ - keep any "// " comment line and any "- " negative line from the input verbatim, each on its own line.
43
+
44
+ Answer with the rewritten prompt and nothing else: no preamble, no explanation.
45
+ `,
46
+ }
47
+
48
+ /** seeds ONCE, on an absent folder, then lists. An emptied folder stays empty: the seed is a
49
+ * starting point, not a file the store keeps restoring */
50
+ export function listPromptEnhancers(): PromptEnhancer[] {
51
+ if (!existsSync(promptEnhancersDir())) writePromptEnhancer(SEED.name, SEED.text)
52
+ return readPromptEnhancers()
53
+ }
54
+
55
+ /** the PURE read: no seeding, no writing. What a workflow calls at define time, since importing
56
+ * a module must never create files in someone's project */
57
+ export function readPromptEnhancers(): PromptEnhancer[] {
58
+ const dir = promptEnhancersDir()
59
+ if (!existsSync(dir)) return []
60
+ const out: PromptEnhancer[] = []
61
+ for (const file of readdirSync(dir).sort()) {
62
+ if (!file.endsWith(EXT)) continue
63
+ const name = file.slice(0, -EXT.length)
64
+ if (validStoreName(name) == null) continue
65
+ // one unreadable entry (a DIRECTORY called *.md, a permission problem) must not take the
66
+ // whole route down: it is skipped loudly, the rest still list
67
+ try {
68
+ out.push({ name, text: readFileSync(join(dir, file), 'utf8') })
69
+ } catch (e) {
70
+ console.error(`[serve] prompt enhancer '${name}' unreadable, skipped:`, e)
71
+ }
72
+ }
73
+ return out
74
+ }
75
+
76
+ /**
77
+ * the same master prompts, shaped for `v.text(x, { presets })` / `v.prompt`: file name → text.
78
+ * The point is that ONE library of texts serves the ✨ enhancer and every var that wants them,
79
+ * so a paragraph you tuned in the panel is offered by the workflow too, with no copy.
80
+ * Empty when the folder is absent, so a var keeps whatever presets it declares inline.
81
+ */
82
+ export function promptEnhancerPresets(): VarPresetSpec {
83
+ const out: VarPresetSpec = {}
84
+ for (const e of readPromptEnhancers()) out[e.name] = e.text
85
+ return out
86
+ }
87
+
88
+ export function writePromptEnhancer(name: string, text: string): string | null {
89
+ const path = promptEnhancerPath(name)
90
+ if (path == null) return null
91
+ mkdirSync(promptEnhancersDir(), { recursive: true })
92
+ writeFileSync(path, text)
93
+ return path
94
+ }
95
+
96
+ /** a missing file is still a success: the caller asked for it to be gone, and it is */
97
+ export function deletePromptEnhancer(name: string): boolean {
98
+ const path = promptEnhancerPath(name)
99
+ if (path == null) return false
100
+ if (existsSync(path)) rmSync(path)
101
+ return true
102
+ }
@@ -36,10 +36,24 @@ export type ComfyExecutionData = {
36
36
  status?: ComfyExecutionStatus | null
37
37
  }
38
38
 
39
+ /** one text output as an output node published it (`nodeKey` is null when the node left the snapshot) */
40
+ export type ComfyTextOutput = {
41
+ nodeId: ComfyNodeId
42
+ nodeKey: string | null
43
+ text: string
44
+ }
45
+
39
46
  export type ExecutionProgress = ProgressReport & {
40
47
  promptId: PromptID
41
48
  nodeName: string | null
42
49
  elapsedMs: number
50
+ /** the executing node's OWN counter, in its own unit: sampler steps, or generated
51
+ * tokens on a text node. Null between nodes. The global percent normalizes this away,
52
+ * and the unit is the only live detail worth reading on a long node */
53
+ nodeProgress: { value: number; max: number } | null
54
+ /** the executing node's live display text, when it publishes one. A streaming generator
55
+ * puts its partial answer here every few tokens */
56
+ progressText: string | null
43
57
  }
44
58
 
45
59
  export class ComfyExecution {
@@ -96,6 +110,8 @@ export class ComfyExecution {
96
110
  promptId: this.data.id,
97
111
  nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,
98
112
  elapsedMs: Date.now() - this.startedAt,
113
+ nodeProgress: this.workflow.currentExecutingNode?.progress ?? null,
114
+ progressText: this.progressText,
99
115
  }
100
116
  }
101
117
 
@@ -108,17 +124,26 @@ export class ComfyExecution {
108
124
  const filled = Math.round((p.percent / 100) * width)
109
125
  const bar = '█'.repeat(filled) + '░'.repeat(width - filled)
110
126
  const node = p.nodeName ? ` · ${p.nodeName}` : ''
111
- const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1000).toFixed(0)}s`
112
- if (line === this._lastLoggedLine) return
113
- this._lastLoggedLine = line
114
- if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`)
115
- else console.log(line)
127
+ // the node's own counter: sampler steps, or generated tokens. Core TextGenerate
128
+ // publishes no partial text, so on it this is the only thing that moves
129
+ const count = p.nodeProgress ? ` ${p.nodeProgress.value}/${p.nodeProgress.max}` : ''
130
+ const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node}${count} · ${(p.elapsedMs / 1000).toFixed(0)}s`
131
+ // a streaming node's newest words, on the same line: the run stays ONE line, and what
132
+ // the model is writing is the thing worth watching on it
133
+ const tail = p.progressText?.replaceAll('\n', ' ').trimEnd().slice(-60)
134
+ const full = tail == null || tail === '' ? line : `${line} · …${tail}`
135
+ if (full === this._lastLoggedLine) return
136
+ this._lastLoggedLine = full
137
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${full}`)
138
+ else console.log(full)
116
139
  }
117
140
 
118
141
  private finishProgressLine(): void {
119
142
  if (!this.logProgress) return
120
143
  const p = this.progress
121
- const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${this.images.length} image(s)`
144
+ const outputs = [`${this.images.length} image(s)`]
145
+ if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`)
146
+ const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${outputs.join(' · ')}`
122
147
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`)
123
148
  else console.log(line)
124
149
  }
@@ -195,6 +220,13 @@ export class ComfyExecution {
195
220
  /** update execution list */
196
221
  private onExecuted = (msg: WsMsgExecuted): void => {
197
222
  const promptNodeID = msg.data.node
223
+ // a STRING output reaches the client ONLY through an output node's ui
224
+ // payload (PreviewAny), never through the prompt result
225
+ for (const entry of msg.data.output?.text ?? []) {
226
+ if (typeof entry !== 'string') continue
227
+ const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null
228
+ this.texts.push({ nodeId: promptNodeID, nodeKey, text: entry })
229
+ }
198
230
  const images = msg.data.output?.images
199
231
  if (images) {
200
232
  for (const img of images) {
@@ -375,6 +407,29 @@ export class ComfyExecution {
375
407
  /** images retrieved for this execution, in arrival order (final once `done` resolves) */
376
408
  images: MediaImage[] = []
377
409
 
410
+ /** text outputs emitted for this execution, in arrival order (final once `done` resolves) */
411
+ texts: ComfyTextOutput[] = []
412
+
413
+ /** live display text per node WHILE it runs, newest wins (`send_progress_text` is a
414
+ * replacement, not a delta). This is the only channel carrying text DURING a node: a
415
+ * generator that streams its tokens shows up here, and nowhere in the final outputs */
416
+ progressTexts: Map<string, string> = new Map()
417
+
418
+ /** the node that most recently published live text — what "watch it work" means */
419
+ progressText: string | null = null
420
+
421
+ /** @internal a live-text frame for one node */
422
+ onProgressText(p: { nodeId: string; text: string }): void {
423
+ this.progressTexts.set(p.nodeId, p.text)
424
+ this.progressText = p.text
425
+ this.emitProgress()
426
+ }
427
+
428
+ /** the last text output, the one a single-generator workflow means by "the result" */
429
+ get text(): string | null {
430
+ return this.texts.at(-1)?.text ?? null
431
+ }
432
+
378
433
  update(data: Partial<ComfyExecutionData>): void {
379
434
  Object.assign(this.data, data)
380
435
  }
@@ -1,4 +1,5 @@
1
1
  import { nanoid } from 'nanoid'
2
+ import { describePromptRejection } from 'src/runner/describePromptRejection.ts'
2
3
  import { join } from 'pathe'
3
4
  import { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'
4
5
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
@@ -354,6 +355,13 @@ export class ComfyWorkflow<ID extends string = string> {
354
355
 
355
356
  /** send the workflow; returns the live execution (await `execution.done` yourself) */
356
357
  start = async (p: RunSettings = {}): Promise<ComfyExecution> => {
358
+ // without a ws the prompt still RUNS on the host, but its messages route to a session
359
+ // that is not ours, so `execution.done` never settles: a silent forever-hang, the one
360
+ // failure mode with no error to read. DefinedWorkflow.run() connects for you
361
+ if (this.host.ws == null)
362
+ throw new Error(
363
+ `🔴 host '${this.host.data.id}' was never connected — call \`await host.connect()\` before running a workflow`,
364
+ )
357
365
  this.resetRunState()
358
366
  // snapshot: exactly what runs, frozen at send time (the live workflow stays editable)
359
367
  const snapshot: ExecutionSnapshot = {
@@ -387,12 +395,18 @@ export class ComfyWorkflow<ID extends string = string> {
387
395
  headers: { 'Content-Type': 'application/json' },
388
396
  body: JSON.stringify(out),
389
397
  })
390
- const promptInfoJson = await res.json()
391
- const promptInfo: PromptInfo = softValidate(PromptInfo_ark, promptInfoJson)
392
-
398
+ const promptInfoJson: unknown = await res.json()
399
+ // a REJECTED prompt is not a malformed success: ComfyUI answers non-200 with its own
400
+ // reason and no prompt_id, so validating first reported "prompt_id must be a string"
401
+ // and threw away the sentence that says which node and which value it refused
393
402
  if (res.status !== 200) {
394
- throw new InvalidPromptError('ComfyUI /prompt request failed', snapshot, promptInfo)
403
+ throw new InvalidPromptError(
404
+ `ComfyUI refused the prompt: ${describePromptRejection(promptInfoJson)}`,
405
+ snapshot,
406
+ promptInfoJson,
407
+ )
395
408
  }
409
+ const promptInfo: PromptInfo = softValidate(PromptInfo_ark, promptInfoJson)
396
410
  // settings + snapshot go through the constructor: the ctor flushes ws
397
411
  // messages that raced ahead, and those handlers need the settings
398
412
  const execution = new ComfyExecution(
@@ -64,6 +64,9 @@ const tempScope = scope({
64
64
  output: {
65
65
  'previews?': [{ filepath: 'string' }, '[]'],
66
66
  'images?': 'ComfyImageInfo[]',
67
+ // ui payload of a text output node (PreviewAny, and how TextGenerate
68
+ // results reach the client); entries are soft, non-strings are dropped
69
+ 'text?': 'unknown[]',
67
70
  },
68
71
  prompt_id: 'PromptID',
69
72
  },
@@ -0,0 +1,34 @@
1
+ // ComfyUI's own words for a refused prompt. The body carries `error` (what went wrong overall)
2
+ // and `node_errors` (per node, with the offending value), and those sentences are the only
3
+ // thing that says WHICH input the host would not take.
4
+ import { isRecord } from 'src/utils/isRecord.ts'
5
+
6
+ function str(v: unknown): string {
7
+ return typeof v === 'string' ? v.trim() : ''
8
+ }
9
+
10
+ export function describePromptRejection(body: unknown): string {
11
+ if (!isRecord(body)) return 'no reason given'
12
+ const parts: string[] = []
13
+ const err = body['error']
14
+ if (isRecord(err)) {
15
+ const head = str(err['message'])
16
+ const detail = str(err['details'])
17
+ if (head !== '') parts.push(detail === '' ? head : `${head} (${detail})`)
18
+ }
19
+ const nodes = body['node_errors']
20
+ if (isRecord(nodes)) {
21
+ for (const [nodeId, raw] of Object.entries(nodes)) {
22
+ if (!isRecord(raw)) continue
23
+ const list = raw['errors']
24
+ if (!Array.isArray(list)) continue
25
+ for (const e of list) {
26
+ if (!isRecord(e)) continue
27
+ const detail = str(e['details'])
28
+ const msg = str(e['message'])
29
+ parts.push(`node ${nodeId}: ${[msg, detail].filter((x) => x !== '').join(' — ')}`)
30
+ }
31
+ }
32
+ }
33
+ return parts.length === 0 ? 'no reason given' : parts.join(' · ')
34
+ }
@@ -1,4 +1,5 @@
1
1
  import { sha1HexOfString } from 'src/utils/sha1.ts'
2
+ import { statelessRegex } from 'src/utils/matchesRegex.ts'
2
3
  import { getUnionNameBasedOnFirstFoundEnumName } from 'src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts'
3
4
  import { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'
4
5
  import { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
@@ -238,13 +239,24 @@ export class ComfySchema {
238
239
  // (instances are `<name>.<inst>` link slots) — never required, and
239
240
  // its template sub-input slot type registers like any slot so
240
241
  // codegen can type the dotted instance keys (agent/sdk-codegen.md)
241
- const isAutogrowContainer =
242
- typeof slotType === 'string' &&
243
- classifyWidgetInput({ name: ipt.name, type: slotType, opts: slotOpts }).kind === 'dynamic-container'
242
+ const widgetKind =
243
+ typeof slotType === 'string'
244
+ ? classifyWidgetInput({ name: ipt.name, type: slotType, opts: slotOpts })
245
+ : null
246
+ const isAutogrowContainer = widgetKind?.kind === 'dynamic-container'
244
247
  if (isAutogrowContainer) {
245
248
  const instType = containerInstanceSlotType(slotOpts)
246
249
  if (instType != null) this.knownSlotTypes.add(asComfyNodeSlotTypeName(instType))
247
250
  }
251
+ // dynamic combo: a branch input is typed by its dotted prompt key,
252
+ // so its slot type must register like any slot (agent/sdk-codegen.md)
253
+ if (widgetKind?.kind === 'dynamic-combo') {
254
+ for (const opt of widgetKind.options) {
255
+ for (const entry of opt.inputs) {
256
+ if (typeof entry.type === 'string') this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type))
257
+ }
258
+ }
259
+ }
248
260
 
249
261
  node.inputs.push({
250
262
  slotName: inputSlotName,
@@ -351,7 +363,8 @@ export class ComfySchema {
351
363
  /** all loras on the host, optionally narrowed by a regex */
352
364
  getLoras = (filter?: RegExp): string[] => {
353
365
  const all = this.stringValues('LoraLoader.lora_name')
354
- return filter == null ? all : all.filter((n) => filter.test(n))
366
+ const stateless = filter == null ? null : statelessRegex(filter)
367
+ return stateless == null ? all : all.filter((n) => stateless.test(n))
355
368
  }
356
369
 
357
370
  hasImage(imgName: string): imgName is ComfyImageName {
@@ -4,7 +4,46 @@ import { escapeJSKey } from 'src/utils/escapeJSKey.ts'
4
4
  import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
5
5
 
6
6
  import { type ComfyNodeSchema, wrapQuote } from 'src/sdk-generator/ComfyNodeSchema.ts'
7
- import { classifySchemaInput, containerInstanceSlotType } from 'src/sdk-generator/inputWidgetKind.ts'
7
+ import {
8
+ classifySchemaInput,
9
+ containerInstanceSlotType,
10
+ isRecord,
11
+ type DynamicComboOption,
12
+ type RawInputSpecEntry,
13
+ } from 'src/sdk-generator/inputWidgetKind.ts'
14
+
15
+ const isScalar = (x: unknown): x is string | number | boolean =>
16
+ typeof x === 'string' || typeof x === 'number' || typeof x === 'boolean'
17
+
18
+ /** a dynamic-combo branch input, typed the way its dotted prompt key is filled: inline enums
19
+ * and COMBO option lists become literal unions, everything else stays a named slot */
20
+ const branchInputType = (entry: RawInputSpecEntry): string => {
21
+ const opts = isRecord(entry.opts) ? entry.opts : null
22
+ const literals = Array.isArray(entry.type) ? entry.type : Array.isArray(opts?.['options']) ? opts['options'] : []
23
+ const scalars = literals.filter(isScalar)
24
+ if (scalars.length > 0) return scalars.map((o) => JSON.stringify(o)).join(' | ')
25
+ if (typeof entry.type === 'string') return `Accepts[${JSON.stringify(entry.type)}]`
26
+ return 'string | number | boolean'
27
+ }
28
+
29
+ /** `& ({key:'a'; 'name.x'?: …} | {key:'b'})` — one member per branch, so a key from a branch
30
+ * you did not select is a type error. Branch fields are optional: ComfyNode fills them
31
+ * from the schema at serialization (agent/architecture.md, dynamic-combo fill) */
32
+ const dynamicComboUnion = (p: {
33
+ name: string
34
+ nameEscaped: string
35
+ options: DynamicComboOption[]
36
+ keyOptional: boolean
37
+ }): string => {
38
+ const members = p.options.map((opt) => {
39
+ const fields = opt.inputs.map(
40
+ (e) => `${escapeJSKey(`${p.name}.${e.name}`)}?: ${branchInputType(e)}`, //
41
+ )
42
+ const key = `${p.nameEscaped}${p.keyOptional ? '?' : ''}: ${JSON.stringify(opt.key)}`
43
+ return `{ ${[key, ...fields].join('; ')} }`
44
+ })
45
+ return ` & (${members.join(' | ')})`
46
+ }
8
47
 
9
48
  /**
10
49
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
@@ -76,6 +115,9 @@ export function codegenSDK(this: ComfySchema, opts: CodegenOptions): string {
76
115
  b.indent()
77
116
  for (const n of nodes) {
78
117
  p(`${escapeJSKey(n.nodeKey)}: {`)
118
+ // dynamic combos leave the flat body and come back as an intersected
119
+ // union suffix, one member per branch (agent/sdk-codegen.md)
120
+ const comboSuffixes: string[] = []
79
121
  for (const i of n.inputs) {
80
122
  // autogrow container: emit dotted instance keys, never the container
81
123
  // decl itself — the backend prompt input is `<name>.<inst>`, the
@@ -91,6 +133,18 @@ export function codegenSDK(this: ComfySchema, opts: CodegenOptions): string {
91
133
  }
92
134
  continue
93
135
  }
136
+ if (kind.kind === 'dynamic-combo') {
137
+ const optsDyn = typeof i.opts === 'string' ? null : i.opts
138
+ comboSuffixes.push(
139
+ dynamicComboUnion({
140
+ name: i.nameInComfy,
141
+ nameEscaped: i.nameInComfyEscaped,
142
+ options: kind.options,
143
+ keyOptional: optsDyn?.default !== undefined || !i.required,
144
+ }),
145
+ )
146
+ continue
147
+ }
94
148
  const opts_ = typeof i.opts === 'string' ? null : i.opts
95
149
  let type = `Accepts[${JSON.stringify(i.typeName)}]`
96
150
  // COMBO inputs (ComfyUI ≥ 0.3.x) carry literal choices in opts.options
@@ -122,7 +176,7 @@ export function codegenSDK(this: ComfySchema, opts: CodegenOptions): string {
122
176
  const canBeOmmited = opts_?.default !== undefined || !i.required
123
177
  p(` ${i.nameInComfyEscaped}${canBeOmmited ? '?' : ''}: ${type}`)
124
178
  }
125
- p(`},`)
179
+ p(`}${comboSuffixes.join('')},`)
126
180
  }
127
181
  b.deindent()
128
182
  p('}')
package/src/state.ts CHANGED
@@ -95,6 +95,7 @@ export class ComfyTS {
95
95
  * .comfy-ts/hosts/<id>/{object_info.json, embeddings.json, sdk.d.ts}
96
96
  * .comfy-ts/outputs/... generated images & workflows
97
97
  * .comfy-ts/drafts/<workflow-id>/<draft>.json TUI var snapshots (local, gitignored)
98
+ * .comfy-ts/prompt-enhancers/<name>.md serve web ui master prompts (local, gitignored)
98
99
  */
99
100
  baseFolder: AbsolutePath
100
101
  hostsFolder: AbsolutePath
@@ -104,6 +105,11 @@ export class ComfyTS {
104
105
  return asAbsolutePath(join(this.baseFolder, 'drafts', relativePath))
105
106
  }
106
107
 
108
+ /** master prompts of the serve web ui's prompt enhancer — hand-editable markdown */
109
+ resolveFromPromptEnhancers(relativePath: string): AbsolutePath {
110
+ return asAbsolutePath(join(this.baseFolder, 'prompt-enhancers', relativePath))
111
+ }
112
+
107
113
  resolveFromCache(relativePath: string): AbsolutePath {
108
114
  return asAbsolutePath(join(this.baseFolder, 'cache', relativePath))
109
115
  }
package/src/utils/ansi.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  // tiny chalk-compatible terminal styler (chainable), keeps chalk out of the deps
2
2
  const codes = {
3
3
  bold: [1, 22],
4
+ dim: [2, 22],
4
5
  underline: [4, 24],
5
6
  red: [31, 39],
6
7
  green: [32, 39],
7
8
  yellow: [33, 39],
8
9
  blue: [34, 39],
10
+ cyan: [36, 39],
11
+ gray: [90, 39],
9
12
  greenBright: [92, 39],
10
13
  } as const
11
14
 
@@ -31,3 +34,13 @@ const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]|\x1b[A-Za-z]/g
31
34
  export function stripAnsi(s: string): string {
32
35
  return s.replace(ANSI_RE, '')
33
36
  }
37
+
38
+ /** colors only where they can be seen: a real terminal, NO_COLOR unset, TERM not 'dumb'.
39
+ * A piped or redirected stdout gets plain text, so `serve > log` stays greppable */
40
+ export function colorsAvailable(): boolean {
41
+ const env = globalThis.process?.env ?? {}
42
+ if (env.NO_COLOR != null && env.NO_COLOR !== '') return false
43
+ if (env.TERM === 'dumb') return false
44
+ if (env.FORCE_COLOR != null && env.FORCE_COLOR !== '' && env.FORCE_COLOR !== '0') return true
45
+ return globalThis.process?.stdout?.isTTY === true
46
+ }
@@ -0,0 +1,13 @@
1
+ // RegExp.test on a /g or /y regex advances lastIndex, so the same pattern answers differently
2
+ // on consecutive calls. A user-supplied filter is shared by several call sites.
3
+ export function statelessRegex(re: RegExp): RegExp {
4
+ if (!re.global && !re.sticky) return re
5
+ // sticky means "match AT lastIndex": dropping the flag would drop the anchoring too, and a
6
+ // filter written as /krea/y would silently widen from starts-with to contains
7
+ const source = re.sticky ? `^(?:${re.source})` : re.source
8
+ return new RegExp(source, re.flags.replace(/[gy]/g, ''))
9
+ }
10
+
11
+ export function matchesRegex(re: RegExp, value: string): boolean {
12
+ return statelessRegex(re).test(value)
13
+ }
@@ -0,0 +1,29 @@
1
+ // THE name gate for every serve route that turns a url segment into a file path.
2
+ // SECURITY-CRITICAL and deliberately shared: handle() decodes per segment, so
3
+ // `%2F` arrives as a real `/` while the segment count still looks right. One
4
+ // function, because a second regex somewhere else is a second traversal hole.
5
+
6
+ /** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */
7
+ export function validStoreName(raw: string): string | null {
8
+ const name = raw.trim()
9
+ // length cap: past it the fs answers ENAMETOOLONG as a raw 500
10
+ if (name.length > 100) return null
11
+ return /^[\w][\w .-]*$/.test(name) ? name : null
12
+ }
13
+
14
+ /** a save prefix becomes a PATH under outputs/, so every segment goes through the same gate:
15
+ * it cannot climb out, and it cannot be absolute. Lives here, not on ServeApp, because the
16
+ * settings READER validates it too, a hand-written settings file never met the PUT route. */
17
+ export function validSavePrefix(raw: string): string | null {
18
+ const clean = raw.trim().replaceAll('\\', '/')
19
+ if (clean === '') return ''
20
+ // an ABSOLUTE path is refused, not quietly re-rooted: dropping the leading slash turned
21
+ // '/etc' into 'etc' under outputs/, which is safe but is not what the writer asked for
22
+ if (clean.startsWith('/') || /^[a-z]:/i.test(clean)) return null
23
+ // the whole path is capped, not only each segment: 3000 valid two-char segments passed and
24
+ // then broke that module's saving for good with an unopenable path
25
+ if (clean.length > 200) return null
26
+ const segments = clean.split('/').filter((s) => s !== '')
27
+ if (segments.length === 0 || segments.some((s) => validStoreName(s) == null)) return null
28
+ return segments.join('/')
29
+ }
@@ -0,0 +1,9 @@
1
+ // unknown json → a plain record of strings. Every localStorage blob and every settings file
2
+ // crossing into this process needs the same shape check; two copies of it drift.
3
+ export function stringMap(raw: unknown): Record<string, string> {
4
+ const out: Record<string, string> = {}
5
+ if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {
6
+ for (const [k, v] of Object.entries(raw)) if (typeof v === 'string') out[k] = v
7
+ }
8
+ return out
9
+ }