comfy-ts 1.2.0 → 1.3.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.
- package/README.md +40 -0
- package/dist/DefinedWorkflow-gpknV-5f.js +686 -0
- package/dist/DefinedWorkflow-gpknV-5f.js.map +1 -0
- package/dist/DraftsSt-DmA0jWGl.js +434 -0
- package/dist/DraftsSt-DmA0jWGl.js.map +1 -0
- package/dist/cli.js +15 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +132 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +23 -18
- package/dist/index.js +132 -21
- package/dist/index.js.map +1 -1
- package/dist/run-serve-Bn6yIJB0.js +638 -0
- package/dist/run-serve-Bn6yIJB0.js.map +1 -0
- package/dist/{run-tui-BAdizWsO.js → run-tui-BtjaOXRh.js} +244 -440
- package/dist/run-tui-BtjaOXRh.js.map +1 -0
- package/dist/{state-BYbxDgfr.js → state-DKCPy105.js} +130 -698
- package/dist/state-DKCPy105.js.map +1 -0
- package/package.json +3 -2
- package/src/cli/comfy-ts-cli.ts +15 -5
- package/src/cli/serve/ServeApp.ts +378 -0
- package/src/cli/serve/applyVarPayload.ts +119 -0
- package/src/cli/serve/describeVar.ts +74 -0
- package/src/cli/serve/run-serve.ts +169 -0
- package/src/cli/tui/components/StatusBar.tsx +1 -0
- package/src/cli/tui/components/TreePanel.tsx +17 -3
- package/src/cli/tui/components/TuiApp.tsx +7 -2
- package/src/cli/tui/components/VarsPanel.tsx +67 -34
- package/src/cli/tui/imageClipboard.ts +39 -0
- package/src/cli/tui/listWindow.ts +36 -0
- package/src/cli/tui/state/ExecSt.ts +48 -0
- package/src/cli/tui/state/TreeSt.ts +25 -0
- package/src/cli/tui/state/TuiSt.ts +34 -0
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
- package/src/runner/ComfyExecution.ts +21 -4
- package/src/runner/outputPath.ts +75 -0
- package/src/sdk-generator/inputWidgetKind.ts +50 -11
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
- package/src/vars/ComfyVars.ts +8 -0
- package/dist/run-tui-BAdizWsO.js.map +0 -1
- package/dist/state-BYbxDgfr.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "comfy-ts",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"comfyui",
|
|
@@ -85,7 +85,8 @@
|
|
|
85
85
|
"release": "bun scripts/release.ts",
|
|
86
86
|
"release:dry": "bun scripts/release.ts --dry-run",
|
|
87
87
|
"prepublishOnly": "bun run ci && bun run build",
|
|
88
|
-
"tui": "bun src/cli/comfy-ts-cli.ts tui"
|
|
88
|
+
"tui": "bun src/cli/comfy-ts-cli.ts tui",
|
|
89
|
+
"serve": "bun src/cli/comfy-ts-cli.ts serve"
|
|
89
90
|
},
|
|
90
91
|
"rvt": {
|
|
91
92
|
"skip": [
|
package/src/cli/comfy-ts-cli.ts
CHANGED
|
@@ -22,6 +22,12 @@ Usage:
|
|
|
22
22
|
host.defineWorkflow(...)); no arg scans cwd + the examples bundled
|
|
23
23
|
with comfy-ts, an explicit dir/file limits to it (file preselected)
|
|
24
24
|
|
|
25
|
+
comfy-ts serve [dir | workflow-module.ts] [--port 8288] [--bind 127.0.0.1]
|
|
26
|
+
drafts as a local HTTP generation API: POST /generate/<module>/<draft>
|
|
27
|
+
with { ...vars } overriding the draft's values (blocking; raw image
|
|
28
|
+
bytes under Accept: image/*), GET /drafts self-describes every var,
|
|
29
|
+
GET /outputs/... serves the results. No bundled examples, no auth.
|
|
30
|
+
|
|
25
31
|
comfy-ts help
|
|
26
32
|
`
|
|
27
33
|
|
|
@@ -29,19 +35,23 @@ async function main(): Promise<number> {
|
|
|
29
35
|
const [cmd, ...rest] = process.argv.slice(2)
|
|
30
36
|
if (cmd === 'gen') return runGen(rest)
|
|
31
37
|
if (cmd === 'outline') return runOutline(rest)
|
|
32
|
-
if (cmd === 'tui') {
|
|
38
|
+
if (cmd === 'tui' || cmd === 'serve') {
|
|
33
39
|
// .cflow.ts workflow modules need bun: node refuses to strip types under
|
|
34
40
|
// node_modules, exactly where the packaged examples live — and the bin's
|
|
35
|
-
// node shebang means `bunx comfy-ts tui` lands here under NODE. Hop
|
|
36
|
-
// bun when we are not already in it; without bun,
|
|
41
|
+
// node shebang means `bunx comfy-ts tui|serve` lands here under NODE. Hop
|
|
42
|
+
// to bun when we are not already in it; without bun, degrade loudly.
|
|
37
43
|
if (process.versions.bun == null) {
|
|
38
44
|
const self = fileURLToPath(import.meta.url)
|
|
39
|
-
const res = spawnSync('bun', [self,
|
|
45
|
+
const res = spawnSync('bun', [self, cmd, ...rest], { stdio: 'inherit' })
|
|
40
46
|
if (res.error == null) return res.status ?? 1
|
|
41
47
|
console.error(
|
|
42
|
-
`[comfy-ts
|
|
48
|
+
`[comfy-ts ${cmd}] bun not found (${res.error.message}) — continuing under node: the examples packaged in node_modules cannot load here, and your own .cflow.ts modules rely on node's type stripping`,
|
|
43
49
|
)
|
|
44
50
|
}
|
|
51
|
+
if (cmd === 'serve') {
|
|
52
|
+
const { runServe } = await import('src/cli/serve/run-serve.ts')
|
|
53
|
+
return runServe(rest)
|
|
54
|
+
}
|
|
45
55
|
// lazy import: keeps ink/react out of the codegen paths
|
|
46
56
|
const { runTui } = await import('src/cli/tui/run-tui.tsx')
|
|
47
57
|
return runTui(rest)
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// `comfy-ts serve` request handling, transport-free: run-serve owns node:http,
|
|
2
|
+
// tests call handle() directly with an injected starter. Full contract:
|
|
3
|
+
// agent/architecture.md item 12.
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { nanoid } from 'nanoid'
|
|
6
|
+
import { basename, dirname, extname, join, resolve } from 'pathe'
|
|
7
|
+
import { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'
|
|
8
|
+
import { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'
|
|
9
|
+
import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
|
|
10
|
+
import { ImageVar, ImageVarEmptyError, SeedVar } from 'src/vars/ComfyVars.ts'
|
|
11
|
+
import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
|
|
12
|
+
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
13
|
+
|
|
14
|
+
export type ServeModule = { key: string; file: string; dw: DefinedWorkflow }
|
|
15
|
+
|
|
16
|
+
/** structural face of ComfyExecution — tests inject a fake starter */
|
|
17
|
+
export type ServeExecution = {
|
|
18
|
+
done: Promise<unknown>
|
|
19
|
+
status: string
|
|
20
|
+
images: { absPath: string; filename: string }[]
|
|
21
|
+
data: { id: string; error?: unknown }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type ServeStarter = (mod: ServeModule) => Promise<ServeExecution>
|
|
25
|
+
|
|
26
|
+
export type ServeRequest = { method: string; url: string; accept?: string; body?: string }
|
|
27
|
+
export type ServeReply = { status: number; contentType: string; body: string | Uint8Array }
|
|
28
|
+
|
|
29
|
+
/** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex */
|
|
30
|
+
const realStarter: ServeStarter = async (mod) => {
|
|
31
|
+
await mod.dw.host.connect()
|
|
32
|
+
const wf = await mod.dw.build({ advance: true })
|
|
33
|
+
return await wf.start({})
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const CONTENT_TYPES: Record<string, string> = {
|
|
37
|
+
'.png': 'image/png',
|
|
38
|
+
'.jpg': 'image/jpeg',
|
|
39
|
+
'.jpeg': 'image/jpeg',
|
|
40
|
+
'.webp': 'image/webp',
|
|
41
|
+
'.gif': 'image/gif',
|
|
42
|
+
'.mp4': 'video/mp4',
|
|
43
|
+
'.webm': 'video/webm',
|
|
44
|
+
'.json': 'application/json',
|
|
45
|
+
'.txt': 'text/plain',
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function json(status: number, payload: unknown): ServeReply {
|
|
49
|
+
return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const USAGE = [
|
|
53
|
+
'GET /drafts — every served workflow, its drafts and var descriptors',
|
|
54
|
+
'GET /drafts/<module>/<draft> — one draft with its stored values',
|
|
55
|
+
'POST /generate/<module>/<draft> with { ...vars } — run, blocking',
|
|
56
|
+
'POST /generate/<draft> — unqualified, when unambiguous',
|
|
57
|
+
'GET /outputs/<path> — generated files',
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
export class ServeApp {
|
|
61
|
+
private starter: ServeStarter
|
|
62
|
+
/** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it */
|
|
63
|
+
private seedState = new Map<string, number>()
|
|
64
|
+
/** per-module promise chain: vars are shared mutable state, apply→send is exclusive */
|
|
65
|
+
private chains = new Map<string, Promise<unknown>>()
|
|
66
|
+
|
|
67
|
+
constructor(
|
|
68
|
+
public modules: ServeModule[],
|
|
69
|
+
private opts: { starter?: ServeStarter; outputRoot?: string; loadErrors?: Record<string, string> } = {},
|
|
70
|
+
) {
|
|
71
|
+
this.starter = opts.starter ?? realStarter
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private get outputRoot(): string {
|
|
75
|
+
return this.opts.outputRoot ?? comfyts.outputPath
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// #region routing ----------------------------------------------------------
|
|
79
|
+
async handle(req: ServeRequest): Promise<ServeReply> {
|
|
80
|
+
try {
|
|
81
|
+
const path = (req.url.split('?')[0] ?? '/').split('#')[0] ?? '/'
|
|
82
|
+
let segs: string[]
|
|
83
|
+
try {
|
|
84
|
+
segs = path
|
|
85
|
+
.split('/')
|
|
86
|
+
.filter((s) => s !== '')
|
|
87
|
+
.map(decodeURIComponent)
|
|
88
|
+
} catch {
|
|
89
|
+
return json(400, { error: `bad url encoding: ${path}` })
|
|
90
|
+
}
|
|
91
|
+
if (req.method === 'GET') {
|
|
92
|
+
if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return this.replyIndex()
|
|
93
|
+
if (segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
94
|
+
return this.replyDraft(segs[1], segs[2])
|
|
95
|
+
if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
|
|
96
|
+
return json(404, { error: `no route: GET ${path}`, usage: USAGE })
|
|
97
|
+
}
|
|
98
|
+
if (req.method === 'POST' && segs[0] === 'generate') {
|
|
99
|
+
const target = this.resolveDraft(segs.slice(1))
|
|
100
|
+
if ('error' in target) return json(target.status, { error: target.error })
|
|
101
|
+
return await this.generate(target.mod, target.draft, req)
|
|
102
|
+
}
|
|
103
|
+
return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })
|
|
104
|
+
} catch (e) {
|
|
105
|
+
console.error('[serve] request crashed:', e)
|
|
106
|
+
return json(500, { error: extractErrorMessage(e) })
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
moduleByKey(key: string): ServeModule | null {
|
|
111
|
+
return this.modules.find((m) => m.key === key) ?? null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */
|
|
115
|
+
draftsFor(mod: ServeModule): string[] {
|
|
116
|
+
const onDisk = listDraftsForFile(mod.file)
|
|
117
|
+
return ['default', ...onDisk.filter((n) => n !== 'default')]
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private draftExists(mod: ServeModule, draft: string): boolean {
|
|
121
|
+
return draft === 'default' || existsSync(join(draftsDirForFile(mod.file), `${draft}.json`))
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private resolveDraft(segs: string[]): { mod: ServeModule; draft: string } | { error: string; status: number } {
|
|
125
|
+
if (segs.length === 2 && segs[0] != null && segs[1] != null) {
|
|
126
|
+
const mod = this.moduleByKey(segs[0])
|
|
127
|
+
if (mod == null)
|
|
128
|
+
return {
|
|
129
|
+
status: 404,
|
|
130
|
+
error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(', ')}`,
|
|
131
|
+
}
|
|
132
|
+
if (!this.draftExists(mod, segs[1]))
|
|
133
|
+
return {
|
|
134
|
+
status: 404,
|
|
135
|
+
error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(', ')}`,
|
|
136
|
+
}
|
|
137
|
+
return { mod, draft: segs[1] }
|
|
138
|
+
}
|
|
139
|
+
if (segs.length === 1 && segs[0] != null) {
|
|
140
|
+
const draft = segs[0]
|
|
141
|
+
if (this.modules.length === 1 && this.modules[0] != null) {
|
|
142
|
+
const mod = this.modules[0]
|
|
143
|
+
if (!this.draftExists(mod, draft))
|
|
144
|
+
return {
|
|
145
|
+
status: 404,
|
|
146
|
+
error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,
|
|
147
|
+
}
|
|
148
|
+
return { mod, draft }
|
|
149
|
+
}
|
|
150
|
+
const hits = this.modules.filter((m) => this.draftExists(m, draft))
|
|
151
|
+
if (hits.length === 1 && hits[0] != null) return { mod: hits[0], draft }
|
|
152
|
+
if (hits.length === 0) return { status: 404, error: `no module has a draft '${draft}'` }
|
|
153
|
+
return {
|
|
154
|
+
status: 400,
|
|
155
|
+
error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(' or ')}`,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { status: 400, error: 'use POST /generate/<module>/<draft> or /generate/<draft>' }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// #region introspection ----------------------------------------------------
|
|
162
|
+
private describeModule(mod: ServeModule): Record<string, unknown> {
|
|
163
|
+
const vars: Record<string, VarDescriptor> = {}
|
|
164
|
+
for (const [name, varDef] of mod.dw.entries()) vars[name] = describeVar(varDef)
|
|
165
|
+
return {
|
|
166
|
+
module: mod.key,
|
|
167
|
+
file: mod.file,
|
|
168
|
+
host: mod.dw.host.data.id,
|
|
169
|
+
drafts: this.draftsFor(mod),
|
|
170
|
+
routes: this.draftsFor(mod).map(
|
|
171
|
+
(d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`,
|
|
172
|
+
),
|
|
173
|
+
vars,
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private replyIndex(): ServeReply {
|
|
178
|
+
return json(200, {
|
|
179
|
+
server: 'comfy-ts serve',
|
|
180
|
+
usage: USAGE,
|
|
181
|
+
workflows: this.modules.map((m) => this.describeModule(m)),
|
|
182
|
+
...(this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0
|
|
183
|
+
? { loadErrors: this.opts.loadErrors }
|
|
184
|
+
: {}),
|
|
185
|
+
})
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private replyDraft(modKey: string, draft: string): ServeReply {
|
|
189
|
+
const mod = this.moduleByKey(modKey)
|
|
190
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
191
|
+
if (!this.draftExists(mod, draft))
|
|
192
|
+
return json(404, {
|
|
193
|
+
error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,
|
|
194
|
+
})
|
|
195
|
+
return json(200, { ...this.describeModule(mod), draft, values: this.draftValues(mod, draft) })
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
|
|
199
|
+
private draftValues(mod: ServeModule, draft: string): Record<string, unknown> {
|
|
200
|
+
const path = join(draftsDirForFile(mod.file), `${draft}.json`)
|
|
201
|
+
if (existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
|
|
202
|
+
const out: Record<string, unknown> = {}
|
|
203
|
+
for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default
|
|
204
|
+
return out
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// #region outputs ----------------------------------------------------------
|
|
208
|
+
private replyOutput(segs: string[]): ServeReply {
|
|
209
|
+
const abs = resolve(this.outputRoot, ...segs)
|
|
210
|
+
// traversal guard: the resolved path must stay under the output root
|
|
211
|
+
if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + '/'))
|
|
212
|
+
return json(400, { error: 'path escapes the outputs root' })
|
|
213
|
+
if (!existsSync(abs) || !statSync(abs).isFile())
|
|
214
|
+
return json(404, { error: `no such output file: /${segs.join('/')}` })
|
|
215
|
+
const contentType = CONTENT_TYPES[extname(abs).toLowerCase()] ?? 'application/octet-stream'
|
|
216
|
+
return { status: 200, contentType, body: new Uint8Array(readFileSync(abs)) }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private outputUrl(absPath: string): string | null {
|
|
220
|
+
if (!absPath.startsWith(this.outputRoot + '/')) return null
|
|
221
|
+
const rel = absPath.slice(this.outputRoot.length + 1)
|
|
222
|
+
return '/outputs/' + rel.split('/').map(encodeURIComponent).join('/')
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// #region generate ---------------------------------------------------------
|
|
226
|
+
private async generate(mod: ServeModule, draft: string, req: ServeRequest): Promise<ServeReply> {
|
|
227
|
+
let payload: Record<string, unknown> = {}
|
|
228
|
+
if (req.body != null && req.body.trim() !== '') {
|
|
229
|
+
let parsed: unknown
|
|
230
|
+
try {
|
|
231
|
+
parsed = JSON.parse(req.body)
|
|
232
|
+
} catch (e) {
|
|
233
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
|
|
234
|
+
}
|
|
235
|
+
if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
236
|
+
return json(400, { error: 'body must be a json object: { "<var>": value, … }' })
|
|
237
|
+
payload = parsed as Record<string, unknown>
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const t0 = Date.now()
|
|
241
|
+
const seeds: Record<string, number> = {}
|
|
242
|
+
const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds))
|
|
243
|
+
if ('error' in started) return json(started.status, { error: started.error })
|
|
244
|
+
|
|
245
|
+
const execution = started.execution
|
|
246
|
+
console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)
|
|
247
|
+
await execution.done
|
|
248
|
+
const durationMs = Date.now() - t0
|
|
249
|
+
|
|
250
|
+
if (execution.status === 'Failure') {
|
|
251
|
+
console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`)
|
|
252
|
+
return json(500, {
|
|
253
|
+
ok: false,
|
|
254
|
+
module: mod.key,
|
|
255
|
+
draft,
|
|
256
|
+
promptId: execution.data.id,
|
|
257
|
+
durationMs,
|
|
258
|
+
error: execution.data.error ?? 'execution failed',
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
console.log(
|
|
263
|
+
`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${execution.images.length} image(s)`,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
// Accept: image/* → first image's bytes directly (curl -o, <img src>)
|
|
267
|
+
const first = execution.images[0]
|
|
268
|
+
if (req.accept?.includes('image/') && first != null) {
|
|
269
|
+
const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'
|
|
270
|
+
return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return json(200, {
|
|
274
|
+
ok: true,
|
|
275
|
+
module: mod.key,
|
|
276
|
+
draft,
|
|
277
|
+
promptId: execution.data.id,
|
|
278
|
+
durationMs,
|
|
279
|
+
seeds,
|
|
280
|
+
images: execution.images.map((img) => ({
|
|
281
|
+
filename: img.filename,
|
|
282
|
+
url: this.outputUrl(img.absPath),
|
|
283
|
+
absPath: img.absPath,
|
|
284
|
+
})),
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** everything that touches the module's SHARED vars, under the module mutex */
|
|
289
|
+
private async prepareAndStart(
|
|
290
|
+
mod: ServeModule,
|
|
291
|
+
draft: string,
|
|
292
|
+
payload: Record<string, unknown>,
|
|
293
|
+
seeds: Record<string, number>,
|
|
294
|
+
): Promise<{ execution: ServeExecution } | { error: string; status: number }> {
|
|
295
|
+
// 1. reset, then load the draft FRESH from disk (TUI edits between requests apply)
|
|
296
|
+
for (const [, varDef] of mod.dw.entries()) varDef.reset()
|
|
297
|
+
const draftPath = join(draftsDirForFile(mod.file), `${draft}.json`)
|
|
298
|
+
if (existsSync(draftPath)) {
|
|
299
|
+
try {
|
|
300
|
+
const values = JSON.parse(readFileSync(draftPath, 'utf8')) as Record<string, unknown>
|
|
301
|
+
for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k])
|
|
302
|
+
} catch (e) {
|
|
303
|
+
return { status: 500, error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}` }
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// 2. payload overrides (image urls download first, so the var gets a local path)
|
|
308
|
+
const varMap = new Map(mod.dw.entries())
|
|
309
|
+
for (const [k, rawValue] of Object.entries(payload)) {
|
|
310
|
+
const varDef = varMap.get(k)
|
|
311
|
+
if (varDef == null)
|
|
312
|
+
return { status: 400, error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(', ')}` }
|
|
313
|
+
let value = rawValue
|
|
314
|
+
if (varDef instanceof ImageVar && typeof rawValue === 'string' && /^https?:\/\//.test(rawValue)) {
|
|
315
|
+
try {
|
|
316
|
+
value = await this.downloadInput(rawValue)
|
|
317
|
+
} catch (e) {
|
|
318
|
+
return { status: 400, error: `var '${k}': ${extractErrorMessage(e)}` }
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const err = applyVarPayload(varDef, value)
|
|
322
|
+
if (err != null) return { status: 400, error: err }
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// 3. image vars must point at real files BEFORE anything is queued
|
|
326
|
+
for (const [k, varDef] of varMap) {
|
|
327
|
+
if (varDef instanceof ImageVar && varDef.isSet() && !existsSync(varDef.absPath()))
|
|
328
|
+
return { status: 400, error: `image var '${k}': file not found: ${varDef.absPath()}` }
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// 4. seed policy (architecture item 12): payload wins; '?' rerolls;
|
|
332
|
+
// '+'/'-' continue from the last SERVED value; '=' keeps the draft value
|
|
333
|
+
for (const [k, varDef] of varMap) {
|
|
334
|
+
if (!(varDef instanceof SeedVar)) continue
|
|
335
|
+
const stateKey = `${mod.key}/${draft}/${k}`
|
|
336
|
+
if (!(k in payload)) {
|
|
337
|
+
if (varDef.mode === '?') varDef.randomize()
|
|
338
|
+
else if (varDef.mode === '+' || varDef.mode === '-') {
|
|
339
|
+
const last = this.seedState.get(stateKey)
|
|
340
|
+
if (last != null) varDef.set(last + (varDef.mode === '+' ? 1 : -1))
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
this.seedState.set(stateKey, varDef.value)
|
|
344
|
+
seeds[k] = varDef.value
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex
|
|
348
|
+
try {
|
|
349
|
+
return { execution: await this.starter(mod) }
|
|
350
|
+
} catch (e) {
|
|
351
|
+
if (e instanceof ImageVarEmptyError) return { status: 400, error: e.message }
|
|
352
|
+
return { status: 500, error: extractErrorMessage(e) }
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** serialize fn per module key; the stored chain never rejects */
|
|
357
|
+
private exclusive<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
358
|
+
const prev = this.chains.get(key) ?? Promise.resolve()
|
|
359
|
+
const next = prev.then(fn)
|
|
360
|
+
this.chains.set(
|
|
361
|
+
key,
|
|
362
|
+
next.catch(() => {}),
|
|
363
|
+
)
|
|
364
|
+
return next
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** payload image urls land as local files under outputs/serve-inputs/ */
|
|
368
|
+
private async downloadInput(url: string): Promise<string> {
|
|
369
|
+
const res = await fetch(url)
|
|
370
|
+
if (!res.ok) throw new Error(`download failed (http ${res.status}): ${url}`)
|
|
371
|
+
const bytes = new Uint8Array(await res.arrayBuffer())
|
|
372
|
+
const name = basename(new URL(url).pathname) || 'input'
|
|
373
|
+
const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${name}`)
|
|
374
|
+
mkdirSync(dirname(abs), { recursive: true })
|
|
375
|
+
writeFileSync(abs, bytes)
|
|
376
|
+
return abs
|
|
377
|
+
}
|
|
378
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// PURE payload → var application: one POST body value onto one var, per kind.
|
|
2
|
+
// Returns an error message (nothing applied) or null. No fs here — ImageVar
|
|
3
|
+
// url download + existence checks are ServeApp's job.
|
|
4
|
+
import {
|
|
5
|
+
type AnyVar,
|
|
6
|
+
ChoiceVar,
|
|
7
|
+
FloatVar,
|
|
8
|
+
ImageVar,
|
|
9
|
+
IntVar,
|
|
10
|
+
type LoraStrength,
|
|
11
|
+
LorasVar,
|
|
12
|
+
PromptVar,
|
|
13
|
+
SeedVar,
|
|
14
|
+
SizeVar,
|
|
15
|
+
TextVar,
|
|
16
|
+
ToggleVar,
|
|
17
|
+
} from 'src/vars/ComfyVars.ts'
|
|
18
|
+
|
|
19
|
+
function isFiniteNumber(x: unknown): x is number {
|
|
20
|
+
return typeof x === 'number' && Number.isFinite(x)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function isLoraStrength(x: unknown): x is LoraStrength {
|
|
24
|
+
if (typeof x === 'boolean') return true
|
|
25
|
+
if (isFiniteNumber(x)) return true
|
|
26
|
+
return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1])
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** cap long option lists in error messages */
|
|
30
|
+
function listSome(items: readonly string[], cap: number = 20): string {
|
|
31
|
+
if (items.length <= cap) return items.join(', ')
|
|
32
|
+
return `${items.slice(0, cap).join(', ')} … +${items.length - cap} more`
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function applyVarPayload(varDef: AnyVar, raw: unknown): string | null {
|
|
36
|
+
const name = varDef.name ?? varDef.label ?? varDef.kind
|
|
37
|
+
|
|
38
|
+
if (varDef instanceof TextVar || varDef instanceof PromptVar) {
|
|
39
|
+
if (typeof raw !== 'string') return `var '${name}' expects a string`
|
|
40
|
+
varDef.set(raw)
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (varDef instanceof IntVar || varDef instanceof FloatVar) {
|
|
45
|
+
if (isFiniteNumber(raw)) {
|
|
46
|
+
varDef.set(raw) // set() clamps to min/max
|
|
47
|
+
return null
|
|
48
|
+
}
|
|
49
|
+
if (typeof raw === 'string' && varDef.parse(raw)) return null
|
|
50
|
+
const o = varDef.opts
|
|
51
|
+
const range = o.min == null && o.max == null ? '' : ` (${o.min ?? '-∞'}..${o.max ?? '∞'})`
|
|
52
|
+
return `var '${name}' expects a number${range}`
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (varDef instanceof SeedVar) {
|
|
56
|
+
if (isFiniteNumber(raw)) {
|
|
57
|
+
// an explicit payload seed is FIXED for this request
|
|
58
|
+
varDef.setMode('=')
|
|
59
|
+
varDef.set(raw)
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
63
|
+
const o = raw as { mode?: unknown; value?: unknown }
|
|
64
|
+
const mode = o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?' ? o.mode : null
|
|
65
|
+
if (o.mode !== undefined && mode == null) return `var '${name}': mode must be one of = + - ?`
|
|
66
|
+
if (o.value !== undefined && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`
|
|
67
|
+
if (mode == null && o.value === undefined) return `var '${name}': give "mode" and/or "value"`
|
|
68
|
+
if (mode != null) varDef.setMode(mode)
|
|
69
|
+
if (isFiniteNumber(o.value)) varDef.set(o.value)
|
|
70
|
+
return null
|
|
71
|
+
}
|
|
72
|
+
return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (varDef instanceof ToggleVar) {
|
|
76
|
+
if (typeof raw !== 'boolean') return `var '${name}' expects true or false`
|
|
77
|
+
varDef.set(raw)
|
|
78
|
+
return null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (varDef instanceof ChoiceVar) {
|
|
82
|
+
if (typeof raw === 'string' && varDef.parse(raw)) return null
|
|
83
|
+
return `var '${name}' expects one of: ${listSome(varDef.choices)}`
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (varDef instanceof LorasVar) {
|
|
87
|
+
if (raw == null || typeof raw !== 'object' || Array.isArray(raw))
|
|
88
|
+
return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`
|
|
89
|
+
const record = raw as Record<string, unknown>
|
|
90
|
+
const known = new Set<string>(varDef.options)
|
|
91
|
+
const unknownNames = Object.keys(record).filter((k) => !known.has(k))
|
|
92
|
+
if (unknownNames.length > 0)
|
|
93
|
+
return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome(varDef.options)}`
|
|
94
|
+
for (const [k, s] of Object.entries(record))
|
|
95
|
+
if (!isLoraStrength(s)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`
|
|
96
|
+
varDef.set(record as Partial<Record<string, LoraStrength>>) // every entry validated just above
|
|
97
|
+
return null
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (varDef instanceof SizeVar) {
|
|
101
|
+
if (typeof raw === 'string' && varDef.parse(raw)) return null
|
|
102
|
+
if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
103
|
+
const o = raw as { width?: unknown; height?: unknown }
|
|
104
|
+
if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
|
|
105
|
+
varDef.set({ width: o.width, height: o.height })
|
|
106
|
+
return null
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (varDef instanceof ImageVar) {
|
|
113
|
+
if (typeof raw !== 'string') return `var '${name}' expects a file path or http(s) url string`
|
|
114
|
+
varDef.set(raw)
|
|
115
|
+
return null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return `var '${name}' has unsupported kind '${varDef.kind}'`
|
|
119
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// PURE var → descriptor: ONE introspection pass feeds GET /drafts (json) AND
|
|
2
|
+
// the startup print (renderDescriptorLine)
|
|
3
|
+
import {
|
|
4
|
+
type AnyVar,
|
|
5
|
+
ChoiceVar,
|
|
6
|
+
FloatVar,
|
|
7
|
+
ImageVar,
|
|
8
|
+
IntVar,
|
|
9
|
+
LorasVar,
|
|
10
|
+
PromptVar,
|
|
11
|
+
SeedVar,
|
|
12
|
+
SizeVar,
|
|
13
|
+
type SizePreset,
|
|
14
|
+
type VarKind,
|
|
15
|
+
} from 'src/vars/ComfyVars.ts'
|
|
16
|
+
|
|
17
|
+
export type VarDescriptor = {
|
|
18
|
+
kind: VarKind
|
|
19
|
+
label?: string
|
|
20
|
+
/** what a POST payload accepts for this var, human-readable */
|
|
21
|
+
payload: string
|
|
22
|
+
default: unknown
|
|
23
|
+
choices?: readonly string[]
|
|
24
|
+
/** loras: the resolved option list */
|
|
25
|
+
options?: readonly string[]
|
|
26
|
+
min?: number
|
|
27
|
+
max?: number
|
|
28
|
+
presets?: SizePreset[]
|
|
29
|
+
extensions?: readonly string[]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function rangeText(opts: { min?: number; max?: number }): string {
|
|
33
|
+
if (opts.min == null && opts.max == null) return ''
|
|
34
|
+
return ` (${opts.min ?? '-∞'}..${opts.max ?? '∞'})`
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function describeVar(varDef: AnyVar): VarDescriptor {
|
|
38
|
+
const base = { kind: varDef.kind, label: varDef.label, default: varDef.defaultValue }
|
|
39
|
+
if (varDef instanceof PromptVar) return { ...base, payload: 'string ("//" lines = comments, "- " lines = negative)' }
|
|
40
|
+
if (varDef instanceof IntVar)
|
|
41
|
+
return { ...base, payload: `integer${rangeText(varDef.opts)}`, min: varDef.opts.min, max: varDef.opts.max }
|
|
42
|
+
if (varDef instanceof FloatVar)
|
|
43
|
+
return { ...base, payload: `number${rangeText(varDef.opts)}`, min: varDef.opts.min, max: varDef.opts.max }
|
|
44
|
+
if (varDef instanceof SeedVar)
|
|
45
|
+
return {
|
|
46
|
+
...base,
|
|
47
|
+
default: { mode: varDef.mode, value: varDef.defaultValue },
|
|
48
|
+
payload: 'number (fixed) or {"mode":"=|+|-|?","value":number}',
|
|
49
|
+
}
|
|
50
|
+
if (varDef.kind === 'toggle') return { ...base, payload: 'true or false' }
|
|
51
|
+
if (varDef instanceof ChoiceVar)
|
|
52
|
+
return { ...base, payload: `one of: ${varDef.choices.join(' | ')}`, choices: varDef.choices }
|
|
53
|
+
if (varDef instanceof LorasVar)
|
|
54
|
+
return {
|
|
55
|
+
...base,
|
|
56
|
+
payload: '{"<lora name>": false | true | strength | [model, clip]}',
|
|
57
|
+
options: varDef.options,
|
|
58
|
+
}
|
|
59
|
+
if (varDef instanceof SizeVar)
|
|
60
|
+
return { ...base, payload: '{"width":W,"height":H} or "WxH" or a preset label', presets: varDef.presets }
|
|
61
|
+
if (varDef instanceof ImageVar)
|
|
62
|
+
return { ...base, payload: 'local file path or http(s) url', extensions: varDef.extensions }
|
|
63
|
+
return { ...base, payload: 'string' } // TextVar and future plain kinds
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** one aligned console line per var (startup print) */
|
|
67
|
+
export function renderDescriptorLine(name: string, d: VarDescriptor, nameWidth: number): string {
|
|
68
|
+
const def = typeof d.default === 'string' ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default)
|
|
69
|
+
return ` ${name.padEnd(nameWidth)} ${d.kind.padEnd(6)} ${d.payload} · default: ${truncate(def ?? 'null', 60)}`
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function truncate(s: string, n: number): string {
|
|
73
|
+
return s.length <= n ? s : s.slice(0, n - 1) + '…'
|
|
74
|
+
}
|