comfy-ts 2.3.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +13 -0
  2. package/dist/{DefinedWorkflow-CwHInZgn.js → DefinedWorkflow-QrhT6V66.js} +441 -9
  3. package/dist/DefinedWorkflow-QrhT6V66.js.map +1 -0
  4. package/dist/{DraftsSt-omWuBSej.js → DraftsSt-D9Fhk4qR.js} +2 -2
  5. package/dist/{DraftsSt-omWuBSej.js.map → DraftsSt-D9Fhk4qR.js.map} +1 -1
  6. package/dist/cli.js +116 -8
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +268 -23
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +150 -9
  11. package/dist/index.d.ts +150 -9
  12. package/dist/index.js +257 -24
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-serve-CfzOH-AR.js → run-serve-C9E8dyLP.js} +3 -3
  15. package/dist/run-serve-C9E8dyLP.js.map +1 -0
  16. package/dist/{run-tui-_LD0DoGe.js → run-tui-8si-rVW0.js} +60 -121
  17. package/dist/run-tui-8si-rVW0.js.map +1 -0
  18. package/dist/{state-C-OOEcp3.js → state-C0ARiFFM.js} +15 -76
  19. package/dist/state-C0ARiFFM.js.map +1 -0
  20. package/dist/web.d.ts +150 -9
  21. package/dist/web.js +257 -24
  22. package/dist/web.js.map +1 -1
  23. package/guide-for-agents.md +3 -0
  24. package/package.json +2 -1
  25. package/src/cli/comfy-ts-cli.ts +16 -1
  26. package/src/cli/flags.ts +14 -0
  27. package/src/cli/gen.ts +2 -4
  28. package/src/cli/loras.ts +113 -0
  29. package/src/cli/serve/applyVarPayload.ts +1 -1
  30. package/src/cli/tui/components/LorasOverlay.tsx +18 -5
  31. package/src/cli/tui/components/StatusBar.tsx +1 -0
  32. package/src/cli/tui/components/TuiApp.tsx +1 -0
  33. package/src/cli/tui/imageClipboard.ts +3 -3
  34. package/src/cli/tui/protocolImagePainter.ts +1 -1
  35. package/src/cli/tui/run-tui.tsx +2 -2
  36. package/src/cli/tui/state/ExecSt.ts +2 -2
  37. package/src/cli/tui/state/HostSt.ts +1 -1
  38. package/src/cli/tui/state/LorasSt.ts +60 -15
  39. package/src/cli/tui/state/PreviewSt.ts +1 -1
  40. package/src/cli/tui/state/SettingsSt.ts +1 -1
  41. package/src/coreExports.ts +20 -1
  42. package/src/host/ComfyHost.ts +10 -1
  43. package/src/host/ResilientWebsocket.ts +20 -0
  44. package/src/host/loraInfoCache.ts +216 -0
  45. package/src/host/loraManagerApi.ts +131 -27
  46. package/src/runner/ComfyExecution.ts +1 -1
  47. package/src/runner/outputPath.ts +3 -3
  48. package/src/utils/isRecord.ts +4 -0
  49. package/src/vars/ComfyVars.ts +13 -7
  50. package/src/vars/loraKeywords.ts +48 -5
  51. package/dist/DefinedWorkflow-CwHInZgn.js.map +0 -1
  52. package/dist/run-serve-CfzOH-AR.js.map +0 -1
  53. package/dist/run-tui-_LD0DoGe.js.map +0 -1
  54. package/dist/state-C-OOEcp3.js.map +0 -1
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli/gen.ts","../src/cli/outline.ts","../src/cli/comfy-ts-cli.ts"],"sourcesContent":["// fetch a live host's schema and generate its typed sdk\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'pathe'\nimport { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport { ComfyTS } from 'src/state.ts'\nimport { readableStringify } from 'src/utils/stringifyReadable.ts'\n\nexport async function runGen(args: string[]): Promise<number> {\n const getFlag = (name: string): string | null => {\n const ix = args.indexOf(`--${name}`)\n return ix >= 0 ? (args[ix + 1] ?? null) : null\n }\n const hostUrl = getFlag('host') ?? 'http://127.0.0.1:8188'\n const id = getFlag('id')\n if (id == null) {\n console.error('[comfy-ts gen] 🔴 --id <host-id> is required (it names .comfy-ts/hosts/<id>/)')\n return 1\n }\n\n // the lib's own authed host.fetch does the /api-first probing + X-API-Key\n const comfy = ComfyTS.create()\n const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY\n const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })\n\n const fetchJSON = async <T>(route: string): Promise<T> => {\n console.log(`[comfy-ts gen] fetching ${hostUrl} ${route} …`)\n const res = await host.fetch(route)\n if (!res.ok) throw new Error(`GET ${route} failed on ${hostUrl}: ${res.status}`)\n if (!(res.headers.get('content-type') ?? '').includes('json'))\n throw new Error(`GET ${route} on ${hostUrl} did not answer json`)\n return (await res.json()) as T\n }\n\n const spec = await fetchJSON<ComfySchemaJSON>('/object_info')\n const embeddings = await fetchJSON<string[]>('/embeddings').catch(() => [] as string[])\n\n const dir = join(process.cwd(), '.comfy-ts', 'hosts', id)\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'object_info.json'), readableStringify(spec, 4), 'utf8')\n writeFileSync(join(dir, 'embeddings.json'), JSON.stringify(embeddings), 'utf8')\n\n const parsed = new ComfySchema({ spec, embeddings })\n const dts = parsed.codegenDTS({ hostId: id })\n // --out: explicit sdk home (the committed cloud catalog) — the json dumps\n // above still cache under .comfy-ts/hosts/<id>/, but the sdk must exist at\n // ONE tsconfig-visible path only, so it skips the hosts dir entirely\n const out = getFlag('out')\n const outPath = out != null ? resolve(process.cwd(), out) : join(dir, 'sdk.d.ts')\n if (out != null) mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, dts, 'utf8')\n console.log(`[comfy-ts gen] 🟢 ${outPath} (${parsed.nodes.length} nodes, ${(dts.length / 1024).toFixed(0)}kB)`)\n if (out == null)\n console.log(`[comfy-ts gen] add \".comfy-ts/hosts/**/sdk.d.ts\" to your tsconfig \"include\" to activate the types`)\n return 0\n}\n","// outline a generated sdk.d.ts without reading 2MB blind\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'pathe'\n\ntype Section = { name: string; kind: string; start: number; end: number; depth: number }\n\nfunction findDefaultSdk(): string | null {\n const hostsDir = join(process.cwd(), '.comfy-ts', 'hosts')\n if (!existsSync(hostsDir)) return null\n for (const id of readdirSync(hostsDir)) {\n const p = join(hostsDir, id, 'sdk.d.ts')\n if (existsSync(p)) return p\n }\n return null\n}\n\nexport function runOutline(args: string[]): number {\n const linesFlagIx = args.indexOf('--lines')\n const maxLines = linesFlagIx >= 0 ? Number(args[linesFlagIx + 1] ?? 10) : null\n const sectionFlagIx = args.indexOf('--section')\n const wantedSection = sectionFlagIx >= 0 ? args[sectionFlagIx + 1] : null\n const flagValueIxs = new Set([linesFlagIx + 1, sectionFlagIx + 1].filter((ix) => ix > 0))\n const fileArg = args.find((a, ix) => !a.startsWith('--') && !flagValueIxs.has(ix))\n\n const file = fileArg ?? findDefaultSdk()\n if (file == null || !existsSync(file)) {\n console.error('[sdk-outline] 🔴 no sdk.d.ts found; pass a path explicitly')\n return 1\n }\n\n const lines = readFileSync(file, 'utf8').split('\\n')\n\n // scan: track brace depth, record interface/type/namespace declarations up to depth 3\n const sections: Section[] = []\n const stack: Section[] = []\n let depth = 0\n const declRe = /^\\s*(?:export\\s+)?(interface|namespace|type)\\s+([A-Za-z0-9_$]+)/\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? ''\n const m = depth <= 3 ? declRe.exec(line) : null\n const opens = (line.match(/{/g) ?? []).length\n const closes = (line.match(/}/g) ?? []).length\n if (m && (opens > 0 || m[1] === 'type')) {\n const sec: Section = { name: m[2] ?? '?', kind: m[1] ?? '?', start: i + 1, end: i + 1, depth }\n sections.push(sec)\n if (opens > closes) stack.push(sec)\n }\n depth += opens - closes\n while (stack.length > 0 && depth <= (stack[stack.length - 1]?.depth ?? 0)) {\n const closed = stack.pop()\n if (closed) closed.end = i + 1\n }\n // type aliases (no braces): extend until next decl at same depth\n const last = sections[sections.length - 1]\n if (last && last.kind === 'type' && stack[stack.length - 1] !== last) last.end = Math.max(last.end, i)\n }\n\n if (wantedSection) {\n const sec = sections.find((s) => s.name === wantedSection)\n if (sec == null) {\n console.error(\n `[sdk-outline] 🔴 section \"${wantedSection}\" not found. Available: ${sections.map((s) => s.name).join(', ')}`,\n )\n return 1\n }\n const body = lines.slice(sec.start - 1, maxLines ? Math.min(sec.end, sec.start - 1 + maxLines) : sec.end)\n console.log(body.join('\\n'))\n if (maxLines && sec.end - sec.start + 1 > maxLines)\n console.log(`… (${sec.end - sec.start + 1 - maxLines} more lines, ends at line ${sec.end})`)\n } else {\n console.log(`${file} — ${lines.length} lines\\n`)\n for (const s of sections) {\n const indent = ' '.repeat(s.depth)\n console.log(`${indent}${s.kind} ${s.name} [${s.start}-${s.end}] (${s.end - s.start + 1} lines)`)\n if (maxLines) {\n const body = lines.slice(s.start - 1, s.start - 1 + maxLines)\n console.log(body.map((l) => `${indent} │ ${l.trim()}`).join('\\n'))\n }\n }\n }\n return 0\n}\n","#!/usr/bin/env node\n// sidekick CLI: `bunx comfy-ts <command>` — codegen without writing any code\nimport { spawnSync } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport { runGen } from 'src/cli/gen.ts'\nimport { runOutline } from 'src/cli/outline.ts'\n\nconst HELP = `comfy-ts — typed SDK codegen for ComfyUI\n\nUsage:\n comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188] [--api-key <key>] [--out <sdk-path>]\n fetch object_info + embeddings from a live ComfyUI host and write\n .comfy-ts/hosts/<host-id>/{object_info.json,embeddings.json,sdk.d.ts}\n (--api-key or COMFY_CLOUD_API_KEY authenticates via X-API-Key;\n --out relocates ONLY the sdk.d.ts, e.g. a committed cloud catalog)\n\n comfy-ts outline [file] [--lines N] [--section Name]\n outline a generated sdk.d.ts (defaults to the first one in .comfy-ts/hosts/)\n\n comfy-ts tui [dir | workflow-module.ts]\n interactive tweak & re-run over **/*.cflow.ts modules (exporting\n host.defineWorkflow(...)); no arg scans cwd + the examples bundled\n with comfy-ts, an explicit dir/file limits to it (file preselected)\n\n comfy-ts serve [dir | workflow-module.ts] [--port 8288] [--bind 127.0.0.1]\n drafts as a local HTTP generation API: POST /generate/<module>/<draft>\n with { ...vars } overriding the draft's values (blocking; raw image\n bytes under Accept: image/*), GET /drafts self-describes every var,\n GET /outputs/... serves the results. No bundled examples, no auth.\n\n comfy-ts help\n`\n\nasync function main(): Promise<number> {\n const [cmd, ...rest] = process.argv.slice(2)\n if (cmd === 'gen') return runGen(rest)\n if (cmd === 'outline') return runOutline(rest)\n if (cmd === 'tui' || cmd === 'serve') {\n // .cflow.ts workflow modules need bun: node refuses to strip types under\n // node_modules, exactly where the packaged examples live — and the bin's\n // node shebang means `bunx comfy-ts tui|serve` lands here under NODE. Hop\n // to bun when we are not already in it; without bun, degrade loudly.\n if (process.versions.bun == null) {\n const self = fileURLToPath(import.meta.url)\n const res = spawnSync('bun', [self, cmd, ...rest], { stdio: 'inherit' })\n if (res.error == null) return res.status ?? 1\n console.error(\n `[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`,\n )\n }\n if (cmd === 'serve') {\n const { runServe } = await import('src/cli/serve/run-serve.ts')\n return runServe(rest)\n }\n // lazy import: keeps ink/react out of the codegen paths\n const { runTui } = await import('src/cli/tui/run-tui.tsx')\n return runTui(rest)\n }\n console.log(HELP)\n return cmd == null || cmd === 'help' ? 0 : 1\n}\n\nprocess.exitCode = await main()\n"],"mappings":";;;;;;;AAQA,eAAsB,OAAO,MAAiC;CAC3D,MAAM,WAAW,SAAgC;EAC9C,MAAM,KAAK,KAAK,QAAQ,KAAK,MAAM;EACnC,OAAO,MAAM,IAAK,KAAK,KAAK,MAAM,OAAQ;CAC7C;CACA,MAAM,UAAU,QAAQ,MAAM,KAAK;CACnC,MAAM,KAAK,QAAQ,IAAI;CACvB,IAAI,MAAM,MAAM;EACb,QAAQ,MAAM,+EAA+E;EAC7F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AO,IAAI;CACrB;CACA,QAAQ,IAAI,IAAI;CAChB,OAAO,OAAO,QAAQ,QAAQ,SAAS,IAAI;AAC9C;AAEA,QAAQ,WAAW,MAAM,KAAK"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli/flags.ts","../src/cli/gen.ts","../src/cli/loras.ts","../src/cli/outline.ts","../src/cli/comfy-ts-cli.ts"],"sourcesContent":["/**\n * the CLI's one flag reader: `--name value`.\n * A flag written with no value after it is a TYPO, never a request for the\n * default — silently falling back would run against the wrong host.\n */\nexport function flagReader(args: string[]): (name: string) => string | null {\n return (name: string): string | null => {\n const ix = args.indexOf(`--${name}`)\n if (ix < 0) return null\n const value = args[ix + 1]\n if (value == null || value.startsWith('--')) throw new Error(`--${name} needs a value`)\n return value\n }\n}\n","// fetch a live host's schema and generate its typed sdk\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'pathe'\nimport { flagReader } from 'src/cli/flags.ts'\nimport { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport { ComfyTS } from 'src/state.ts'\nimport { readableStringify } from 'src/utils/stringifyReadable.ts'\n\nexport async function runGen(args: string[]): Promise<number> {\n const getFlag = flagReader(args)\n const hostUrl = getFlag('host') ?? 'http://127.0.0.1:8188'\n const id = getFlag('id')\n if (id == null) {\n console.error('[comfy-ts gen] 🔴 --id <host-id> is required (it names .comfy-ts/hosts/<id>/)')\n return 1\n }\n\n // the lib's own authed host.fetch does the /api-first probing + X-API-Key\n const comfy = ComfyTS.create()\n const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY\n const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })\n\n const fetchJSON = async <T>(route: string): Promise<T> => {\n console.log(`[comfy-ts gen] fetching ${hostUrl} ${route} …`)\n const res = await host.fetch(route)\n if (!res.ok) throw new Error(`GET ${route} failed on ${hostUrl}: ${res.status}`)\n if (!(res.headers.get('content-type') ?? '').includes('json'))\n throw new Error(`GET ${route} on ${hostUrl} did not answer json`)\n return (await res.json()) as T\n }\n\n const spec = await fetchJSON<ComfySchemaJSON>('/object_info')\n const embeddings = await fetchJSON<string[]>('/embeddings').catch(() => [] as string[])\n\n const dir = join(process.cwd(), '.comfy-ts', 'hosts', id)\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'object_info.json'), readableStringify(spec, 4), 'utf8')\n writeFileSync(join(dir, 'embeddings.json'), JSON.stringify(embeddings), 'utf8')\n\n const parsed = new ComfySchema({ spec, embeddings })\n const dts = parsed.codegenDTS({ hostId: id })\n // --out: explicit sdk home (the committed cloud catalog) — the json dumps\n // above still cache under .comfy-ts/hosts/<id>/, but the sdk must exist at\n // ONE tsconfig-visible path only, so it skips the hosts dir entirely\n const out = getFlag('out')\n const outPath = out != null ? resolve(process.cwd(), out) : join(dir, 'sdk.d.ts')\n if (out != null) mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, dts, 'utf8')\n console.log(`[comfy-ts gen] 🟢 ${outPath} (${parsed.nodes.length} nodes, ${(dts.length / 1024).toFixed(0)}kB)`)\n if (out == null)\n console.log(`[comfy-ts gen] add \".comfy-ts/hosts/**/sdk.d.ts\" to your tsconfig \"include\" to activate the types`)\n return 0\n}\n","// refresh the local mirror of what ComfyUI-Lora-Manager knows about a host's loras\nimport { readdirSync } from 'node:fs'\nimport { join } from 'pathe'\nimport { flagReader } from 'src/cli/flags.ts'\nimport { buildLoraMirror, readLoraMirror, writeLoraMirror } from 'src/host/loraInfoCache.ts'\nimport { fetchLoraList, lmModelName, lmTrainedWords } from 'src/host/loraManagerApi.ts'\nimport { ComfyTS } from 'src/state.ts'\n\nconst DEFAULT_HOST_URL = 'http://127.0.0.1:8188'\n\n/** host ids already known on disk — `.comfy-ts/hosts/<id>/` is created by `comfy-ts gen` */\nfunction knownHostIds(): string[] {\n try {\n return readdirSync(join(process.cwd(), '.comfy-ts', 'hosts'), { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => e.name)\n .sort()\n } catch {\n return []\n }\n}\n\nexport async function runLoras(args: string[]): Promise<number> {\n const getFlag = flagReader(args)\n\n // --id: explicit, else the only host folder on disk (unambiguous), else loud\n const known = knownHostIds()\n const explicitId = getFlag('id')\n const id = explicitId ?? (known.length === 1 ? known[0] : null)\n if (id == null) {\n const hint =\n known.length === 0 ? 'none yet — run `comfy-ts gen --id <host-id> --host <url>` first' : known.join(', ')\n console.error(`[comfy-ts loras] 🔴 --id <host-id> is required (known: ${hint})`)\n return 1\n }\n // a typo'd id used to be CREATED as a side effect of registering the host, and\n // the junk folder then broke the `--id` default (and outline's) for good\n if (explicitId != null && known.length > 0 && !known.includes(explicitId)) {\n console.error(\n `[comfy-ts loras] 🔴 unknown host id '${explicitId}' (known: ${known.join(', ')}). Run \\`comfy-ts gen --id ${explicitId} --host <url>\\` first if it is new.`,\n )\n return 1\n }\n\n // ComfyTS FIRST: every .comfy-ts path, the mirror's included, resolves through the global\n const comfy = ComfyTS.create()\n\n // --host: explicit, else the url the last sync remembered for this id\n const previous = readLoraMirror(id)\n const hostUrl = getFlag('host') ?? (previous?.hostUrl !== '' ? previous?.hostUrl : null) ?? DEFAULT_HOST_URL\n\n const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY\n const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })\n\n console.log(`[comfy-ts loras] sweeping ${hostUrl} /api/lm/loras/list …`)\n const sweep = await fetchLoraList(host)\n if (sweep.status === 'absent') {\n console.error(\n `[comfy-ts loras] 🔴 ${hostUrl} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.`,\n )\n return 1\n }\n if (sweep.status === 'unreachable') {\n console.error(`[comfy-ts loras] 🔴 ${hostUrl} unreachable — ${sweep.reason}. Mirror left untouched.`)\n return 1\n }\n if (sweep.status === 'partial') {\n // writing this would DELETE loras from the mirror that are alive on the\n // host, and every surface would then quietly not know them\n console.error(\n `[comfy-ts loras] 🔴 the sweep broke off after ${sweep.items.length} loras (${sweep.reason}). Writing that would drop every lora past it, so the mirror is left untouched. Re-run when the host is healthy.`,\n )\n return 1\n }\n\n const mirror = buildLoraMirror({ hostId: id, hostUrl, fetchedAt: new Date().toISOString(), items: sweep.items })\n const path = writeLoraMirror(mirror)\n\n // what actually moved since the last sync — the whole point of running it again\n const before = previous?.loras ?? {}\n const added: string[] = []\n const changed: string[] = []\n let withWords = 0\n for (const [key, item] of Object.entries(mirror.loras)) {\n const words = lmTrainedWords(item)\n if (words.length > 0) withWords++\n const old = before[key]\n if (old == null) {\n if (words.length > 0) added.push(`${key} → ${words.join(', ')}`)\n else added.push(key)\n } else if (lmTrainedWords(old).join('\\0') !== words.join('\\0')) {\n changed.push(`${key} → ${words.length === 0 ? '(cleared)' : words.join(', ')}`)\n }\n }\n const removed = Object.keys(before).filter((k) => mirror.loras[k] == null)\n\n const sample = (label: string, lines: string[]): void => {\n if (lines.length === 0) return\n console.log(`[comfy-ts loras] ${label} (${lines.length}):`)\n for (const line of lines.slice(0, 10)) console.log(` ${line}`)\n if (lines.length > 10) console.log(` … +${lines.length - 10} more`)\n }\n sample('added', added)\n sample('trigger words changed', changed)\n sample('gone from the host', removed)\n\n const named = Object.values(mirror.loras).filter((i) => lmModelName(i) != null).length\n console.log(\n `[comfy-ts loras] 🟢 ${path} — ${mirror.count} loras, ${withWords} with trigger words, ${named} with a model name`,\n )\n if (previous == null) console.log(`[comfy-ts loras] next time: \\`comfy-ts loras --id ${id}\\` (url remembered)`)\n return 0\n}\n","// outline a generated sdk.d.ts without reading 2MB blind\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'pathe'\n\ntype Section = { name: string; kind: string; start: number; end: number; depth: number }\n\nfunction findDefaultSdk(): string | null {\n const hostsDir = join(process.cwd(), '.comfy-ts', 'hosts')\n if (!existsSync(hostsDir)) return null\n for (const id of readdirSync(hostsDir)) {\n const p = join(hostsDir, id, 'sdk.d.ts')\n if (existsSync(p)) return p\n }\n return null\n}\n\nexport function runOutline(args: string[]): number {\n const linesFlagIx = args.indexOf('--lines')\n const maxLines = linesFlagIx >= 0 ? Number(args[linesFlagIx + 1] ?? 10) : null\n const sectionFlagIx = args.indexOf('--section')\n const wantedSection = sectionFlagIx >= 0 ? args[sectionFlagIx + 1] : null\n const flagValueIxs = new Set([linesFlagIx + 1, sectionFlagIx + 1].filter((ix) => ix > 0))\n const fileArg = args.find((a, ix) => !a.startsWith('--') && !flagValueIxs.has(ix))\n\n const file = fileArg ?? findDefaultSdk()\n if (file == null || !existsSync(file)) {\n console.error('[sdk-outline] 🔴 no sdk.d.ts found; pass a path explicitly')\n return 1\n }\n\n const lines = readFileSync(file, 'utf8').split('\\n')\n\n // scan: track brace depth, record interface/type/namespace declarations up to depth 3\n const sections: Section[] = []\n const stack: Section[] = []\n let depth = 0\n const declRe = /^\\s*(?:export\\s+)?(interface|namespace|type)\\s+([A-Za-z0-9_$]+)/\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? ''\n const m = depth <= 3 ? declRe.exec(line) : null\n const opens = (line.match(/{/g) ?? []).length\n const closes = (line.match(/}/g) ?? []).length\n if (m && (opens > 0 || m[1] === 'type')) {\n const sec: Section = { name: m[2] ?? '?', kind: m[1] ?? '?', start: i + 1, end: i + 1, depth }\n sections.push(sec)\n if (opens > closes) stack.push(sec)\n }\n depth += opens - closes\n while (stack.length > 0 && depth <= (stack[stack.length - 1]?.depth ?? 0)) {\n const closed = stack.pop()\n if (closed) closed.end = i + 1\n }\n // type aliases (no braces): extend until next decl at same depth\n const last = sections[sections.length - 1]\n if (last && last.kind === 'type' && stack[stack.length - 1] !== last) last.end = Math.max(last.end, i)\n }\n\n if (wantedSection) {\n const sec = sections.find((s) => s.name === wantedSection)\n if (sec == null) {\n console.error(\n `[sdk-outline] 🔴 section \"${wantedSection}\" not found. Available: ${sections.map((s) => s.name).join(', ')}`,\n )\n return 1\n }\n const body = lines.slice(sec.start - 1, maxLines ? Math.min(sec.end, sec.start - 1 + maxLines) : sec.end)\n console.log(body.join('\\n'))\n if (maxLines && sec.end - sec.start + 1 > maxLines)\n console.log(`… (${sec.end - sec.start + 1 - maxLines} more lines, ends at line ${sec.end})`)\n } else {\n console.log(`${file} — ${lines.length} lines\\n`)\n for (const s of sections) {\n const indent = ' '.repeat(s.depth)\n console.log(`${indent}${s.kind} ${s.name} [${s.start}-${s.end}] (${s.end - s.start + 1} lines)`)\n if (maxLines) {\n const body = lines.slice(s.start - 1, s.start - 1 + maxLines)\n console.log(body.map((l) => `${indent} │ ${l.trim()}`).join('\\n'))\n }\n }\n }\n return 0\n}\n","#!/usr/bin/env node\n// sidekick CLI: `bunx comfy-ts <command>` — codegen without writing any code\nimport { spawnSync } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport { runGen } from 'src/cli/gen.ts'\nimport { runLoras } from 'src/cli/loras.ts'\nimport { runOutline } from 'src/cli/outline.ts'\n\nconst HELP = `comfy-ts — typed SDK codegen for ComfyUI\n\nUsage:\n comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188] [--api-key <key>] [--out <sdk-path>]\n fetch object_info + embeddings from a live ComfyUI host and write\n .comfy-ts/hosts/<host-id>/{object_info.json,embeddings.json,sdk.d.ts}\n (--api-key or COMFY_CLOUD_API_KEY authenticates via X-API-Key;\n --out relocates ONLY the sdk.d.ts, e.g. a committed cloud catalog)\n\n comfy-ts outline [file] [--lines N] [--section Name]\n outline a generated sdk.d.ts (defaults to the first one in .comfy-ts/hosts/)\n\n comfy-ts loras [--id <host-id>] [--host http://…] [--api-key <key>]\n mirror what the optional ComfyUI-Lora-Manager extension knows about\n every lora into .comfy-ts/hosts/<id>/loras.json: real model names,\n civitai trigger words, tags, base model, preview urls. The TUI then\n fuzzy-matches loras by their human name and auto-injects their trigger\n words into v.prompt (⌃K still overrides, per lora). --id defaults to\n the only host folder on disk, --host to the url the last sync used\n\n comfy-ts tui [dir | workflow-module.ts]\n interactive tweak & re-run over **/*.cflow.ts modules (exporting\n host.defineWorkflow(...)); no arg scans cwd + the examples bundled\n with comfy-ts, an explicit dir/file limits to it (file preselected)\n\n comfy-ts serve [dir | workflow-module.ts] [--port 8288] [--bind 127.0.0.1]\n drafts as a local HTTP generation API: POST /generate/<module>/<draft>\n with { ...vars } overriding the draft's values (blocking; raw image\n bytes under Accept: image/*), GET /drafts self-describes every var,\n GET /outputs/... serves the results. No bundled examples, no auth.\n\n comfy-ts help\n`\n\nasync function main(): Promise<number> {\n const [cmd, ...rest] = process.argv.slice(2)\n if (cmd === 'gen') return runGen(rest)\n if (cmd === 'outline') return runOutline(rest)\n if (cmd === 'loras') return runLoras(rest)\n if (cmd === 'tui' || cmd === 'serve') {\n // .cflow.ts workflow modules need bun: node refuses to strip types under\n // node_modules, exactly where the packaged examples live — and the bin's\n // node shebang means `bunx comfy-ts tui|serve` lands here under NODE. Hop\n // to bun when we are not already in it; without bun, degrade loudly.\n if (process.versions.bun == null) {\n const self = fileURLToPath(import.meta.url)\n const res = spawnSync('bun', [self, cmd, ...rest], { stdio: 'inherit' })\n if (res.error == null) return res.status ?? 1\n console.error(\n `[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`,\n )\n }\n if (cmd === 'serve') {\n const { runServe } = await import('src/cli/serve/run-serve.ts')\n return runServe(rest)\n }\n // lazy import: keeps ink/react out of the codegen paths\n const { runTui } = await import('src/cli/tui/run-tui.tsx')\n return runTui(rest)\n }\n console.log(HELP)\n return cmd == null || cmd === 'help' ? 0 : 1\n}\n\n// a thrown command (a flag with no value, an unreadable path) must print ONE\n// clear line and exit non-zero, never a raw unhandled-rejection stack\nprocess.exitCode = await main().catch((e: unknown) => {\n console.error(`[comfy-ts] 🔴 ${e instanceof Error ? e.message : String(e)}`)\n return 1\n})\n"],"mappings":";;;;;;;;;;;;;AAKA,SAAgB,WAAW,MAAiD;C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AC5D,QAAQ,IAAI,KAAK,KAAK,MAAM,GAAG,OAAO,OAAO,EAAE,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC;GACtE;EACH;CACH;CACA,OAAO;AACV;;;ACzEA,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCb,eAAe,OAAwB;CACpC,MAAM,CAAC,KAAK,GAAG,QAAQ,QAAQ,KAAK,MAAM,CAAC;CAC3C,IAAI,QAAQ,OAAO,OAAO,OAAO,IAAI;CACrC,IAAI,QAAQ,WAAW,OAAO,WAAW,IAAI;CAC7C,IAAI,QAAQ,SAAS,OAAO,SAAS,IAAI;CACzC,IAAI,QAAQ,SAAS,QAAQ,SAAS;EAKnC,IAAI,QAAQ,SAAS,OAAO,MAAM;GAE/B,MAAM,MAAM,UAAU,OAAO;IADhB,cAAc,OAAO,KAAK,GACN;IAAG;IAAK,GAAG;GAAI,GAAG,EAAE,OAAO,UAAU,CAAC;GACvE,IAAI,IAAI,SAAS,MAAM,OAAO,IAAI,UAAU;GAC5C,QAAQ,MACL,aAAa,IAAI,mBAAmB,IAAI,MAAM,QAAQ,gJACzD;EACH;EACA,IAAI,QAAQ,SAAS;GAClB,MAAM,EAAE,aAAa,MAAM,OAAO;GAClC,OAAO,SAAS,IAAI;EACvB;EAEA,MAAM,EAAE,WAAW,MAAM,OAAO;EAChC,OAAO,OAAO,IAAI;CACrB;CACA,QAAQ,IAAI,IAAI;CAChB,OAAO,OAAO,QAAQ,QAAQ,SAAS,IAAI;AAC9C;AAIA,QAAQ,WAAW,MAAM,KAAK,CAAC,CAAC,OAAO,MAAe;CACnD,QAAQ,MAAM,iBAAiB,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAAG;CAC3E,OAAO;AACV,CAAC"}
package/dist/index.cjs CHANGED
@@ -134,7 +134,7 @@ function createNodeStorage() {
134
134
  }
135
135
  //#endregion
136
136
  //#region package.json
137
- var version = "2.3.0";
137
+ var version = "2.4.1";
138
138
  //#endregion
139
139
  //#region src/litegraph/LiteGraphLinkID.ts
140
140
  const asLiteGraphLinkID = (id) => id;
@@ -766,7 +766,7 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
766
766
  };
767
767
  //#endregion
768
768
  //#region src/sdk-generator/inputWidgetKind.ts
769
- const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
769
+ const isRecord$1 = (x) => typeof x === "object" && x != null && !Array.isArray(x);
770
770
  /**
771
771
  * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.
772
772
  * The frontend creates the control widget on truthiness, and real 2026 hosts
@@ -783,7 +783,7 @@ const flattenInputSections = (inputs) => {
783
783
  const out = [];
784
784
  for (const section of ["required", "optional"]) {
785
785
  const sec = inputs[section];
786
- if (!isRecord(sec)) continue;
786
+ if (!isRecord$1(sec)) continue;
787
787
  for (const [name, spec] of Object.entries(sec)) {
788
788
  if (!Array.isArray(spec) || spec.length === 0) continue;
789
789
  const t = spec[0];
@@ -803,10 +803,10 @@ const parseDynamicOptions = (options) => {
803
803
  if (options.length === 0) return null;
804
804
  const out = [];
805
805
  for (const entry of options) {
806
- if (!isRecord(entry)) return null;
806
+ if (!isRecord$1(entry)) return null;
807
807
  const key = entry["key"];
808
808
  const inputs = entry["inputs"];
809
- if (typeof key !== "string" || !isRecord(inputs)) return null;
809
+ if (typeof key !== "string" || !isRecord$1(inputs)) return null;
810
810
  out.push({
811
811
  key,
812
812
  inputs: flattenInputSections(inputs)
@@ -830,7 +830,7 @@ const parseContainer = (template) => {
830
830
  return {
831
831
  kind: "dynamic-container",
832
832
  instanceNames: names,
833
- requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
833
+ requiredCount: isRecord$1(input) && isRecord$1(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
834
834
  };
835
835
  };
836
836
  /**
@@ -841,8 +841,8 @@ const parseContainer = (template) => {
841
841
  * typed instance keys and the container stays builderBase territory.
842
842
  */
843
843
  const containerInstanceSlotType = (opts) => {
844
- const template = (isRecord(opts) ? opts : null)?.["template"];
845
- if (!isRecord(template) || !isRecord(template["input"])) return null;
844
+ const template = (isRecord$1(opts) ? opts : null)?.["template"];
845
+ if (!isRecord$1(template) || !isRecord$1(template["input"])) return null;
846
846
  const subs = flattenInputSections(template["input"]);
847
847
  const first = subs[0];
848
848
  if (subs.length !== 1 || first == null || typeof first.type !== "string") return null;
@@ -868,7 +868,7 @@ const EMPTY_CONFIG_FRONTEND_WIDGETS = { LOAD_3D: { prefixValues: [
868
868
  "clear"
869
869
  ] } };
870
870
  const classifyWidgetInput = (p) => {
871
- const o = isRecord(p.opts) ? p.opts : null;
871
+ const o = isRecord$1(p.opts) ? p.opts : null;
872
872
  if (o?.["forceInput"] === true) return { kind: "slot" };
873
873
  if (Array.isArray(p.type) || p.isEnumUnion === true) {
874
874
  const tn = typeof p.type === "string" ? p.type : "COMBO";
@@ -907,8 +907,8 @@ const classifyWidgetInput = (p) => {
907
907
  };
908
908
  }
909
909
  const template = o?.["template"];
910
- if (isRecord(template)) {
911
- if (isRecord(template["input"])) return parseContainer(template);
910
+ if (isRecord$1(template)) {
911
+ if (isRecord$1(template["input"])) return parseContainer(template);
912
912
  return { kind: "slot" };
913
913
  }
914
914
  if (o?.["socketless"] === true) return {
@@ -939,7 +939,7 @@ const classifySchemaInput = (input) => classifyWidgetInput({
939
939
  * backend accepts an explicit null but errors on an ABSENT required key.
940
940
  */
941
941
  const defaultValueForWidget = (p) => {
942
- const o = isRecord(p.opts) ? p.opts : null;
942
+ const o = isRecord$1(p.opts) ? p.opts : null;
943
943
  if (o != null && o["default"] !== void 0) return o["default"];
944
944
  const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
945
945
  if (widgetTypeName === "INT" || widgetTypeName === "FLOAT") return 0;
@@ -1030,7 +1030,7 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1030
1030
  if (value == null) return null;
1031
1031
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
1032
1032
  if (Array.isArray(value)) return { __value__: value };
1033
- if (!p.strict && isRecord(value)) return value;
1033
+ if (!p.strict && isRecord$1(value)) return value;
1034
1034
  throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
1035
1035
  };
1036
1036
  /** named wins, then positional cursor (+prefixLen skips leading button values, LOAD_3D); filled=true when both miss (caller falls back to the schema default) */
@@ -1681,8 +1681,8 @@ var LiteGraphCtx = class {
1681
1681
  //#endregion
1682
1682
  //#region src/runner/outputPath.ts
1683
1683
  /**
1684
- * local output naming, relative to `.comfy-ts/outputs/` (his repro
1685
- * 2026-07-31): the server filename is NOT unique — cloud hosts reset the
1684
+ * local output naming, relative to `.comfy-ts/outputs/`:
1685
+ * the server filename is NOT unique — cloud hosts reset the
1686
1686
  * `_00001_` counter every run, so trusting it overwrote the same file — and
1687
1687
  * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
1688
1688
  * prefix. Local names are ours: dir from the prompt's own filename_prefix
@@ -1727,7 +1727,7 @@ const withExtension = (path, ext) => {
1727
1727
  /**
1728
1728
  * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR
1729
1729
  * was already CLAIMED by a still-downloading retrieval (two same-second runs
1730
- * on a counter-resetting cloud host compute the same name — reviewer catch).
1730
+ * on a counter-resetting cloud host compute the same name).
1731
1731
  * The chosen path is claimed before returning.
1732
1732
  */
1733
1733
  const uniquifyOutputPath = (p) => {
@@ -3838,6 +3838,7 @@ var ResilientWebSocketClient = class {
3838
3838
  this.messageBuffer = [];
3839
3839
  this.isOpen = false;
3840
3840
  this.debugMessages = [];
3841
+ this.hasEverOpened = false;
3841
3842
  this.permanentlyClosed = false;
3842
3843
  this.url = options.url();
3843
3844
  this.connect();
@@ -3889,6 +3890,7 @@ var ResilientWebSocketClient = class {
3889
3890
  ws.onopen = () => {
3890
3891
  if (ws !== this.currentWS) return;
3891
3892
  this.addInfo("✅ WebSocket connected to " + this.url);
3893
+ this.hasEverOpened = true;
3892
3894
  this.isOpen = true;
3893
3895
  this.options.onConnectOrReconnect();
3894
3896
  this.flushMessageBuffer();
@@ -3899,6 +3901,11 @@ var ResilientWebSocketClient = class {
3899
3901
  this.options.onClose();
3900
3902
  if (this.permanentlyClosed) return;
3901
3903
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
3904
+ if (!this.hasEverOpened && this.options.onFirstConnectFailed != null) {
3905
+ this.permanentlyClosed = true;
3906
+ this.options.onFirstConnectFailed(/* @__PURE__ */ new Error(`connection refused (code=${event.code}${event.reason === "" ? "" : `, ${event.reason}`})`));
3907
+ return;
3908
+ }
3902
3909
  this.addInfo("⏱️ reconnecting in 2 seconds...");
3903
3910
  this.reconnectTimeout = setTimeout(() => void this.connect(), 2e3);
3904
3911
  };
@@ -3920,6 +3927,191 @@ var ResilientWebSocketClient = class {
3920
3927
  }
3921
3928
  };
3922
3929
  //#endregion
3930
+ //#region src/utils/isRecord.ts
3931
+ /** narrows unknown wire json to an indexable object (arrays and null excluded) */
3932
+ function isRecord(v) {
3933
+ return typeof v === "object" && v !== null && !Array.isArray(v);
3934
+ }
3935
+ (0, arktype.type)({
3936
+ items: "unknown[]",
3937
+ "total?": "number"
3938
+ });
3939
+ function readString(item, key) {
3940
+ const v = item[key];
3941
+ return typeof v === "string" && v !== "" ? v : null;
3942
+ }
3943
+ function readStringArray(item, key) {
3944
+ const v = item[key];
3945
+ if (!Array.isArray(v)) return [];
3946
+ return v.filter((x) => typeof x === "string" && x !== "");
3947
+ }
3948
+ function lmModelName(item) {
3949
+ return readString(item, "model_name");
3950
+ }
3951
+ function lmBaseModel(item) {
3952
+ return readString(item, "base_model");
3953
+ }
3954
+ function lmPreviewUrl(item) {
3955
+ return readString(item, "preview_url");
3956
+ }
3957
+ function lmTags(item) {
3958
+ return readStringArray(item, "tags");
3959
+ }
3960
+ /** the trigger words: civitai's `trainedWords`, absent for a lora nobody published */
3961
+ function lmTrainedWords(item) {
3962
+ const civitai = item["civitai"];
3963
+ if (!isRecord(civitai)) return [];
3964
+ return readStringArray(civitai, "trainedWords");
3965
+ }
3966
+ /**
3967
+ * the ONE key space where a host's object_info spelling of a lora meets
3968
+ * lora-manager's: lowercase, forward slashes, no model extension.
3969
+ * `styles\Aurora.safetensors` and lm's folder `styles` + file_name `aurora`
3970
+ * both become `styles/aurora`.
3971
+ */
3972
+ function loraKey(name) {
3973
+ return name.replaceAll("\\", "/").replace(/\.(safetensors|st|pt|ckpt)$/i, "").toLowerCase();
3974
+ }
3975
+ /** the file's own name, windows separators included (`styles\x.safetensors` → `x.safetensors`) */
3976
+ function loraBasename(name) {
3977
+ return (0, pathe.basename)(name.replaceAll("\\", "/"));
3978
+ }
3979
+ //#endregion
3980
+ //#region src/host/loraInfoCache.ts
3981
+ function loraMirrorPath(hostId) {
3982
+ return comfyts.resolveFromHosts((0, pathe.join)(hostId, "loras.json"));
3983
+ }
3984
+ /** null = never synced (or unreadable, which is LOGGED) */
3985
+ function readLoraMirror(hostId) {
3986
+ const path = loraMirrorPath(hostId);
3987
+ const text = getComfyStorage().readTextIfExists(path);
3988
+ if (text == null) return null;
3989
+ try {
3990
+ const raw = JSON.parse(text);
3991
+ if (!isRecord(raw)) return null;
3992
+ const rawLoras = raw["loras"];
3993
+ if (!isRecord(rawLoras)) return null;
3994
+ const loras = {};
3995
+ for (const [key, item] of Object.entries(rawLoras)) if (isRecord(item)) loras[key] = item;
3996
+ const str = (key, fallback) => {
3997
+ const v = raw[key];
3998
+ return typeof v === "string" ? v : fallback;
3999
+ };
4000
+ return {
4001
+ hostId: str("hostId", hostId),
4002
+ hostUrl: str("hostUrl", ""),
4003
+ fetchedAt: str("fetchedAt", ""),
4004
+ count: Object.keys(loras).length,
4005
+ loras
4006
+ };
4007
+ } catch (e) {
4008
+ logError(`[loraInfoCache] unreadable ${path}: ${String(e)}`);
4009
+ return null;
4010
+ }
4011
+ }
4012
+ /**
4013
+ * the read model: each registered host's mirror, kept PER HOST.
4014
+ *
4015
+ * Per host, not merged into one map, because the same file name on two hosts is
4016
+ * routinely a different model. A merged map served whichever host loaded first,
4017
+ * so on the other host the overlay showed the wrong model name and the prompt
4018
+ * silently received the wrong trigger words — a bad generation with no error
4019
+ * anywhere. Callers that know their host say so; the rest fall back to any host
4020
+ * that has the lora, which is still better than nothing for a display name.
4021
+ *
4022
+ * Plain (non-observable) on purpose: the loras overlay reads this from inside a
4023
+ * mobx render. The storage seam has no readdir, so the host set comes from
4024
+ * `comfyts.hosts` — exactly the hosts this process can be asked about.
4025
+ */
4026
+ const byHost = /* @__PURE__ */ new Map();
4027
+ /** hosts already looked for, INCLUDING the ones with no mirror (see reloadLoraInfoCache) */
4028
+ const loadedHostIds = /* @__PURE__ */ new Set();
4029
+ function ensureLoaded() {
4030
+ for (const hostId of comfyts.hosts.keys()) {
4031
+ if (loadedHostIds.has(hostId)) continue;
4032
+ loadedHostIds.add(hostId);
4033
+ const mirror = readLoraMirror(hostId);
4034
+ if (mirror == null) continue;
4035
+ byHost.set(hostId, new Map(Object.entries(mirror.loras)));
4036
+ }
4037
+ }
4038
+ /**
4039
+ * forget everything loaded, so the next read picks up a fresh `comfy-ts loras`.
4040
+ * A long-lived process (the TUI, `comfy-ts serve`) has no other way to see a
4041
+ * re-sync that happened in another terminal.
4042
+ */
4043
+ function reloadLoraInfoCache() {
4044
+ byHost.clear();
4045
+ loadedHostIds.clear();
4046
+ }
4047
+ /**
4048
+ * the lm item for a raw lora name (`styles\x.safetensors`).
4049
+ * `hostId` picks the mirror that actually describes this host's file; without
4050
+ * it, any host that knows the name answers. null when unsynced/unknown.
4051
+ */
4052
+ function getLoraInfo(name, hostId) {
4053
+ ensureLoaded();
4054
+ const key = loraKey(name);
4055
+ if (hostId != null) {
4056
+ const own = byHost.get(hostId);
4057
+ if (own != null) return own.get(key) ?? null;
4058
+ }
4059
+ for (const mirror of byHost.values()) {
4060
+ const hit = mirror.get(key);
4061
+ if (hit != null) return hit;
4062
+ }
4063
+ return null;
4064
+ }
4065
+ /** civitai trigger words for this lora, in civitai's order */
4066
+ function getLoraTriggerWords(name, hostId) {
4067
+ const info = getLoraInfo(name, hostId);
4068
+ return info == null ? [] : lmTrainedWords(info);
4069
+ }
4070
+ /** the human name (`Aurora Ink Wash`), falling back to the file's own name */
4071
+ function getLoraDisplayName(name, hostId) {
4072
+ const info = getLoraInfo(name, hostId);
4073
+ return (info == null ? null : lmModelName(info)) ?? loraBasename(name);
4074
+ }
4075
+ /** server-relative preview url from the mirror, null when unsynced/unknown */
4076
+ function getLoraPreviewUrl(name, hostId) {
4077
+ const info = getLoraInfo(name, hostId);
4078
+ return info == null ? null : lmPreviewUrl(info);
4079
+ }
4080
+ /** the lora's NAMES: the file, and the model name a human would call it by */
4081
+ function loraSearchNames(name, hostId) {
4082
+ const names = [loraBasename(name), name.replaceAll("\\", "/")];
4083
+ const info = getLoraInfo(name, hostId);
4084
+ const modelName = info == null ? null : lmModelName(info);
4085
+ if (modelName != null) names.push(modelName);
4086
+ return names;
4087
+ }
4088
+ /** the lora's FREE TEXT: tags, base model, trigger words */
4089
+ function loraSearchText(name, hostId) {
4090
+ const info = getLoraInfo(name, hostId);
4091
+ if (info == null) return [];
4092
+ const text = [...lmTags(info), ...lmTrainedWords(info)];
4093
+ const baseModel = lmBaseModel(info);
4094
+ if (baseModel != null) text.push(baseModel);
4095
+ return text;
4096
+ }
4097
+ /**
4098
+ * the loras overlay filter: find a lora by its human name, not only by the file
4099
+ * name. EVERY whitespace-separated token must be a SUBSTRING of some field — order
4100
+ * free, so `aurora ink`, `ink aurora` and `styles wash` all land on the same
4101
+ * lora. NOT fuzzyMatch: a subsequence match over phrases this long matches
4102
+ * nearly everything. Measured on a real collection, filtering by each lora's
4103
+ * own file name: this rule peaks at 8 hits where fuzzyMatch matched a third of
4104
+ * every lora present.
4105
+ * Fields are matched one by one, never as a concatenated haystack, for the same
4106
+ * reason. `tests/lora-corpus.private.test.ts` keeps that measurement runnable.
4107
+ */
4108
+ function loraMatchesFilter(name, filter, hostId) {
4109
+ const tokens = filter.toLowerCase().split(/\s+/).filter((t) => t !== "");
4110
+ if (tokens.length === 0) return true;
4111
+ const fields = [...loraSearchNames(name, hostId), ...loraSearchText(name, hostId)].map((f) => f.toLowerCase());
4112
+ return tokens.every((token) => fields.some((field) => field.includes(token)));
4113
+ }
4114
+ //#endregion
3923
4115
  //#region src/vars/loraKeywords.ts
3924
4116
  /**
3925
4117
  * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras
@@ -3927,6 +4119,12 @@ var ResilientWebSocketClient = class {
3927
4119
  * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
3928
4120
  * and must survive a cache wipe). Observable map: overlay rows re-render on
3929
4121
  * assignment. Keys are the RAW lora names (folder/file.safetensors).
4122
+ *
4123
+ * This file is the OVERRIDE layer. Below it sits the lora-manager mirror's
4124
+ * civitai trigger words (src/host/loraInfoCache.ts, refreshed by
4125
+ * `comfy-ts loras`), so most loras carry a keyword without anyone typing one.
4126
+ * The overlay renders a mirror-sourced keyword dim and a hand-typed one yellow,
4127
+ * and ⌃D drops the override to fall back to the mirror again.
3930
4128
  */
3931
4129
  const keywords = mobx.observable.map();
3932
4130
  let loaded = false;
@@ -3949,18 +4147,50 @@ function loadOnce() {
3949
4147
  logError(`[loraKeywords] unreadable ${path}: ${String(e)}`);
3950
4148
  }
3951
4149
  }
3952
- function getLoraKeyword(name) {
4150
+ /** the hand keyword when this lora HAS an entry (`''` included), else the mirror's trigger words */
4151
+ function getLoraKeyword(name, hostId) {
3953
4152
  loadOnce();
3954
- return keywords.get(name) ?? "";
4153
+ const hand = keywords.get(name);
4154
+ if (hand != null) return hand;
4155
+ return getLoraTriggerWords(name, hostId).join(", ");
3955
4156
  }
3956
- /** empty keyword deletes the entry; every set writes the file (tiny, rare) */
3957
- function setLoraKeyword(name, keyword) {
4157
+ /** true when the keyword shown comes from the lora-manager mirror, not from ⌃K */
4158
+ function isLoraKeywordFromMirror(name, hostId) {
4159
+ loadOnce();
4160
+ return !keywords.has(name) && getLoraTriggerWords(name, hostId).length > 0;
4161
+ }
4162
+ /** what `clearLoraKeywordOverride` would restore this lora to, `''` when nothing */
4163
+ function loraKeywordFromMirror(name, hostId) {
4164
+ return getLoraTriggerWords(name, hostId).join(", ");
4165
+ }
4166
+ /**
4167
+ * drop the hand entry entirely, so the mirror's trigger words apply again.
4168
+ * The way BACK from an empty-string tombstone: without it, clearing a keyword on
4169
+ * a lora that has trigger words was a one-way door only a text editor could undo.
4170
+ */
4171
+ function clearLoraKeywordOverride(name) {
4172
+ loadOnce();
4173
+ if (!keywords.has(name)) return;
4174
+ (0, mobx.runInAction)(() => void keywords.delete(name));
4175
+ writeKeywords();
4176
+ }
4177
+ /**
4178
+ * empty keyword deletes the entry — EXCEPT when the mirror has trigger words for
4179
+ * this lora: there `''` is stored as an explicit tombstone, the only way to say
4180
+ * "inject nothing" about a lora civitai gave words to. Every set writes the file
4181
+ * (tiny, rare).
4182
+ */
4183
+ function setLoraKeyword(name, keyword, hostId) {
3958
4184
  loadOnce();
3959
4185
  const trimmed = keyword.trim();
3960
4186
  (0, mobx.runInAction)(() => {
3961
- if (trimmed === "") keywords.delete(name);
4187
+ if (trimmed === "" && getLoraTriggerWords(name, hostId).length === 0) keywords.delete(name);
3962
4188
  else keywords.set(name, trimmed);
3963
4189
  });
4190
+ writeKeywords();
4191
+ }
4192
+ /** every set writes the file: it is tiny and hand-edited rarely */
4193
+ function writeKeywords() {
3964
4194
  const path = filePath();
3965
4195
  try {
3966
4196
  getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
@@ -4067,7 +4297,7 @@ var PromptVar = class extends ComfyVarBase {
4067
4297
  injectedKeywords() {
4068
4298
  const src = this.promptOpts.loraKeywordsFrom;
4069
4299
  if (src == null) return [];
4070
- return [...new Set(src.activeNames().map(getLoraKeyword).filter((k) => k !== ""))];
4300
+ return [...new Set(src.activeNames().map((name) => getLoraKeyword(name, src.hostId)).filter((k) => k !== ""))];
4071
4301
  }
4072
4302
  outValue() {
4073
4303
  const pos = [];
@@ -4259,6 +4489,7 @@ var LorasVar = class LorasVar extends ComfyVar {
4259
4489
  this.kind = "loras";
4260
4490
  this.prev = {};
4261
4491
  this.resolvedOptions = null;
4492
+ this.hostId = void 0;
4262
4493
  }
4263
4494
  get options() {
4264
4495
  if (!(this.optionsSource instanceof RegExp)) return this.optionsSource;
@@ -4269,6 +4500,7 @@ var LorasVar = class LorasVar extends ComfyVar {
4269
4500
  * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
4270
4501
  * values of the SAME object_info enum the generated E_LoraName union comes from */
4271
4502
  bindHost(host) {
4503
+ this.hostId = host.data?.id;
4272
4504
  if (!(this.optionsSource instanceof RegExp)) return;
4273
4505
  this.resolvedOptions = host.schema.getLoras(this.optionsSource);
4274
4506
  }
@@ -4387,7 +4619,7 @@ const DEFAULT_SIZE_PRESETS = [
4387
4619
  }
4388
4620
  ];
4389
4621
  /** width/height picker: presets + free `WxH` entry + optionally the LIVE
4390
- * size of a linked image var (his ask 2026-07-30: the widget shows
4622
+ * size of a linked image var (the widget shows
4391
4623
  * `WxH size of image '<name>'` as a pickable row) */
4392
4624
  var SizeVar = class extends ComfyVar {
4393
4625
  constructor(defaultValue = {
@@ -4987,6 +5219,7 @@ var ComfyHost = class {
4987
5219
  url: () => this.getWSUrl(),
4988
5220
  headers: () => this.authHeaders(),
4989
5221
  onTransportDead: (e) => this.markFailed(e),
5222
+ onFirstConnectFailed: (e) => this.markFailed(new ComfyHostUnreachableError(`host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`)),
4990
5223
  onClose: () => {
4991
5224
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
4992
5225
  }
@@ -5883,19 +6116,31 @@ exports.asMDContent = asMDContent;
5883
6116
  exports.asRelativePath = asRelativePath;
5884
6117
  exports.auto = auto;
5885
6118
  exports.auto_ = auto_;
6119
+ exports.clearLoraKeywordOverride = clearLoraKeywordOverride;
5886
6120
  exports.codegenSDK = codegenSDK;
5887
6121
  exports.convertFlowToLiteGraphJSON = convertFlowToLiteGraphJSON;
5888
6122
  exports.convertLiteGraphToPrompt = convertLiteGraphToPrompt;
5889
6123
  exports.createMemoryStorage = createMemoryStorage;
5890
6124
  exports.exampleImagePath = exampleImagePath;
5891
6125
  exports.getComfyStorage = getComfyStorage;
6126
+ exports.getLoraDisplayName = getLoraDisplayName;
6127
+ exports.getLoraInfo = getLoraInfo;
5892
6128
  exports.getLoraKeyword = getLoraKeyword;
6129
+ exports.getLoraPreviewUrl = getLoraPreviewUrl;
6130
+ exports.getLoraTriggerWords = getLoraTriggerWords;
5893
6131
  exports.hostIdToNamespace = hostIdToNamespace;
6132
+ exports.isLoraKeywordFromMirror = isLoraKeywordFromMirror;
5894
6133
  exports.isTuiActive = isTuiActive;
6134
+ exports.loraKey = loraKey;
6135
+ exports.loraKeywordFromMirror = loraKeywordFromMirror;
6136
+ exports.loraMatchesFilter = loraMatchesFilter;
6137
+ exports.loraSearchNames = loraSearchNames;
6138
+ exports.loraSearchText = loraSearchText;
5895
6139
  exports.loraTag = loraTag;
5896
6140
  exports.normalizeWorkflow = normalizeWorkflow;
5897
6141
  exports.parseHostBase = parseHostBase;
5898
6142
  exports.parseWorkflowJson = parseWorkflowJson;
6143
+ exports.reloadLoraInfoCache = reloadLoraInfoCache;
5899
6144
  exports.renderHttpBase = renderHttpBase;
5900
6145
  exports.renderWsUrl = renderWsUrl;
5901
6146
  exports.resultFailure = resultFailure;