comfy-ts 2.9.0 → 2.11.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 +6 -4
- package/dist/{LogsSt-DFxzQfDc.js → LogsSt-qtFzOKpu.js} +2 -2
- package/dist/{LogsSt-DFxzQfDc.js.map → LogsSt-qtFzOKpu.js.map} +1 -1
- package/dist/cli.js +4 -4
- package/dist/index.cjs +102 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +102 -3
- package/dist/index.js.map +1 -1
- package/dist/{run-serve-_nrvJYyt.js → run-serve-BK7BA2dn.js} +91 -3
- package/dist/run-serve-BK7BA2dn.js.map +1 -0
- package/dist/{run-tui-BLEdTsOX.js → run-tui-CQyvMf0N.js} +36 -4
- package/dist/run-tui-CQyvMf0N.js.map +1 -0
- package/dist/{DefinedWorkflow-BatWaZO1.js → schemaDrift-DjjEtwfx.js} +176 -2
- package/dist/schemaDrift-DjjEtwfx.js.map +1 -0
- package/dist/serve-web.js +32 -16
- package/dist/{state-BbgJeCe6.js → state--wrz0BQc.js} +23 -5
- package/dist/state--wrz0BQc.js.map +1 -0
- package/dist/web.d.ts +19 -0
- package/dist/web.js +102 -3
- package/dist/web.js.map +1 -1
- package/examples/README.md +1 -0
- package/examples/comfy-cloud/capybara-i2v.cflow.ts +2 -0
- package/examples/comfy-cloud/ltx25-i2v.cflow.ts +152 -0
- package/examples/comfy-cloud/ltx25-t2v.cflow.ts +126 -0
- package/examples/comfy-cloud/minimax-music3-t2a.cflow.ts +95 -0
- package/examples/comfy-cloud/sdk.d.ts +30724 -24404
- package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +2 -0
- package/examples/comfy-cloud/wan22-i2v.cflow.ts +2 -0
- package/examples/comfy-cloud/wan22-t2v.cflow.ts +2 -0
- package/examples/rvion/07-local-llm-text-gen.cflow.ts +2 -2
- package/examples/rvion/08-qwen-image-21-t2i.cflow.ts +64 -0
- package/examples/rvion/09-qwen-image-21-edit.cflow.ts +83 -0
- package/package.json +4 -2
- package/src/cli/serve/ServeApp.ts +94 -0
- package/src/cli/serve/describeVar.ts +7 -0
- package/src/cli/serve/favicon.ts +3 -0
- package/src/cli/serve/web/api.ts +12 -0
- package/src/cli/serve/web/components/VarsForm.tsx +18 -7
- package/src/cli/serve/web/components/controls/LorasControl.tsx +102 -6
- package/src/cli/serve/web/state/WebSt.ts +79 -0
- package/src/cli/serve/web/state/loraSort.ts +39 -0
- package/src/cli/serve/web/styles.ts +15 -0
- package/src/cli/tui/components/Header.tsx +2 -0
- package/src/cli/tui/state/HostSt.ts +34 -0
- package/src/graph/ComfyNode.ts +19 -3
- package/src/host/ComfyHost.ts +15 -0
- package/src/host/loraInfoCache.ts +64 -0
- package/src/host/loraManagerApi.ts +27 -0
- package/src/host/schemaDrift.ts +87 -0
- package/dist/DefinedWorkflow-BatWaZO1.js.map +0 -1
- package/dist/run-serve-_nrvJYyt.js.map +0 -1
- package/dist/run-tui-BLEdTsOX.js.map +0 -1
- package/dist/state-BbgJeCe6.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"DefinedWorkflow-BatWaZO1.js","names":["g"],"sources":["../src/utils/sha1.ts","../src/utils/matchesRegex.ts","../src/utils/log.ts","../src/storage/ComfyStorage.ts","../src/utils/bang.ts","../src/utils/isRecord.ts","../src/utils/extractErrorMessage.ts","../src/utils/ansi.ts","../src/host/loraManagerApi.ts","../src/host/loraInfoCache.ts","../src/vars/loraKeywords.ts","../src/vars/presets.ts","../src/vars/ComfyVars.ts","../src/vars/DefinedWorkflow.ts"],"sourcesContent":["// pure-JS SHA-1, browser-safe (architecture item 13): replaces node:crypto in\n// the core path. Output matches node's createHash('sha1') byte-for-byte —\n// upload-dedupe names and preview-cache keys stay identical across the swap\n// (vector-tested against node:crypto in tests/sha1.test.ts).\n\nexport function sha1Hex(data: Uint8Array): string {\n const ml = data.length\n const total = Math.ceil((ml + 1 + 8) / 64) * 64\n const bytes = new Uint8Array(total)\n bytes.set(data)\n bytes[ml] = 0x80\n const dv = new DataView(bytes.buffer)\n const bitLen = ml * 8\n dv.setUint32(total - 8, Math.floor(bitLen / 2 ** 32))\n dv.setUint32(total - 4, bitLen >>> 0)\n\n let h0 = 0x67452301\n let h1 = 0xefcdab89\n let h2 = 0x98badcfe\n let h3 = 0x10325476\n let h4 = 0xc3d2e1f0\n const w = new Uint32Array(80)\n\n for (let i = 0; i < total; i += 64) {\n for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4)\n for (let j = 16; j < 80; j++) {\n const n = (w[j - 3] ?? 0) ^ (w[j - 8] ?? 0) ^ (w[j - 14] ?? 0) ^ (w[j - 16] ?? 0)\n w[j] = (n << 1) | (n >>> 31)\n }\n let a = h0\n let b = h1\n let c = h2\n let d = h3\n let e = h4\n for (let j = 0; j < 80; j++) {\n let f: number\n let k: number\n if (j < 20) {\n f = (b & c) | (~b & d)\n k = 0x5a827999\n } else if (j < 40) {\n f = b ^ c ^ d\n k = 0x6ed9eba1\n } else if (j < 60) {\n f = (b & c) | (b & d) | (c & d)\n k = 0x8f1bbcdc\n } else {\n f = b ^ c ^ d\n k = 0xca62c1d6\n }\n const temp = (((a << 5) | (a >>> 27)) + f + e + k + (w[j] ?? 0)) >>> 0\n e = d\n d = c\n c = (b << 30) | (b >>> 2)\n b = a\n a = temp\n }\n h0 = (h0 + a) >>> 0\n h1 = (h1 + b) >>> 0\n h2 = (h2 + c) >>> 0\n h3 = (h3 + d) >>> 0\n h4 = (h4 + e) >>> 0\n }\n return [h0, h1, h2, h3, h4].map((x) => x.toString(16).padStart(8, '0')).join('')\n}\n\nexport function sha1HexOfString(s: string): string {\n return sha1Hex(new TextEncoder().encode(s))\n}\n","// RegExp.test on a /g or /y regex advances lastIndex, so the same pattern answers differently\n// on consecutive calls. A user-supplied filter is shared by several call sites.\nexport function statelessRegex(re: RegExp): RegExp {\n if (!re.global && !re.sticky) return re\n // sticky means \"match AT lastIndex\": dropping the flag would drop the anchoring too, and a\n // filter written as /krea/y would silently widen from starts-with to contains\n const source = re.sticky ? `^(?:${re.source})` : re.source\n return new RegExp(source, re.flags.replace(/[gy]/g, ''))\n}\n\nexport function matchesRegex(re: RegExp, value: string): boolean {\n return statelessRegex(re).test(value)\n}\n","// 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","import type { Maybe } from 'src/types/index.ts'\n\n/** assertNotNull */\nexport const bang = <T>(x: Maybe<T>, msg: string = ''): T => {\n if (x == null) {\n console.error(`[🔴] BANG FAILED`, msg)\n throw new Error('bang: ' + (msg ?? 'no message'))\n }\n return x\n}\n\n/** soft assertNotNull — LIES on failure: logs then returns the null as T. Prefer bang(). */\nexport const bong = <T>(x: Maybe<T>, msg: string = ''): T => {\n if (x == null) {\n console.error(`[🔴] BONG FAILED`, msg)\n return x as T\n }\n return x\n}\n\nexport function ASSERT_ARRAY(a: unknown): a is unknown[] {\n if (!Array.isArray(a)) throw new Error('❌ not an array')\n return true\n}\n\nexport function ASSERT_EQUAL(a: unknown, b: unknown): a is unknown[] {\n if (a !== b) throw new Error('❌ not equal')\n return true\n}\n\n// ----------\nexport function ASSERT_STRING(a: unknown): a is string {\n if (typeof a !== 'string') throw new Error('❌ not a string')\n return true\n}\nexport function asSTRING_orCrash(a: unknown, errMsg: string = '❌ not a string'): string {\n if (typeof a !== 'string') throw new Error(errMsg)\n return a\n}\n","/** narrows unknown wire json to an indexable object (arrays and null excluded) */\nexport function isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\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","// tiny chalk-compatible terminal styler (chainable), keeps chalk out of the deps\nconst codes = {\n bold: [1, 22],\n dim: [2, 22],\n underline: [4, 24],\n red: [31, 39],\n green: [32, 39],\n yellow: [33, 39],\n blue: [34, 39],\n cyan: [36, 39],\n gray: [90, 39],\n greenBright: [92, 39],\n} as const\n\ntype StyleName = keyof typeof codes\nexport type Styler = ((s: string) => string) & { [k in StyleName]: Styler }\n\nfunction styler(open: string = '', close: string = ''): Styler {\n const fn = (s: string): string => open + s + close\n return new Proxy(fn, {\n get(_target, prop: string) {\n const c = codes[prop as StyleName]\n if (c == null) throw new Error(`unknown ansi style: ${prop}`)\n return styler(`${open}\\x1b[${c[0]}m`, `\\x1b[${c[1]}m${close}`)\n },\n }) as Styler\n}\n\nexport const ansi: Styler = styler()\n\n// CSI sequences + lone ESC-letter escapes (server logs re-rendered inside ink)\nconst ANSI_RE = /\\x1b\\[[0-9;?]*[A-Za-z]|\\x1b[A-Za-z]/g\n\nexport function stripAnsi(s: string): string {\n return s.replace(ANSI_RE, '')\n}\n\n/** colors only where they can be seen: a real terminal, NO_COLOR unset, TERM not 'dumb'.\n * A piped or redirected stdout gets plain text, so `serve > log` stays greppable */\nexport function colorsAvailable(): boolean {\n const env = globalThis.process?.env ?? {}\n if (env.NO_COLOR != null && env.NO_COLOR !== '') return false\n if (env.TERM === 'dumb') return false\n if (env.FORCE_COLOR != null && env.FORCE_COLOR !== '' && env.FORCE_COLOR !== '0') return true\n return globalThis.process?.stdout?.isTTY === true\n}\n","import { type } from 'arktype'\nimport { basename } from 'pathe'\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\nimport { isRecord } from 'src/utils/isRecord.ts'\nimport { sha1HexOfString } from 'src/utils/sha1.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { logError } from 'src/utils/log.ts'\n\n/**\n * client for the OPTIONAL ComfyUI-Lora-Manager extension.\n * absent extension = normal condition: callers get null/empty and degrade.\n */\n\n/**\n * one lora exactly as lora-manager sent it. RAW on purpose (agent/architecture\n * item 8): the mirror on disk keeps every field, including the ones we do not\n * read yet, so adding `sha256` or `civitai.modelId` to a surface later is an\n * accessor, not a re-sync. Reading goes through the checked lm* helpers below.\n */\nexport type LmLoraItem = Record<string, unknown>\n\n/** only the ENVELOPE is schema'd — items stay unknown so nothing can strip their fields */\nconst lmLoraPage = type({\n items: 'unknown[]',\n 'total?': 'number',\n})\n\nfunction readString(item: LmLoraItem, key: string): string | null {\n const v = item[key]\n return typeof v === 'string' && v !== '' ? v : null\n}\n\nfunction readStringArray(item: LmLoraItem, key: string): string[] {\n const v = item[key]\n if (!Array.isArray(v)) return []\n return v.filter((x): x is string => typeof x === 'string' && x !== '')\n}\n\nexport function lmFileName(item: LmLoraItem): string | null {\n return readString(item, 'file_name')\n}\nexport function lmFolder(item: LmLoraItem): string {\n return readString(item, 'folder') ?? ''\n}\nexport function lmModelName(item: LmLoraItem): string | null {\n return readString(item, 'model_name')\n}\nexport function lmBaseModel(item: LmLoraItem): string | null {\n return readString(item, 'base_model')\n}\nexport function lmPreviewUrl(item: LmLoraItem): string | null {\n return readString(item, 'preview_url')\n}\n/** the file's size in bytes, when the extension reports it */\n/** the file's content hash: what the extension keys its example images by */\nexport function lmSha256(item: LmLoraItem): string | null {\n return readString(item, 'sha256')\n}\n\nexport function lmFileSize(item: LmLoraItem): number | null {\n const raw = item['file_size']\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : null\n}\n\n/** the note YOU wrote in the lora manager, empty when there is none */\nexport function lmNotes(item: LmLoraItem): string {\n return readString(item, 'notes') ?? ''\n}\n\n/** the civitai block: what links a local file back to the page it came from */\nexport function lmCivitai(item: LmLoraItem): { modelId: number | null; name: string | null } | null {\n const civitai = item['civitai']\n if (!isRecord(civitai)) return null\n const modelId = civitai['modelId']\n return {\n modelId: typeof modelId === 'number' && Number.isFinite(modelId) ? modelId : null,\n name: readString(civitai, 'name'),\n }\n}\n\nexport function lmTags(item: LmLoraItem): string[] {\n return readStringArray(item, 'tags')\n}\n\n/** the trigger words: civitai's `trainedWords`, absent for a lora nobody published */\nexport function lmTrainedWords(item: LmLoraItem): string[] {\n const civitai = item['civitai']\n if (!isRecord(civitai)) return []\n return readStringArray(civitai, 'trainedWords')\n}\n\n/** lm's own absolute path for the file, as it exists on the HOST's disk */\nexport function lmFilePath(item: LmLoraItem): string | null {\n return readString(item, 'file_path')\n}\n\n/**\n * the ONE key space where a host's object_info spelling of a lora meets\n * lora-manager's: lowercase, forward slashes, no model extension.\n * `styles\\Aurora.safetensors` and lm's folder `styles` + file_name `aurora`\n * both become `styles/aurora`.\n */\nexport function loraKey(name: string): string {\n return name\n .replaceAll('\\\\', '/')\n .replace(/\\.(safetensors|st|pt|ckpt)$/i, '')\n .toLowerCase()\n}\n\n/** the file's own name, windows separators included (`styles\\x.safetensors` → `x.safetensors`) */\nexport function loraBasename(name: string): string {\n return basename(name.replaceAll('\\\\', '/'))\n}\n\n/** the mirror key for an lm item: its folder/file_name pair, normalized */\nexport function lmItemKey(item: LmLoraItem): string | null {\n const file = lmFileName(item)\n if (file == null) return null\n const folder = lmFolder(item)\n return loraKey(folder === '' ? file : `${folder}/${file}`)\n}\n\n/** runaway stop: 20 pages × the server's 100-per-page cap = 2000 loras */\nconst MAX_PAGES = 20\n\n/**\n * the outcome of a sweep, DISCRIMINATED. A bare `null` for \"no loras\" conflated\n * three very different situations, and callers then told the user the wrong one:\n * a host that is merely DOWN was reported as \"extension not detected\", and a\n * sweep cut short mid-collection was indistinguishable from a complete one, so\n * a partial mirror could overwrite a good one and report success.\n */\nexport type LoraSweep =\n | { status: 'ok'; items: LmLoraItem[] }\n /** the extension answered, then stopped answering: `items` is INCOMPLETE, never write it over a good mirror */\n | { status: 'partial'; items: LmLoraItem[]; reason: string }\n /** no ComfyUI-Lora-Manager on this host (404 on the first page) */\n | { status: 'absent' }\n /** the host itself could not be reached (down, refused, auth) */\n | { status: 'unreachable'; reason: string }\n\n/** civitai's model description for ONE lora, as PLAIN TEXT. The extension answers html, and\n * html from a third party is never rendered: tags are stripped here, at the seam.\n * null = the extension has no description for it (or does not expose the route) */\nexport async function fetchLoraDescription(host: ComfyHost, filePath: string): Promise<string | null> {\n try {\n const res = await host.fetch(`/lm/loras/model-description?file_path=${encodeURIComponent(filePath)}`, {})\n // a 404 IS \"no description\", any other status is the extension failing at its job: the\n // two collapsed to the same silent null, which is the wrong-cause report the sibling\n // fetchLoraExampleImages carries a `reason` to avoid\n if (!res.ok) {\n if (res.status !== 404) logError(`[lora-manager] description ${res.status} for ${filePath}`)\n return null\n }\n const raw: unknown = await res.json()\n const description = isRecord(raw) ? raw['description'] : null\n if (typeof description !== 'string' || description === '') return null\n return htmlToText(description)\n } catch (e) {\n logError(`[lora-manager] description unreachable for ${filePath}: ${extractErrorMessage(e)}`)\n return null\n }\n}\n\n/** `<p>a</p><br>b` → `a\\n\\nb`. Deliberately dumb: this text is DISPLAYED, never parsed */\nfunction htmlToText(html: string): string {\n return html\n .replaceAll(/<\\s*br\\s*\\/?>/gi, '\\n')\n .replaceAll(/<\\/\\s*(p|div|li|h[1-6])\\s*>/gi, '\\n\\n')\n .replaceAll(/<\\s*li[^>]*>/gi, '· ')\n .replaceAll(/<[^>]+>/g, '')\n .replaceAll(' ', ' ')\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('"', '\"')\n .replaceAll(''', \"'\")\n .replaceAll(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\n/** the example images lora-manager keeps for a lora. `reason` explains an empty list rather\n * than pretending the lora has none, \"no example images path configured\" is a SETTING */\nexport async function fetchLoraExampleImages(\n host: ComfyHost,\n sha256: string,\n): Promise<{ files: string[]; reason: string | null }> {\n try {\n const res = await host.fetch(`/lm/example-image-files?model_hash=${encodeURIComponent(sha256)}`, {})\n const raw: unknown = await res.json()\n if (!isRecord(raw)) return { files: [], reason: `unexpected reply (http ${res.status})` }\n if (raw['success'] !== true) {\n const err = raw['error']\n return { files: [], reason: typeof err === 'string' ? err : `http ${res.status}` }\n }\n const files = raw['files']\n if (!Array.isArray(files)) return { files: [], reason: null }\n const out: string[] = []\n for (const f of files) {\n if (typeof f === 'string') out.push(f)\n else if (isRecord(f) && typeof f['path'] === 'string') out.push(f['path'])\n }\n return { files: out, reason: null }\n } catch (e) {\n return { files: [], reason: e instanceof Error ? e.message : String(e) }\n }\n}\n\n/**\n * every lora lora-manager knows, RAW, in one paged sweep.\n * page_size asks for 500; the server caps it at 100, so the loop follows `total`.\n */\nexport async function fetchLoraList(host: ComfyHost): Promise<LoraSweep> {\n const items: LmLoraItem[] = []\n for (let page = 1; page <= MAX_PAGES; page++) {\n let res: Response\n try {\n // the extension registers under /api — already prefixed, skip the probe\n res = await host.fetch(`/api/lm/loras/list?page=${page}&page_size=500`, {}, { apiPrefix: false })\n } catch (e) {\n const reason = `host unreachable at page ${page}: ${extractErrorMessage(e)}`\n return page === 1 ? { status: 'unreachable', reason } : partial(items, reason)\n }\n if (!res.ok) {\n // ONLY a route-not-there status means \"no extension here\". A 500 while lm\n // rescans its model db, or a 403, used to be announced to the user as\n // \"the extension is not installed\" — the same wrong-cause report the\n // discriminated status exists to prevent\n const missing = res.status === 404 || res.status === 405\n if (page === 1)\n return missing ? { status: 'absent' } : { status: 'unreachable', reason: `answered ${res.status}` }\n return partial(items, `page ${page} answered ${res.status}`)\n }\n let parsed: ReturnType<typeof lmLoraPage>\n try {\n // json() throws on an html SPA fallback or an empty body, and a THROW is\n // a fifth outcome this function promises not to have\n parsed = lmLoraPage(await res.json())\n } catch (e) {\n const reason = `page ${page} did not answer json: ${extractErrorMessage(e)}`\n return page === 1 ? { status: 'absent' } : partial(items, reason)\n }\n if (parsed instanceof type.errors) {\n // wire tolerance (agent/coding.md): lm drifts faster than our schema\n return partial(items, `page ${page} shape mismatch: ${parsed.summary}`)\n }\n const pageItems = parsed.items.filter(isRecord)\n items.push(...pageItems)\n const total = parsed.total\n if (total != null && items.length >= total) return { status: 'ok', items }\n if (pageItems.length === 0) {\n // an empty page is the END only when nothing said there was more. With a\n // `total` still ahead of us the collection is TRUNCATED, and calling that\n // `ok` let the cli overwrite a good mirror and print 🟢 while dropping loras\n return total == null || page === 1\n ? { status: 'ok', items }\n : partial(items, `page ${page} came back empty with ${items.length}/${total} fetched`)\n }\n }\n return partial(items, `stopped at the ${MAX_PAGES}-page runaway limit`)\n}\n\n/** a truncated sweep is LOUD at the source, whatever the caller then decides to do */\nfunction partial(items: LmLoraItem[], reason: string): LoraSweep {\n logError(`[loraManagerApi] lora sweep INCOMPLETE after ${items.length} loras — ${reason}`)\n return { status: 'partial', items, reason }\n}\n\n/** `loraKey` → server-relative preview_url */\nexport function loraPreviewMapFrom(items: LmLoraItem[]): Map<string, string> {\n const map = new Map<string, string>()\n for (const item of items) {\n const key = lmItemKey(item)\n const url = lmPreviewUrl(item)\n if (key != null && url != null) map.set(key, url)\n }\n return map\n}\n\n/** the bytes look like an image (magic numbers) — guards against ComfyUI's SPA index.html fallback */\nexport function looksLikeImage(bytes: Uint8Array): boolean {\n if (bytes.length < 3) return false // shortest signature (JPEG/GIF) is 3 bytes\n const b = bytes\n const is = (sig: number[], off = 0): boolean => sig.every((v, i) => b[off + i] === v)\n return (\n is([0x89, 0x50, 0x4e, 0x47]) || // PNG\n is([0xff, 0xd8, 0xff]) || // JPEG\n is([0x47, 0x49, 0x46]) || // GIF\n (is([0x52, 0x49, 0x46, 0x46]) && is([0x57, 0x45, 0x42, 0x50], 8)) // RIFF…WEBP\n )\n}\n\n/**\n * fetch a preview image's bytes from its server-relative preview_url.\n * cached on success at `.comfy-ts/cache/lora-previews/<sha1(url)>`. Returns null\n * when the file is missing: lora-manager SPA-fallbacks to index.html (HTML), so\n * a non-image content-type OR non-image magic bytes => no preview, not a crash.\n */\nexport async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string): Promise<Uint8Array | null> {\n const storage = getComfyStorage()\n const cachePath = comfyts.resolveFromCache(`lora-previews/${sha1HexOfString(previewUrl)}`)\n if (storage.exists(cachePath)) return storage.readBytes(cachePath)\n try {\n // preview_url is already a full server-relative path — no /api probing\n const res = await host.fetch(previewUrl, {}, { apiPrefix: false })\n if (!res.ok) return null\n const ct = res.headers.get('content-type') ?? ''\n if (ct !== '' && !ct.startsWith('image/')) return null // HTML fallback etc.\n const bytes = new Uint8Array(await res.arrayBuffer())\n if (!looksLikeImage(bytes)) return null\n storage.writeBytes(cachePath, bytes)\n return bytes\n } catch {\n return null\n }\n}\n","import { join } from 'pathe'\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport {\n type LmLoraItem,\n lmBaseModel,\n lmFileName,\n lmFilePath,\n lmFolder,\n lmItemKey,\n lmModelName,\n lmPreviewUrl,\n lmTags,\n lmTrainedWords,\n loraBasename,\n loraKey,\n} from 'src/host/loraManagerApi.ts'\nimport type { AbsolutePath } from 'src/types/index.ts'\nimport { isRecord } from 'src/utils/isRecord.ts'\nimport { logError } from 'src/utils/log.ts'\n\n/**\n * the LOCAL MIRROR of what ComfyUI-Lora-Manager knows about a host's loras\n * (agent/architecture.md item 8). A ComfyUI host only ever tells us a lora's\n * file name; the model's real name, its trigger words and its tags live in the\n * extension. We sweep them once (`comfy-ts loras`) into\n * `.comfy-ts/hosts/<id>/loras.json` and every surface reads the mirror after.\n */\n\nexport type LoraMirror = {\n hostId: string\n /** remembered so a later `comfy-ts loras` re-syncs with no flags. NEVER an api key. */\n hostUrl: string\n fetchedAt: string\n count: number\n /** `loraKey` → the RAW lm item */\n loras: Record<string, LmLoraItem>\n}\n\nfunction loraMirrorPath(hostId: string): AbsolutePath {\n return comfyts.resolveFromHosts(join(hostId, 'loras.json'))\n}\n\n/** pure: the on-disk shape for a sweep. Items without a file_name are dropped (nothing to key them by). */\nexport function buildLoraMirror(p: {\n hostId: string\n hostUrl: string\n fetchedAt: string\n items: LmLoraItem[]\n}): LoraMirror {\n const loras: Record<string, LmLoraItem> = {}\n for (const item of p.items) {\n const key = lmItemKey(item)\n if (key == null) continue\n // `x.safetensors` and `x.pt` in one folder collapse here: one lora would\n // silently inherit the other's trigger words, so say it out loud\n if (loras[key] != null) logError(`[loraInfoCache] two loras share the key '${key}' — one of them is shadowed`)\n loras[key] = item\n }\n return {\n hostId: p.hostId,\n hostUrl: p.hostUrl,\n fetchedAt: p.fetchedAt,\n count: Object.keys(loras).length,\n loras,\n }\n}\n\nexport function writeLoraMirror(mirror: LoraMirror): AbsolutePath {\n const path = loraMirrorPath(mirror.hostId)\n getComfyStorage().writeText(path, JSON.stringify(mirror, null, 2))\n return path\n}\n\n/** null = never synced (or unreadable, which is LOGGED) */\nexport function readLoraMirror(hostId: string): LoraMirror | null {\n const path = loraMirrorPath(hostId)\n const text = getComfyStorage().readTextIfExists(path)\n if (text == null) return null\n try {\n const raw: unknown = JSON.parse(text)\n if (!isRecord(raw)) return null\n const rawLoras = raw['loras']\n if (!isRecord(rawLoras)) return null\n const loras: Record<string, LmLoraItem> = {}\n for (const [key, item] of Object.entries(rawLoras)) if (isRecord(item)) loras[key] = item\n const str = (key: string, fallback: string): string => {\n const v = raw[key]\n return typeof v === 'string' ? v : fallback\n }\n // count is RECOUNTED, never trusted: the file is hand-editable like every .comfy-ts json\n return {\n hostId: str('hostId', hostId),\n hostUrl: str('hostUrl', ''),\n fetchedAt: str('fetchedAt', ''),\n count: Object.keys(loras).length,\n loras,\n }\n } catch (e) {\n logError(`[loraInfoCache] unreadable ${path}: ${String(e)}`)\n return null\n }\n}\n\n/**\n * the read model: each registered host's mirror, kept PER HOST.\n *\n * Per host, not merged into one map, because the same file name on two hosts is\n * routinely a different model. A merged map served whichever host loaded first,\n * so on the other host the overlay showed the wrong model name and the prompt\n * silently received the wrong trigger words — a bad generation with no error\n * anywhere. Callers that know their host say so; the rest fall back to any host\n * that has the lora, which is still better than nothing for a display name.\n *\n * Plain (non-observable) on purpose: the loras overlay reads this from inside a\n * mobx render. The storage seam has no readdir, so the host set comes from\n * `comfyts.hosts` — exactly the hosts this process can be asked about.\n */\nconst byHost = new Map<string, Map<string, LmLoraItem>>()\n/** hosts already looked for, INCLUDING the ones with no mirror on disk → their mtime is null */\nconst loadedMtimes = new Map<string, number | null>()\n\n/** cheap: no stat, no parse — this runs inside the overlay's render for every row */\nfunction ensureLoaded(): void {\n for (const hostId of comfyts.hosts.keys()) if (!loadedMtimes.has(hostId)) loadHost(hostId)\n}\n\nfunction loadHost(hostId: string): void {\n const storage = getComfyStorage()\n const path = loraMirrorPath(hostId)\n loadedMtimes.set(hostId, storage.mtimeMs(path))\n const mirror = readLoraMirror(hostId)\n if (mirror != null) byHost.set(hostId, new Map(Object.entries(mirror.loras)))\n // a mirror that EXISTS but will not parse (a sync killed mid-write) still makes\n // this host authoritative, with an empty map: falling through to another host's\n // entries is exactly the wrong-model-name bug the per-host split removed\n else if (storage.exists(path)) byHost.set(hostId, new Map())\n else byHost.delete(hostId)\n}\n\n/**\n * re-read any mirror whose file changed (or appeared) since we loaded it.\n * `comfy-ts loras` in another terminal is the normal case, and without this a\n * TUI session kept the stale data — or kept knowing NOTHING, for a host whose\n * first sync happened while it was open. One stat per registered host, so this\n * belongs at user-initiated moments (opening the loras overlay), never in a render.\n */\nexport function refreshLoraInfoCacheIfChanged(): void {\n const storage = getComfyStorage()\n for (const hostId of comfyts.hosts.keys()) {\n const seen = loadedMtimes.get(hostId)\n const now = storage.mtimeMs(loraMirrorPath(hostId))\n // `undefined` = never looked; `null` = looked, no file. Both differ from a real mtime.\n if (!loadedMtimes.has(hostId) || seen !== now) loadHost(hostId)\n }\n}\n\n/** forget everything loaded, so the next read re-reads from disk (tests, and a hard refresh) */\nexport function reloadLoraInfoCache(): void {\n byHost.clear()\n loadedMtimes.clear()\n}\n\n/**\n * the lm item for a raw lora name (`styles\\x.safetensors`).\n * `hostId` picks the mirror that actually describes this host's file; without\n * it, any host that knows the name answers. null when unsynced/unknown.\n */\nexport function getLoraInfo(name: string, hostId?: string): LmLoraItem | null {\n ensureLoaded()\n const key = loraKey(name)\n if (hostId != null) {\n const own = byHost.get(hostId)\n // a host WITH a mirror is authoritative about its own loras: never fall\n // back to another host's entry for a lora it does not have\n if (own != null) return own.get(key) ?? null\n }\n for (const mirror of byHost.values()) {\n const hit = mirror.get(key)\n if (hit != null) return hit\n }\n return null\n}\n\n/** civitai trigger words for this lora, in civitai's order */\nexport function getLoraTriggerWords(name: string, hostId?: string): string[] {\n const info = getLoraInfo(name, hostId)\n return info == null ? [] : lmTrainedWords(info)\n}\n\n/** the human name (`Aurora Ink Wash`), falling back to the file's own name */\nexport function getLoraDisplayName(name: string, hostId?: string): string {\n const info = getLoraInfo(name, hostId)\n return (info == null ? null : lmModelName(info)) ?? loraBasename(name)\n}\n\n/** server-relative preview url from the mirror, null when unsynced/unknown */\nexport function getLoraPreviewUrl(name: string, hostId?: string): string | null {\n const info = getLoraInfo(name, hostId)\n return info == null ? null : lmPreviewUrl(info)\n}\n\n/** the lora's NAMES: the file, and the model name a human would call it by */\n/**\n * every lora the mirror knows for a host: its normalized KEY (comparable with `loraKey(option)`,\n * never with a raw enum value, those keep their case, extension and windows separators) and the\n * NAME a ComfyUI graph would load it by, rebuilt from the manager's folder + real filename.\n * `[]` when the host was never synced.\n */\nexport function loraMirrorEntries(\n hostId: string,\n p: { separator?: '/' | '\\\\' } = {},\n): {\n key: string\n serverName: string\n}[] {\n ensureLoaded()\n const sep = p.separator ?? '/'\n const out: { key: string; serverName: string }[] = []\n for (const [key, item] of byHost.get(hostId) ?? []) {\n // file_path carries the extension the enum value needs; file_name may not\n const filePath = lmFilePath(item)\n const base = filePath == null ? null : (filePath.split(/[/\\\\]/).pop() ?? null)\n const file = base ?? lmFileName(item)\n if (file == null) continue\n const folder = lmFolder(item)\n // the manager's own `folder` can be a NESTED path with its own separators, so the whole\n // name is normalized to the host's style, never just the join (8 of 119 came out mixed)\n const joined = folder === '' ? file : `${folder}/${file}`\n out.push({ key, serverName: joined.replaceAll(/[\\\\/]/g, sep) })\n }\n return out.sort((a, b) => a.serverName.localeCompare(b.serverName))\n}\n\nexport function loraSearchNames(name: string, hostId?: string): string[] {\n const names = [loraBasename(name), name.replaceAll('\\\\', '/')]\n const info = getLoraInfo(name, hostId)\n const modelName = info == null ? null : lmModelName(info)\n if (modelName != null) names.push(modelName)\n return names\n}\n\n/** the lora's FREE TEXT: tags, base model, trigger words */\nexport function loraSearchText(name: string, hostId?: string): string[] {\n const info = getLoraInfo(name, hostId)\n if (info == null) return []\n const text = [...lmTags(info), ...lmTrainedWords(info)]\n const baseModel = lmBaseModel(info)\n if (baseModel != null) text.push(baseModel)\n return text\n}\n\n/**\n * the loras overlay filter: find a lora by its human name, not only by the file\n * name. EVERY whitespace-separated token must be a SUBSTRING of some field — order\n * free, so `aurora ink`, `ink aurora` and `styles wash` all land on the same\n * lora. NOT fuzzyMatch: a subsequence match over phrases this long matches\n * nearly everything. Measured on a real collection, filtering by each lora's\n * own file name: this rule peaks at 8 hits where fuzzyMatch matched a third of\n * every lora present.\n * Fields are matched one by one, never as a concatenated haystack, for the same\n * reason. `tests/lora-corpus.private.test.ts` keeps that measurement runnable.\n */\nexport function loraMatchesFilter(name: string, filter: string, hostId?: string): boolean {\n const tokens = filter\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t !== '')\n if (tokens.length === 0) return true\n const fields = [...loraSearchNames(name, hostId), ...loraSearchText(name, hostId)].map((f) => f.toLowerCase())\n return tokens.every((token) => fields.some((field) => field.includes(token)))\n}\n","import { observable, runInAction } from 'mobx'\nimport { join } from 'pathe'\nimport { getLoraTriggerWords } from 'src/host/loraInfoCache.ts'\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 *\n * This file is the OVERRIDE layer. Below it sits the lora-manager mirror's\n * civitai trigger words (src/host/loraInfoCache.ts, refreshed by\n * `comfy-ts loras`), so most loras carry a keyword without anyone typing one.\n * The overlay renders a mirror-sourced keyword dim and a hand-typed one yellow,\n * and ⌃D drops the override to fall back to the mirror again.\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\n/** the hand keyword when this lora HAS an entry (`''` included), else the mirror's trigger words */\nexport function getLoraKeyword(name: string, hostId?: string): string {\n loadOnce()\n const hand = keywords.get(name)\n if (hand != null) return hand\n return getLoraTriggerWords(name, hostId).join(', ')\n}\n\n/** true when the keyword shown comes from the lora-manager mirror, not from ⌃K */\nexport function isLoraKeywordFromMirror(name: string, hostId?: string): boolean {\n loadOnce()\n return !keywords.has(name) && getLoraTriggerWords(name, hostId).length > 0\n}\n\n/** what `clearLoraKeywordOverride` would restore this lora to, `''` when nothing */\nexport function loraKeywordFromMirror(name: string, hostId?: string): string {\n return getLoraTriggerWords(name, hostId).join(', ')\n}\n\n/**\n * drop the hand entry entirely, so the mirror's trigger words apply again.\n * The way BACK from an empty-string tombstone: without it, clearing a keyword on\n * a lora that has trigger words was a one-way door only a text editor could undo.\n */\nexport function clearLoraKeywordOverride(name: string): void {\n loadOnce()\n if (!keywords.has(name)) return\n runInAction(() => void keywords.delete(name))\n writeKeywords()\n}\n\n/**\n * empty keyword deletes the entry — EXCEPT when the mirror has trigger words for\n * this lora: there `''` is stored as an explicit tombstone, the only way to say\n * \"inject nothing\" about a lora civitai gave words to. Every set writes the file\n * (tiny, rare).\n */\nexport function setLoraKeyword(name: string, keyword: string, hostId?: string): void {\n loadOnce()\n const trimmed = keyword.trim()\n runInAction(() => {\n if (trimmed === '' && getLoraTriggerWords(name, hostId).length === 0) keywords.delete(name)\n else keywords.set(name, trimmed)\n })\n writeKeywords()\n}\n\n/** every set writes the file: it is tiny and hand-edited rarely */\nfunction writeKeywords(): void {\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","// named starting texts for a text/prompt var. PURE and dependency-free on purpose: the\n// browser bundle imports it too (the web panel matches the live value against the list).\nexport type VarPreset = { label: string; text: string }\n\n/** authored shape: `{ 'terse one-liner': 'reply with one sentence…' }`. Key order is display order */\nexport type VarPresetSpec = Record<string, string>\n\nexport function toPresetList(spec: VarPresetSpec | undefined): VarPreset[] {\n if (spec == null) return []\n return Object.entries(spec).map(([label, text]) => ({ label, text }))\n}\n\n/** which preset the value still IS, or null once it was hand-edited (trailing whitespace ignored) */\nexport function activePresetLabel(presets: readonly VarPreset[], value: string): string | null {\n const v = value.trim()\n return presets.find((p) => p.text.trim() === v)?.label ?? null\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'\nimport { toPresetList, type VarPreset, type VarPresetSpec } from 'src/vars/presets.ts'\n\n/**\n * the var's CLASS, and the only safe way to discriminate one: `instanceof` compares class\n * OBJECTS, and the published package hands the same class out twice — a consumer's\n * `.cflow.ts` imports `comfy-ts` (dist/index.js) while `comfy-ts serve`/`tui` run from the\n * cli bundle, so every `instanceof XVar` across that boundary is false (observed\n * in a consumer app: \"var 'prompt' has unsupported kind 'text'\", for EVERY kind). A string tag\n * crosses bundles; a class identity does not.\n */\nexport type VarKind = 'text' | 'prompt' | '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 type TextVarOpts = {\n label?: string\n /** render as a box you can write paragraphs in, not a one-line field. Some text IS long by\n * nature (an llm instruction, a system prompt) and a single line hides all but its start */\n multiline?: boolean\n /** named starting texts, `{ label: text }`. The TUI and the web panel offer them behind one\n * button and picking one REPLACES the value, so a preset is a shortcut, never a mode */\n presets?: VarPresetSpec\n}\n\nexport class TextVar extends ComfyVar<string> {\n readonly kind = 'text' as const\n /** normalized `opts.presets`, in authored order */\n readonly presets: VarPreset[]\n readonly opts: TextVarOpts\n /** a bare label string was the whole second parameter before opts existed: a published\n * consumer passing one must keep working, exactly as SeedVar does */\n constructor(defaultValue: string, opts: string | TextVarOpts = {}) {\n const o = typeof opts === 'string' ? { label: opts } : opts\n super(defaultValue, o.label)\n this.opts = o\n this.presets = toPresetList(o.presets)\n }\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.\n * `hostId` scopes the keyword lookup: the same file name on two hosts is often a\n * different model, and injecting the other host's trigger words is a silently\n * wrong generation. */\nexport type ActiveLoraSource = { activeNames(): string[]; hostId?: 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 = 'prompt' as const\n /** normalized `promptOpts.presets`, in authored order (TextVarOpts.presets owns the WHY) */\n readonly presets: VarPreset[]\n constructor(\n defaultValue: string,\n public promptOpts: {\n label?: string\n loraKeywordsFrom?: ActiveLoraSource\n presets?: VarPresetSpec\n } = {},\n ) {\n super(defaultValue, promptOpts.label)\n this.presets = toPresetList(promptOpts.presets)\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((name) => getLoraKeyword(name, src.hostId))\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 /** the mode a reset() restores — the SPEC default, never the live one (introspection\n * reads this: a running mode must not masquerade as the var's default) */\n readonly defaultMode: SeedMode\n /** `opts` is the modern shape; a bare label string stays accepted, since that was the\n * signature before a workflow could declare the mode it wants to run in */\n constructor(defaultValue: number = 0, opts: string | { label?: string; mode?: SeedMode } = {}) {\n const o = typeof opts === 'string' ? { label: opts } : opts\n super(defaultValue, o.label)\n this.mode = o.mode ?? '='\n this.defaultMode = this.mode\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(this.defaultMode)\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 = { data?: { id?: string }; 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 /** which host these loras live on, so their metadata is read from ITS mirror */\n hostId: string | undefined = undefined\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 /** the filter the workflow declared, when it declared one (`v.loras(/krea-?2/i)`). Public so\n * a UI can SHOW it, and so serve applies the same narrowing to loras only its lora-manager\n * mirror knows, an unfiltered union would put the whole catalog back in a filtered picker */\n get optionsFilter(): RegExp | null {\n return this.optionsSource instanceof RegExp ? this.optionsSource : null\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 this.hostId = host.data?.id\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 (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. NOT a security\n * boundary: `comfy-ts serve` keeps its own floor of image types it will read off the disk\n * and upload, which this list may NARROW but never widen (emptying it changes the picker,\n * not what the api accepts) */\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 /** name, not instanceof: the cli bundle and dist/index.js each define this class */\n override readonly name = 'ImageVarEmptyError'\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 // the old `v.text(x, 'label')` form still works: a bare string IS the label\n text: (defaultValue: string, opts: TextVarOpts | string = {}): TextVar =>\n new TextVar(defaultValue, typeof opts === 'string' ? { label: opts } : opts),\n prompt: (\n defaultValue: string,\n opts: { label?: string; loraKeywordsFrom?: ActiveLoraSource; presets?: VarPresetSpec } = {},\n ): PromptVar => 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 /** `mode` is the SPEC default the workflow runs in: `'+'` makes every run step the seed,\n * which is what a tuning session wants, and reset()/revert come back to it */\n seed: (defaultValue: number = 0, opts: string | { label?: string; mode?: SeedMode } = {}): SeedVar =>\n new SeedVar(defaultValue, opts),\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":";;;;;AAKA,SAAgB,QAAQ,MAA0B;CAC/C,MAAM,KAAK,KAAK;CAChB,MAAM,QAAQ,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,IAAI;CAC7C,MAAM,QAAQ,IAAI,WAAW,KAAK;CAClC,MAAM,IAAI,IAAI;CACd,MAAM,MAAM;CACZ,MAAM,KAAK,IAAI,SAAS,MAAM,MAAM;CACpC,MAAM,SA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