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.
Files changed (55) hide show
  1. package/README.md +6 -4
  2. package/dist/{LogsSt-DFxzQfDc.js → LogsSt-qtFzOKpu.js} +2 -2
  3. package/dist/{LogsSt-DFxzQfDc.js.map → LogsSt-qtFzOKpu.js.map} +1 -1
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +102 -3
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +19 -0
  8. package/dist/index.d.ts +19 -0
  9. package/dist/index.js +102 -3
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-_nrvJYyt.js → run-serve-BK7BA2dn.js} +91 -3
  12. package/dist/run-serve-BK7BA2dn.js.map +1 -0
  13. package/dist/{run-tui-BLEdTsOX.js → run-tui-CQyvMf0N.js} +36 -4
  14. package/dist/run-tui-CQyvMf0N.js.map +1 -0
  15. package/dist/{DefinedWorkflow-BatWaZO1.js → schemaDrift-DjjEtwfx.js} +176 -2
  16. package/dist/schemaDrift-DjjEtwfx.js.map +1 -0
  17. package/dist/serve-web.js +32 -16
  18. package/dist/{state-BbgJeCe6.js → state--wrz0BQc.js} +23 -5
  19. package/dist/state--wrz0BQc.js.map +1 -0
  20. package/dist/web.d.ts +19 -0
  21. package/dist/web.js +102 -3
  22. package/dist/web.js.map +1 -1
  23. package/examples/README.md +1 -0
  24. package/examples/comfy-cloud/capybara-i2v.cflow.ts +2 -0
  25. package/examples/comfy-cloud/ltx25-i2v.cflow.ts +152 -0
  26. package/examples/comfy-cloud/ltx25-t2v.cflow.ts +126 -0
  27. package/examples/comfy-cloud/minimax-music3-t2a.cflow.ts +95 -0
  28. package/examples/comfy-cloud/sdk.d.ts +30724 -24404
  29. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +2 -0
  30. package/examples/comfy-cloud/wan22-i2v.cflow.ts +2 -0
  31. package/examples/comfy-cloud/wan22-t2v.cflow.ts +2 -0
  32. package/examples/rvion/07-local-llm-text-gen.cflow.ts +2 -2
  33. package/examples/rvion/08-qwen-image-21-t2i.cflow.ts +64 -0
  34. package/examples/rvion/09-qwen-image-21-edit.cflow.ts +83 -0
  35. package/package.json +4 -2
  36. package/src/cli/serve/ServeApp.ts +94 -0
  37. package/src/cli/serve/describeVar.ts +7 -0
  38. package/src/cli/serve/favicon.ts +3 -0
  39. package/src/cli/serve/web/api.ts +12 -0
  40. package/src/cli/serve/web/components/VarsForm.tsx +18 -7
  41. package/src/cli/serve/web/components/controls/LorasControl.tsx +102 -6
  42. package/src/cli/serve/web/state/WebSt.ts +79 -0
  43. package/src/cli/serve/web/state/loraSort.ts +39 -0
  44. package/src/cli/serve/web/styles.ts +15 -0
  45. package/src/cli/tui/components/Header.tsx +2 -0
  46. package/src/cli/tui/state/HostSt.ts +34 -0
  47. package/src/graph/ComfyNode.ts +19 -3
  48. package/src/host/ComfyHost.ts +15 -0
  49. package/src/host/loraInfoCache.ts +64 -0
  50. package/src/host/loraManagerApi.ts +27 -0
  51. package/src/host/schemaDrift.ts +87 -0
  52. package/dist/DefinedWorkflow-BatWaZO1.js.map +0 -1
  53. package/dist/run-serve-_nrvJYyt.js.map +0 -1
  54. package/dist/run-tui-BLEdTsOX.js.map +0 -1
  55. package/dist/state-BbgJeCe6.js.map +0 -1
package/dist/web.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"web.js","names":["g","isRecord","isRecord","types","chalk","isRecord","chalk","chalk","chalk","chalk","chalk","chalk","pkgJson.version","globalHack"],"sources":["../src/storage/ComfyStorage.ts","../package.json","../src/litegraph/LiteGraphLinkID.ts","../src/utils/bang.ts","../src/litegraph/expandSubgraphs.ts","../src/litegraph/LiteGraphGroup.ts","../src/litegraph/LiteGraphLink.ts","../src/litegraph/LiteGraphNodeInput.ts","../src/litegraph/LiteGraphSlotIndex.ts","../src/litegraph/LiteGraphNodeOutput.ts","../src/litegraph/LiteGraphNode.ts","../src/litegraph/LiteGraphSubgraphDef.ts","../src/litegraph/LiteGraphJSON.ts","../src/litegraph/normalizeWorkflow.ts","../src/runner/wsBinaryFrame.ts","../src/sdk-generator/Primitives.ts","../src/sdk-generator/inputWidgetKind.ts","../src/sdk-generator/litegraphToApiRequestPayload.ts","../src/utils/isRecord.ts","../src/runner/describePromptRejection.ts","../src/errors/InvalidPromptError.ts","../src/utils/ComfyColors.ts","../src/graph/autoValue.ts","../src/graph/ComfyNodeOutput.ts","../src/graph/ComfyNode.ts","../src/host/ComfyWorkflowBuilder.ts","../src/litegraph/convertFlowToLiteGraphJSON.ts","../src/runner/outputPath.ts","../src/utils/extractErrorMessage.ts","../src/utils/lazySharp.ts","../src/types/index.ts","../src/image-utils/_getPngMetadata.ts","../src/utils/exhaust.ts","../src/utils/sha1.ts","../src/utils/hashArrayBuffer.ts","../src/graph/ComfyNodeID.ts","../src/runner/ComfyWsApi.ts","../src/runner/MediaImage.ts","../src/runner/ComfyExecution.ts","../src/runner/ephemeral.ts","../src/utils/deepCopyNaive.ts","../src/utils/ansi.ts","../src/utils/log.ts","../src/utils/printArkResultInConsole.ts","../src/utils/softValidate.ts","../src/utils/toposort.ts","../src/runner/ComfyWorkflowLayout.ts","../src/runner/ComfyWorkflow.ts","../src/utils/matchesRegex.ts","../src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts","../src/sdk-generator/_pythonModuleToNamespace.ts","../src/sdk-generator/_toQualifiedNodeKey.ts","../src/utils/CodeBuffer.ts","../src/utils/escapeJSKey.ts","../src/sdk-generator/ComfyNodeSchema.ts","../src/sdk-generator/comfyui-sdk-codegen.ts","../src/sdk-generator/comfyui-types.ts","../src/sdk-generator/ComfySchema.ts","../src/sdk-generator/ComfyUIObjectInfoTypes.ts","../src/utils/stringifyReadable.ts","../src/manager/types/ComfyManagerAPIModelList.ts","../src/manager/types/ComfyManagerAPIPluginList.ts","../src/host/ComfyManager.ts","../src/host/ComfyUploader.ts","../src/host/hostUrl.ts","../src/host/ResilientWebsocket.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","../src/host/ComfyHost.ts","../src/utils/downloadFile.ts","../src/manager/loaders/step1_downloadComfyManagerJSONs.ts","../src/utils/githubRegexes.ts","../src/manager/json/custom-node-list.extra.ts","../src/manager/loaders/parseReport.ts","../src/manager/types/ComfyManagerFilePluginList.ts","../src/manager/types/ComfyManagerPluginInfo.ts","../src/manager/loaders/step2_custom-node-list-loader.ts","../src/manager/types/ComfyManagerPluginContentMetadata.ts","../src/manager/types/ComfyManagerPluginEnums.ts","../src/manager/types/ComfyManagerFilePluginContent.ts","../src/manager/loaders/step3_extension-node-map-loader.ts","../src/manager/json/model-list.extra.ts","../src/manager/types/ComfyManagerFileModelInfo.ts","../src/manager/types/ComfyManagerModelInfo.ts","../src/manager/loaders/step4_model-list-loader.ts","../src/manager/types/ComfyManagerAlterInfo.ts","../src/manager/loaders/step5_alter-list-loader.ts","../src/manager/types/ComfyManagerGithubStats.ts","../src/manager/loaders/step6_github-stats-loader.ts","../src/manager/ComfyRegistry.ts","../src/state.ts","../src/utils/loraTag.ts","../src/web.ts"],"sourcesContent":["// 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 } from 'arktype'\nimport type { Branded } from 'src/types/index.ts'\n\nexport const asLiteGraphLinkID = (id: number): LiteGraphLinkID => id as LiteGraphLinkID\nexport const LiteGraphLinkID_ = type.number.atLeast(0).as<Branded<number, { LiteGraphLinkID: true }>>()\nexport type LiteGraphLinkID = typeof LiteGraphLinkID_.infer\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","import type { CanonicalLink, CanonicalNode, CanonicalWorkflow } from 'src/litegraph/CanonicalWorkflow.ts'\nimport { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'\nimport { WorkflowNormalizeError } from 'src/litegraph/normalizeWorkflow.ts'\nimport { bang } from 'src/utils/bang.ts'\n\n/** one exposed slot of a normalized subgraph definition */\nexport type CanonicalSubgraphIO = {\n name: string\n type: string\n}\n\n/** a subgraph definition normalized by the SAME per-node/per-link normalizers as the root */\nexport type CanonicalSubgraphDef = {\n id: string // uuid, referenced by instance nodes' `type`\n name: string\n inputs: CanonicalSubgraphIO[]\n outputs: CanonicalSubgraphIO[]\n nodes: CanonicalNode[]\n links: CanonicalLink[]\n}\n\n/** boundary sentinel ids inside definition link tables */\nconst SUBGRAPH_INPUT_NODE_ID = -10\nconst SUBGRAPH_OUTPUT_NODE_ID = -20\n\n/** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */\nconst MAX_EXPANSION_PASSES = 32\n\n/**\n * widget-kind fallback when a def input slot has no boundary target carrying a\n * widget marker: these litegraph slot types carry widget values. LOCAL copy on\n * purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here\n * (the io-widget era serializes exactly one value per exposed widget slot).\n */\nconst PRIMITIVE_WIDGET_TYPES: ReadonlySet<string> = new Set(['INT', 'FLOAT', 'STRING', 'BOOLEAN', 'COMBO'])\n\n/**\n * inline every subgraph instance (node whose `type` is a definition uuid) into\n * the root graph: fresh numeric ids, boundary links rewired, instance widget\n * values promoted into the inner nodes' `named` overrides. Iterative so nested\n * definitions expand on the next pass. Muted instances are dropped (their\n * consumers resolve unconnected); bypassed instances stay for the converter's\n * passthrough walk, which needs no interior.\n */\nexport const expandSubgraphs = (wf: CanonicalWorkflow, defs: Map<string, CanonicalSubgraphDef>): CanonicalWorkflow => {\n let passes = 0\n while (true) {\n const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== 'bypassed')\n if (expandable.length === 0) return wf\n if (++passes > MAX_EXPANSION_PASSES)\n throw new WorkflowNormalizeError(\n 'subgraph-cycle',\n `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`,\n )\n for (const instance of expandable) {\n if (instance.mode === 'muted') dropMutedInstance(wf, instance)\n else expandOneInstance(wf, instance, bang(defs.get(instance.type)))\n }\n }\n}\n\n/** converter mute semantics applied early: after expansion there is no single node left to skip */\nconst dropMutedInstance = (wf: CanonicalWorkflow, instance: CanonicalNode): void => {\n const dead = new Set<LiteGraphLinkID>()\n for (const link of wf.links) {\n if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id)\n }\n wf.links = wf.links.filter((l) => !dead.has(l.id))\n wf.nodes = wf.nodes.filter((n) => n.id !== instance.id)\n pruneDeadLinkRefs(wf, dead)\n}\n\nconst pruneDeadLinkRefs = (wf: CanonicalWorkflow, dead: ReadonlySet<LiteGraphLinkID>): void => {\n if (dead.size === 0) return\n for (const node of wf.nodes) {\n for (const input of node.inputs) {\n if (input.link != null && dead.has(input.link)) input.link = null\n }\n for (const output of node.outputs) {\n output.links = output.links.filter((id) => !dead.has(id))\n }\n }\n}\n\nconst expandOneInstance = (wf: CanonicalWorkflow, instance: CanonicalNode, def: CanonicalSubgraphDef): void => {\n // 1. fresh numeric ids, deterministic (def node order / def link order)\n let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id))\n let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id))\n const newNodeIds = new Map<number, number>()\n for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId)\n // null = the def link references a node the def does not contain: upstream\n // editors leave STALE links behind after node deletion (corpus-verified,\n // e.g. utility_video_upscale) and the frontend prunes them on load. We drop\n // the link; the consumer resolves unconnected, loud at conversion when required.\n const remapNodeId = (id: number): number | null => newNodeIds.get(id) ?? null\n\n // 2. instance input slot → def input slot, BY NAME (instances may serialize\n // a subset of the def's inputs). A name matching NO def input is LOUD:\n // silently falling back to the positional index would wire the outer feed\n // into the wrong inner slot (corpus-absent today, so a throw is safe)\n const defSlotOfInstanceSlot = new Map<number, number>()\n for (const [k, input] of instance.inputs.entries()) {\n const defSlot = def.inputs.findIndex((d) => d.name === input.name)\n if (defSlot < 0)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): input \"${input.name}\" (slot ${k}) matches no definition input (defined: ${def.inputs.map((d) => d.name).join(', ')})`,\n )\n defSlotOfInstanceSlot.set(k, defSlot)\n }\n\n // 3. outer links INTO the instance, keyed by def input slot\n const outerLinkIntoDefSlot = new Map<number, CanonicalLink>()\n for (const link of wf.links) {\n if (link.targetId !== instance.id) continue\n const defSlot = defSlotOfInstanceSlot.get(link.targetSlot)\n if (defSlot == null)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`,\n )\n outerLinkIntoDefSlot.set(defSlot, link)\n }\n\n // 4. classify definition links: plain interior links clone with fresh ids;\n // input-boundary links (-10 origin) become real links from the outer origin\n // when one exists (else they drop and the inner target falls back to its own\n // widget values); output-boundary links (-20 target) just name the inner\n // producer each def output slot maps to.\n const newLinkIds = new Map<LiteGraphLinkID, LiteGraphLinkID>()\n const splicedLinks: CanonicalLink[] = []\n const producerByOutSlot = new Map<number, { nodeId: number; slot: number }>()\n const passthroughOutSlot = new Map<number, number>() // def out slot → def in slot (-10 → -20 direct)\n const boundaryTargetsByInSlot = new Map<number, { nodeId: number; slot: number }[]>() // remapped inner targets\n for (const link of def.links) {\n const fromInputBoundary = link.originId === SUBGRAPH_INPUT_NODE_ID\n const toOutputBoundary = link.targetId === SUBGRAPH_OUTPUT_NODE_ID\n if (fromInputBoundary && toOutputBoundary) {\n passthroughOutSlot.set(link.targetSlot, link.originSlot)\n continue\n }\n if (toOutputBoundary) {\n const producerId = remapNodeId(link.originId)\n if (producerId != null && !producerByOutSlot.has(link.targetSlot))\n producerByOutSlot.set(link.targetSlot, { nodeId: producerId, slot: link.originSlot })\n continue\n }\n if (fromInputBoundary) {\n const targetId = remapNodeId(link.targetId)\n if (targetId == null) continue\n const target = { nodeId: targetId, slot: link.targetSlot }\n const targets = boundaryTargetsByInSlot.get(link.originSlot) ?? []\n targets.push(target)\n boundaryTargetsByInSlot.set(link.originSlot, targets)\n const outer = outerLinkIntoDefSlot.get(link.originSlot)\n if (outer == null) continue // no outer feed: inner target's input.link nulls at clone time\n const fresh = asLiteGraphLinkID(++nextLinkId)\n newLinkIds.set(link.id, fresh)\n splicedLinks.push({\n id: fresh,\n originId: outer.originId,\n originSlot: outer.originSlot,\n targetId: target.nodeId,\n targetSlot: target.slot,\n type: link.type,\n })\n const originNode = wf.nodes.find((n) => n.id === outer.originId)\n originNode?.outputs[outer.originSlot]?.links.push(fresh)\n continue\n }\n const interiorOrigin = remapNodeId(link.originId)\n const interiorTarget = remapNodeId(link.targetId)\n if (interiorOrigin == null || interiorTarget == null) continue\n const fresh = asLiteGraphLinkID(++nextLinkId)\n newLinkIds.set(link.id, fresh)\n splicedLinks.push({\n id: fresh,\n originId: interiorOrigin,\n originSlot: link.originSlot,\n targetId: interiorTarget,\n targetSlot: link.targetSlot,\n type: link.type,\n })\n }\n\n // 5. clone inner nodes with remapped ids; link refs not in newLinkIds were\n // dropped boundary links → null (the node falls back to its widget values)\n const splicedNodes: CanonicalNode[] = def.nodes.map((inner) => ({\n id: bang(newNodeIds.get(inner.id)),\n type: inner.type,\n title: inner.title,\n mode: inner.mode,\n isVirtualNode: inner.isVirtualNode,\n inputs: inner.inputs.map((i) => ({\n name: i.name,\n type: i.type,\n link: i.link != null ? (newLinkIds.get(i.link) ?? null) : null,\n widgetName: i.widgetName,\n })),\n outputs: inner.outputs.map((o) => ({\n name: o.name,\n type: o.type,\n links: o.links.map((id) => newLinkIds.get(id)).filter((id): id is LiteGraphLinkID => id != null),\n })),\n widgets: { positional: [...inner.widgets.positional], named: { ...inner.widgets.named } },\n pos: [inner.pos[0], inner.pos[1]],\n size: [inner.size[0], inner.size[1]],\n properties: { ...inner.properties },\n }))\n\n // 6. rewire root links FROM the instance's outputs onto the inner producers;\n // outer links INTO the instance were consumed by step 4\n const dead = new Set<LiteGraphLinkID>()\n for (const link of wf.links) {\n if (link.targetId === instance.id) {\n dead.add(link.id)\n continue\n }\n if (link.originId !== instance.id) continue\n const producer = producerByOutSlot.get(link.originSlot)\n if (producer != null) {\n link.originId = producer.nodeId\n link.originSlot = producer.slot\n const producerNode = splicedNodes.find((n) => n.id === producer.nodeId)\n producerNode?.outputs[producer.slot]?.links.push(link.id)\n continue\n }\n const passthroughInSlot = passthroughOutSlot.get(link.originSlot)\n const outer = passthroughInSlot != null ? outerLinkIntoDefSlot.get(passthroughInSlot) : null\n if (outer != null) {\n link.originId = outer.originId\n link.originSlot = outer.originSlot\n continue\n }\n dead.add(link.id) // def output has no producer: consumers resolve unconnected\n }\n wf.links = wf.links.filter((l) => !dead.has(l.id))\n pruneDeadLinkRefs(wf, dead)\n\n // 7. widget promotion (both serialization eras), then splice\n promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot)\n wf.nodes = wf.nodes.filter((n) => n.id !== instance.id)\n wf.nodes.push(...splicedNodes)\n wf.links.push(...splicedLinks)\n}\n\n/**\n * instance widget values land in inner nodes' `named` overrides. TWO eras for\n * the POSITIONAL values:\n * - proxyWidgets era: `properties.proxyWidgets` pairs [innerNodeId, widgetName]\n * zip against the instance's positional values (incl. `control_after_generate`\n * phantom pairs — written to `named` and simply never read, no schema input\n * has that name).\n * - io-widget era (no proxyWidgets): positional values zip against the def's\n * widget-kind input slots in def order, one value per slot (no phantom —\n * corpus-verified). An outer link into the same slot wins in the converter;\n * the named override is still written, matching ComfyUI.\n * PLUS, in both eras, NAMED overrides on the instance keyed by def-input name:\n * that is how a NESTED instance receives its outer values (the previous pass\n * wrote them to `named`), so they must forward through THIS expansion too —\n * named wins over positional, same precedence as the converter.\n */\nconst promoteInstanceWidgets = (\n instance: CanonicalNode,\n def: CanonicalSubgraphDef,\n splicedNodes: CanonicalNode[],\n newNodeIds: Map<number, number>,\n boundaryTargetsByInSlot: Map<number, { nodeId: number; slot: number }[]>,\n): void => {\n const promoteToSlotTargets = (slot: number, value: unknown): void => {\n for (const t of boundaryTargetsByInSlot.get(slot) ?? []) {\n const target = splicedNodes.find((n) => n.id === t.nodeId)\n const input = innerInputAt(splicedNodes, t)\n if (target == null || input == null) continue\n target.widgets.named[input.name] = value\n }\n }\n\n promotePositionalWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets)\n\n for (const [slot, io] of def.inputs.entries()) {\n if (!Object.hasOwn(instance.widgets.named, io.name)) continue\n promoteToSlotTargets(slot, instance.widgets.named[io.name])\n }\n}\n\nconst promotePositionalWidgets = (\n instance: CanonicalNode,\n def: CanonicalSubgraphDef,\n splicedNodes: CanonicalNode[],\n newNodeIds: Map<number, number>,\n boundaryTargetsByInSlot: Map<number, { nodeId: number; slot: number }[]>,\n promoteToSlotTargets: (slot: number, value: unknown) => void,\n): void => {\n const values = instance.widgets.positional\n if (values.length === 0) return // inner nodes keep their serialized defaults\n\n const proxy = instance.properties['proxyWidgets']\n if (Array.isArray(proxy) && proxy.length > 0) {\n const count = Math.min(values.length, proxy.length)\n for (let k = 0; k < count; k++) {\n const pair: unknown = proxy[k]\n if (!Array.isArray(pair) || pair.length !== 2)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): malformed proxyWidgets entry ${JSON.stringify(pair)}`,\n )\n const innerId = Number(pair[0])\n const widgetName = String(pair[1])\n if (innerId < 0) {\n // id -1 names a widget on the subgraph node ITSELF (a promoted io\n // widget): route the value through the matching def input slot\n const slot = def.inputs.findIndex((d) => d.name === widgetName)\n if (slot < 0)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names io widget \"${widgetName}\" but no definition input matches`,\n )\n promoteToSlotTargets(slot, values[k])\n continue\n }\n const target = splicedNodes.find((n) => n.id === newNodeIds.get(innerId))\n if (target == null)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names unknown inner node ${String(pair[0])}`,\n )\n target.widgets.named[widgetName] = values[k]\n }\n return\n }\n\n let valueIndex = 0\n for (const [slot, io] of def.inputs.entries()) {\n const targets = boundaryTargetsByInSlot.get(slot) ?? []\n const isWidgetSlot =\n targets.length > 0\n ? targets.some((t) => innerInputAt(splicedNodes, t)?.widgetName != null)\n : PRIMITIVE_WIDGET_TYPES.has(io.type)\n if (!isWidgetSlot) continue\n if (valueIndex >= values.length) break\n promoteToSlotTargets(slot, values[valueIndex++])\n }\n}\n\nconst innerInputAt = (\n splicedNodes: CanonicalNode[],\n t: { nodeId: number; slot: number },\n): { name: string; widgetName: string | null } | null => {\n const node = splicedNodes.find((n) => n.id === t.nodeId)\n return node?.inputs[t.slot] ?? null\n}\n","import { type } from 'arktype'\nimport type { EmptyRecord, IsEqual } from 'src/types/index.ts'\n\n// prettier-ignore\nexport type LiteGraphGroup = {\n id?: number // 1 (newer serializers only)\n title: string // 'Create Mask'\n bounding: [number, number, number, number] // [1078, -579, 1589, 614]\n color?: string // '#3f789e' (omitted = litegraph default)\n font_size?: number // 24 (omitted = litegraph default)\n flags?: EmptyRecord // {}\n}\n\nexport const LiteGraphGroup_ark = type({\n 'id?': 'number',\n title: 'string',\n bounding: type(['number', 'number', 'number', 'number']),\n 'color?': 'string',\n 'font_size?': 'number',\n // EmptyRecord: an object we don't read any key from\n 'flags?': type.Record('string', 'unknown').as<EmptyRecord>(),\n})\n\ntrue satisfies IsEqual<LiteGraphGroup, typeof LiteGraphGroup_ark.infer>\n","import { type } from 'arktype'\nimport type { IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'\n\n/** v0.4 serialization: links are 6-tuples (our EXPORT path emits this form) */\nexport type LiteGraphLinkTuple = [\n linkId: LiteGraphLinkID, // 9, - linkId\n fromNodeId: number, // 8, - fromNodeId\n fromNodeOutputIx: number, // 0, - fromNodeOutputIx\n toNodeId: number, // 9, - toNodeId\n toNodeInputIx: number, // 0, - toNodeInputIx\n linkType: string, // \"IMAGE\" - type\n]\n\nexport const LiteGraphLinkTuple_ark = type([\n LiteGraphLinkID_, // 9, - linkId\n 'number', // 8, - fromNodeId\n 'number', // 0, - fromNodeOutputIx\n 'number', // 9, - toNodeId\n 'number', // 0, - toNodeInputIx\n 'string', // \"IMAGE\" - linkType\n])\n\ntrue satisfies IsEqual<typeof LiteGraphLinkTuple_ark.infer, LiteGraphLinkTuple>\n\n/** v1 serialization: links are objects (subgraph definition interiors use this) */\nexport type LiteGraphLinkObject = {\n id: LiteGraphLinkID\n origin_id: number // -10 = the subgraph's inputNode boundary\n origin_slot: number\n target_id: number // -20 = the subgraph's outputNode boundary\n target_slot: number\n type: string\n parentId?: number // reroute chain parent (cosmetic)\n}\n\nexport const LiteGraphLinkObject_ark = type({\n id: LiteGraphLinkID_,\n origin_id: 'number',\n origin_slot: 'number',\n target_id: 'number',\n target_slot: 'number',\n type: 'string',\n 'parentId?': 'number',\n})\n\ntrue satisfies IsEqual<typeof LiteGraphLinkObject_ark.infer, LiteGraphLinkObject>\n\nexport type LiteGraphLink = LiteGraphLinkTuple | LiteGraphLinkObject\n\nexport const LiteGraphLink_ark = LiteGraphLinkTuple_ark.or(LiteGraphLinkObject_ark)\n\ntrue satisfies IsEqual<typeof LiteGraphLink_ark.infer, LiteGraphLink>\n","import { type } from 'arktype'\nimport type { IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'\n\nexport type LiteGraphNodeInput = {\n name: string // | 'clip'\n type: string // | 'CLIP'\n link?: LiteGraphLinkID | null // | 5 (widget-backed inputs omit the key)\n shape?: number // | 7\n label?: string // | 'select'\n widget?: {\n name: string // | 'select'\n config?: unknown // | 2022-era serializer only, gone since\n }\n}\n\nexport const LiteGraphNodeInput_ark = type({\n name: 'string',\n type: 'string',\n 'link?': LiteGraphLinkID_.or(type.null),\n 'shape?': 'number',\n 'label?': 'string',\n 'widget?': type({\n name: 'string',\n 'config?': 'unknown',\n }),\n})\n\ntrue satisfies IsEqual<LiteGraphNodeInput, typeof LiteGraphNodeInput_ark.infer>\n","import { type } from 'arktype'\nimport type { Branded } from 'src/types/index.ts'\n\nexport const asLiteGraphSlotIndex = (id: number): LiteGraphSlotIndex => id as LiteGraphSlotIndex\nexport const LiteGraphSlotIndex_ = type.number.atLeast(0).as<Branded<number, { LiteGraphSlotIndex: true }>>()\nexport type LiteGraphSlotIndex = typeof LiteGraphSlotIndex_.infer\n","import { type } from 'arktype'\nimport type { IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'\nimport { type LiteGraphSlotIndex, LiteGraphSlotIndex_ } from 'src/litegraph/LiteGraphSlotIndex.ts'\n\nexport type LiteGraphNodeOutput = {\n name: string\n type: string // 'CONDITIONING'\n links?: LiteGraphLinkID[] | null // unconnected outputs may omit the key\n shape?: number // '2D'\n slot_index?: LiteGraphSlotIndex\n}\n\nexport const LiteGraphNodeOutput_ark = type({\n name: 'string',\n type: 'string',\n 'links?': LiteGraphLinkID_.array().or(type.null),\n 'shape?': 'number',\n 'slot_index?': LiteGraphSlotIndex_,\n})\n\ntrue satisfies IsEqual<LiteGraphNodeOutput, typeof LiteGraphNodeOutput_ark.infer>\n","import { type } from 'arktype'\nimport type { IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphNodeInput, LiteGraphNodeInput_ark } from 'src/litegraph/LiteGraphNodeInput.ts'\nimport { type LiteGraphNodeOutput, LiteGraphNodeOutput_ark } from 'src/litegraph/LiteGraphNodeOutput.ts'\n\n// prettier-ignore\nexport type LiteGraphNode = {\n id: number // 5\n type: string // 'CLIPTextEncode', or a definitions.subgraphs uuid (instance)\n\n // cosmetics\n title?: string // \"Inpaint (Positive)\",\n color?: string // \"#222\", or \"#3f789e\"\n bgcolor?: string // \"#3f789e\" (lowercase, like upstream)\n pos: { '0': number; '1': number } // serialized as [number, number] OR {0,1}\n size: { '0': number; '1': number }\n flags?: Record<string, unknown> // collapsed?, pinned?, … — never read\n order?: number\n /**\n * 0 = always (normal), 1 = on-event, 2 = muted (never),\n * 3 = on-trigger, 4 = bypassed\n */\n mode?: number\n inputs?: LiteGraphNodeInput[]\n outputs?: LiteGraphNodeOutput[]\n\n isVirtualNode?: boolean // frontend only\n /** open record: proxyWidgets (subgraph widget promotion), cnr_id/ver (pack provenance), … */\n properties?: Record<string, unknown>\n /** array form (positional) OR object form (named, e.g. VHS_VideoCombine) */\n widgets_values?: unknown[] | Record<string, unknown>\n}\n\nexport const LiteGraphNode_ark = type({\n id: 'number',\n type: 'string',\n\n // cosmetics\n 'title?': 'string',\n 'color?': 'string',\n 'bgcolor?': 'string',\n pos: { '0': 'number', '1': 'number' },\n size: { '0': 'number', '1': 'number' },\n 'flags?': type.Record('string', 'unknown'),\n 'order?': 'number',\n 'mode?': 'number',\n 'inputs?': LiteGraphNodeInput_ark.array(),\n 'outputs?': LiteGraphNodeOutput_ark.array(),\n 'isVirtualNode?': 'boolean',\n 'properties?': type.Record('string', 'unknown'),\n 'widgets_values?': type('unknown[]').or(type.Record('string', 'unknown')),\n})\n\ntrue satisfies IsEqual<LiteGraphNode, typeof LiteGraphNode_ark.infer>\n","import { type } from 'arktype'\nimport type { EmptyRecord, IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphGroup, LiteGraphGroup_ark } from 'src/litegraph/LiteGraphGroup.ts'\nimport { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'\nimport { type LiteGraphLinkObject, LiteGraphLinkObject_ark } from 'src/litegraph/LiteGraphLink.ts'\nimport { type LiteGraphNode, LiteGraphNode_ark } from 'src/litegraph/LiteGraphNode.ts'\n\n/** one exposed input/output slot of a subgraph definition */\nexport type LiteGraphSubgraphIO = {\n id: string // uuid\n name: string // 'image'\n type: string // 'IMAGE'\n linkIds?: LiteGraphLinkID[]\n label?: string\n localized_name?: string\n pos?: { '0': number; '1': number }\n shape?: number\n}\n\nexport const LiteGraphSubgraphIO_ark = type({\n id: 'string',\n name: 'string',\n type: 'string',\n 'linkIds?': LiteGraphLinkID_.array(),\n 'label?': 'string',\n 'localized_name?': 'string',\n 'pos?': { '0': 'number', '1': 'number' },\n 'shape?': 'number',\n})\n\ntrue satisfies IsEqual<LiteGraphSubgraphIO, typeof LiteGraphSubgraphIO_ark.infer>\n\n/**\n * a subgraph definition body (definitions.subgraphs[] entry). Corpus fact:\n * every one is a v1-shaped interior (object links, `state`) even when the\n * root document is v0.4 — instances reference it via node.type = this uuid.\n */\nexport type LiteGraphSubgraphDef = {\n id: string // uuid, referenced by instance nodes' `type`\n name: string\n version: number // 1 in the whole corpus\n state?: Record<string, unknown> // {lastNodeId, lastLinkId, …} — recomputable\n revision?: number\n config?: EmptyRecord\n extra?: unknown\n nodes: LiteGraphNode[]\n links: LiteGraphLinkObject[]\n groups?: LiteGraphGroup[]\n inputNode: { id: number; bounding: number[] } // id is -10 in boundary links\n outputNode: { id: number; bounding: number[] } // id is -20 in boundary links\n inputs: LiteGraphSubgraphIO[]\n outputs: LiteGraphSubgraphIO[]\n widgets: unknown[] // empty in the whole corpus\n}\n\nexport const LiteGraphSubgraphDef_ark = type({\n id: 'string',\n name: 'string',\n version: 'number',\n 'state?': type.Record('string', 'unknown'),\n 'revision?': 'number',\n 'config?': type.Record('string', 'unknown').as<EmptyRecord>(),\n 'extra?': 'unknown',\n nodes: LiteGraphNode_ark.array(),\n links: LiteGraphLinkObject_ark.array(),\n 'groups?': LiteGraphGroup_ark.array(),\n inputNode: { id: 'number', bounding: 'number[]' },\n outputNode: { id: 'number', bounding: 'number[]' },\n inputs: LiteGraphSubgraphIO_ark.array(),\n outputs: LiteGraphSubgraphIO_ark.array(),\n widgets: 'unknown[]',\n})\n\ntrue satisfies IsEqual<LiteGraphSubgraphDef, typeof LiteGraphSubgraphDef_ark.infer>\n","import { type } from 'arktype'\nimport type { EmptyRecord, IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphGroup, LiteGraphGroup_ark } from 'src/litegraph/LiteGraphGroup.ts'\nimport { type LiteGraphLink, LiteGraphLink_ark } from 'src/litegraph/LiteGraphLink.ts'\nimport { type LiteGraphNode, LiteGraphNode_ark } from 'src/litegraph/LiteGraphNode.ts'\nimport { type LiteGraphSubgraphDef, LiteGraphSubgraphDef_ark } from 'src/litegraph/LiteGraphSubgraphDef.ts'\n\n/** comfy workflows are simply LiteGraphs workflows */\nexport type ComfyWorkflowJSON = LiteGraphJSON\n\n/**\n * litegraph workflow root, TOLERANT: models what upstream actually serializes\n * across eras — v0.4 (tuple links, last_*_id) and v1 (object links, `state`),\n * including hybrid files (v0.4 root + v1-shaped subgraph definitions).\n * Downstream code never reads this shape: `normalizeWorkflow` turns it into\n * the strict `CanonicalWorkflow`.\n */\nexport type LiteGraphJSON = {\n id?: string // uuid (newer serializers)\n revision?: number\n last_node_id?: number // v0.4 (recomputable, absent in v1)\n last_link_id?: number // v0.4\n state?: Record<string, unknown> // v1: {lastNodeId, lastLinkId, …}\n nodes: LiteGraphNode[]\n links: LiteGraphLink[]\n groups?: LiteGraphGroup[]\n config?: EmptyRecord\n extra?: {\n ds?: {\n scale: number\n offset: { 0: number; 1: number }\n }\n }\n models?: unknown[] // model download manifest — never read\n definitions?: { subgraphs: LiteGraphSubgraphDef[] }\n reroutes?: unknown[] // v1 cosmetic link routing — dropped at normalization\n floatingLinks?: unknown[] // v1 cosmetic — dropped at normalization\n version: 0.4 | 1\n}\n\nexport const LiteGraphJSON_ark = type({\n 'id?': 'string',\n 'revision?': 'number',\n 'last_node_id?': 'number',\n 'last_link_id?': 'number',\n 'state?': type.Record('string', 'unknown'),\n nodes: LiteGraphNode_ark.array(),\n links: LiteGraphLink_ark.array(),\n 'groups?': LiteGraphGroup_ark.array(),\n 'config?': type.Record('never', 'never'),\n 'extra?': {\n 'ds?': {\n scale: 'number',\n offset: {\n '0': 'number',\n '1': 'number',\n },\n },\n },\n 'models?': 'unknown[]',\n 'definitions?': { subgraphs: LiteGraphSubgraphDef_ark.array() },\n 'reroutes?': 'unknown[]',\n 'floatingLinks?': 'unknown[]',\n version: '0.4 | 1',\n})\n\ntrue satisfies IsEqual<LiteGraphJSON, typeof LiteGraphJSON_ark.infer>\n","import { type } from 'arktype'\nimport type {\n CanonicalGroup,\n CanonicalInput,\n CanonicalLink,\n CanonicalNode,\n CanonicalOutput,\n CanonicalWidgetValues,\n CanonicalWorkflow,\n NodeMode,\n} from 'src/litegraph/CanonicalWorkflow.ts'\nimport { type CanonicalSubgraphDef, expandSubgraphs } from 'src/litegraph/expandSubgraphs.ts'\nimport type { LiteGraphGroup } from 'src/litegraph/LiteGraphGroup.ts'\nimport { type LiteGraphJSON, LiteGraphJSON_ark } from 'src/litegraph/LiteGraphJSON.ts'\nimport type { LiteGraphLink } from 'src/litegraph/LiteGraphLink.ts'\nimport type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'\nimport type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'\nimport type { LiteGraphNodeOutput } from 'src/litegraph/LiteGraphNodeOutput.ts'\nimport type { LiteGraphSubgraphDef } from 'src/litegraph/LiteGraphSubgraphDef.ts'\n\nexport type WorkflowNormalizeErrorCode = 'schema-reject' | 'subgraph-cycle' | 'subgraph-io-mismatch' | 'bad-document'\n\n/** a workflow JSON we cannot turn into a CanonicalWorkflow — loud, typed, never a cast */\nexport class WorkflowNormalizeError extends Error {\n constructor(\n public code: WorkflowNormalizeErrorCode,\n message: string,\n public detail?: unknown,\n ) {\n super(`[workflow ${code}] ${message}`)\n this.name = 'WorkflowNormalizeError'\n }\n}\n\n/**\n * THE one entry for foreign workflow JSON (files, clipboard, imports):\n * tolerant ark validation, then normalization to the strict canonical shape.\n */\nexport const parseWorkflowJson = (json: unknown): CanonicalWorkflow => {\n const out = LiteGraphJSON_ark(json)\n if (out instanceof type.errors) throw new WorkflowNormalizeError('schema-reject', out.summary, out)\n return normalizeWorkflow(out)\n}\n\n/**\n * loose wire document → strict canonical document. Defaults filled, both link\n * eras unified, cosmetic fields dropped, subgraph definitions expanded away\n * (see expandSubgraphs.ts — def interiors go through the SAME per-shape\n * normalizers, they are v1 bodies).\n */\nexport const normalizeWorkflow = (raw: LiteGraphJSON): CanonicalWorkflow => {\n const wf: CanonicalWorkflow = {\n nodes: raw.nodes.map(normalizeNode),\n links: raw.links.map(normalizeLink),\n groups: (raw.groups ?? []).map(normalizeGroup),\n }\n const rawDefs = raw.definitions?.subgraphs ?? []\n if (rawDefs.length === 0) return wf\n const defs = new Map<string, CanonicalSubgraphDef>()\n for (const d of rawDefs) defs.set(d.id, normalizeSubgraphDef(d))\n return expandSubgraphs(wf, defs)\n}\n\nconst normalizeSubgraphDef = (d: LiteGraphSubgraphDef): CanonicalSubgraphDef => {\n return {\n id: d.id,\n name: d.name,\n inputs: d.inputs.map((io) => ({ name: io.name, type: io.type })),\n outputs: d.outputs.map((io) => ({ name: io.name, type: io.type })),\n nodes: d.nodes.map(normalizeNode),\n links: d.links.map(normalizeLink),\n }\n}\n\nconst normalizeMode = (mode: number | undefined): NodeMode => {\n if (mode === 2) return 'muted'\n if (mode === 4) return 'bypassed'\n return 'normal' // 0 (always) / 1 (on-event) / 3 (on-trigger) all execute\n}\n\nconst normalizeNode = (n: LiteGraphNode): CanonicalNode => {\n return {\n id: n.id,\n type: n.type,\n title: n.title ?? null,\n mode: normalizeMode(n.mode),\n isVirtualNode: n.isVirtualNode ?? false,\n inputs: (n.inputs ?? []).map(normalizeInput),\n outputs: (n.outputs ?? []).map(normalizeOutput),\n widgets: normalizeWidgetValues(n.widgets_values),\n pos: [n.pos[0], n.pos[1]],\n size: [n.size[0], n.size[1]],\n properties: { ...n.properties },\n }\n}\n\nconst normalizeInput = (i: LiteGraphNodeInput): CanonicalInput => {\n return {\n name: i.name,\n type: i.type,\n link: i.link ?? null,\n widgetName: i.widget?.name ?? null,\n }\n}\n\nconst normalizeOutput = (o: LiteGraphNodeOutput): CanonicalOutput => {\n return {\n name: o.name,\n type: o.type,\n links: [...(o.links ?? [])],\n }\n}\n\nconst normalizeWidgetValues = (wv: unknown[] | Record<string, unknown> | undefined): CanonicalWidgetValues => {\n if (wv == null) return { positional: [], named: {} }\n if (Array.isArray(wv)) return { positional: [...wv], named: {} }\n return { positional: [], named: { ...wv } }\n}\n\nconst normalizeLink = (l: LiteGraphLink): CanonicalLink => {\n if (Array.isArray(l)) {\n return { id: l[0], originId: l[1], originSlot: l[2], targetId: l[3], targetSlot: l[4], type: l[5] }\n }\n return {\n id: l.id,\n originId: l.origin_id,\n originSlot: l.origin_slot,\n targetId: l.target_id,\n targetSlot: l.target_slot,\n type: l.type,\n }\n}\n\nconst normalizeGroup = (g: LiteGraphGroup): CanonicalGroup => {\n return {\n title: g.title,\n bounding: [g.bounding[0], g.bounding[1], g.bounding[2], g.bounding[3]],\n color: g.color ?? '#3f789e',\n fontSize: g.font_size ?? 24,\n }\n}\n","// pure parser for BINARY ws frames (formats per\n// agent/external-docs/comfy-cloud/api-reference.md, all integers big-endian):\n// 1 PREVIEW_IMAGE 4B type · 4B image_type (1 jpeg, 2 png) · image bytes\n// 3 TEXT 4B type · 4B node_id_len · node_id · progress text\n// 4 PREVIEW_IMAGE_WITH_METADATA 4B type · 4B metadata_len · metadata JSON · image bytes\n// Unknown types come back as 'unknown' — the CALLER logs, never throws: the\n// wire drifts faster than we do (type 4 appeared on the first live cloud run).\n\nexport type ParsedBinaryWsFrame =\n | { kind: 'preview'; bytes: Uint8Array<ArrayBuffer>; mime: string; metadata: unknown }\n | { kind: 'text'; nodeId: string; text: string }\n | { kind: 'unknown'; eventType: number }\n\nexport function parseBinaryWsFrame(data: ArrayBuffer): ParsedBinaryWsFrame {\n const view = new DataView(data)\n const eventType = view.getUint32(0)\n\n if (eventType === 1) {\n const imageType = view.getUint32(4)\n const bytes = new Uint8Array(data.slice(8))\n const mime = imageType === 2 ? 'image/png' : 'image/jpeg'\n return { kind: 'preview', bytes, mime, metadata: null }\n }\n\n if (eventType === 3) {\n const nodeIdLen = view.getUint32(4)\n const decoder = new TextDecoder()\n const nodeId = decoder.decode(data.slice(8, 8 + nodeIdLen))\n const text = decoder.decode(data.slice(8 + nodeIdLen))\n return { kind: 'text', nodeId, text }\n }\n\n if (eventType === 4) {\n const metadataLen = view.getUint32(4)\n let metadata: unknown = null\n try {\n metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)))\n } catch {\n // tolerate broken metadata: the image bytes are the payload that matters\n }\n const bytes = new Uint8Array(data.slice(8 + metadataLen))\n // the docs say \"raw JPEG/PNG bytes\" with no format field — sniff the magic\n const mime = bytes[0] === 0x89 && bytes[1] === 0x50 ? 'image/png' : 'image/jpeg'\n return { kind: 'preview', bytes, mime, metadata }\n }\n\n return { kind: 'unknown', eventType }\n}\n","import type { ComfyNodeSchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\n\nexport const ComfyPrimitiveMapping: { [key: string]: string } = {\n // BACK\n BOOLEAN: 'boolean',\n FLOAT: 'number',\n INT: 'number',\n STRING: 'string',\n\n // ????\n // ⏸️ Boolean: 'boolean',\n // ⏸️ Float: 'number',\n // ⏸️ Integer: 'number',\n // ⏸️ SchedulerName: 'string',\n // ⏸️ SamplerName: 'string',\n // ⏸️ IMAGE_PATH: 'string',\n}\n\nexport const ComfyPrimitives: string[] = Object.keys(ComfyPrimitiveMapping)\n\n// schema-driven widget counting moved to src/sdk-generator/inputWidgetKind.ts\n// (config-driven classification); what stays below is the LEGACY serialized-\n// type path, used only when an old file carries a widget-marked input whose\n// schema now says slot.\n\n/**\n * when a litegraph node has an input entry with a widget marker, the\n * serialized TYPE string decides how many widgets_values it consumed in that era\n */\nexport const howManyWidgetValuesForThisInputType = (type: string, nameInComfy: string): number => {\n if (type === 'INT') {\n if (nameInComfy === 'seed' || nameInComfy === 'noise_seed') return 2\n return 1\n }\n if (type === 'BOOLEAN') return 1\n if (type === 'FLOAT') return 1\n if (type === 'STRING') return 1\n if (type === 'COMBO') return 1\n if (type === 'INT:seed') return 2\n if (type === 'INT:noise_seed') return 2\n\n // not a primitive, no Field_values\n return 0\n}\nexport const ComfyDefaultNodeWhenUnknown_Name: string = 'UnknownNodeXX'\n\nexport const ComfyDefaultNodeWhenUnknown_Schema: ComfyNodeSchemaJSON = {\n category: 'test',\n input: {},\n output: [],\n description: 'This is a test node',\n output_name: [],\n display_name: 'UnknownNodeXX',\n name: 'UnknownNodeXX',\n output_is_list: [],\n output_node: false,\n python_module: 'nodes',\n}\n","import type { NodeInputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { ComfyPrimitiveMapping } from 'src/sdk-generator/Primitives.ts'\n\n/**\n * Widget-ness of a schema input, decided from its CONFIG — never from a\n * type-name whitelist (2026 object_info spells widget inputs as arbitrary\n * strings backed by a frontend widget registry we cannot mirror; every\n * registry spelling carries a config signal instead). Signal precedence and\n * their upstream anchors: agent/architecture.md \"Widget-ness is decided from\n * the input CONFIG\".\n */\nexport type InputWidgetKind =\n | { kind: 'slot' }\n | {\n kind: 'widget'\n /** total widgets_values entries this input's run occupies: prefix buttons + value + control phantom */\n consumes: number\n strictValues: boolean\n /**\n * serialized values the frontend addWidget()s BEFORE the real value\n * (button widgets, creation order). Import reads the value at\n * `offset + prefixValues.length`; export writes these literals first\n * so a round-trip through the ComfyUI editor keeps positional\n * alignment. Empty for every config-signalled widget.\n */\n prefixValues: readonly unknown[]\n }\n | { kind: 'dynamic-combo'; options: DynamicComboOption[]; defaultKey: string }\n | { kind: 'dynamic-container'; instanceNames: string[]; requiredCount: number }\n\n/** one raw `[type, opts]` input entry as spelled in object_info (dynamic-combo branches arrive in this raw form) */\nexport type RawInputSpecEntry = {\n name: string\n type: string | readonly unknown[]\n opts: unknown\n required: boolean\n}\n\nexport type DynamicComboOption = { key: string; inputs: RawInputSpecEntry[] }\n\nexport const isRecord = (x: unknown): x is Record<string, unknown> =>\n typeof x === 'object' && x != null && !Array.isArray(x)\n\n/**\n * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.\n * The frontend creates the control widget on truthiness, and real 2026 hosts\n * spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,\n * SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed\n * heuristic applies.\n */\nconst controlConsumes = (o: Record<string, unknown> | null, typeName: string, name: string): 1 | 2 => {\n if (o != null && 'control_after_generate' in o) return o['control_after_generate'] ? 2 : 1\n if (typeName === 'INT' && (name === 'seed' || name === 'noise_seed')) return 2\n return 1\n}\n\nconst flattenInputSections = (inputs: Record<string, unknown>): RawInputSpecEntry[] => {\n const out: RawInputSpecEntry[] = []\n for (const section of ['required', 'optional'] as const) {\n const sec = inputs[section]\n if (!isRecord(sec)) continue\n for (const [name, spec] of Object.entries(sec)) {\n if (!Array.isArray(spec) || spec.length === 0) continue\n const t: unknown = spec[0]\n if (typeof t !== 'string' && !Array.isArray(t)) continue\n out.push({ name, type: t, opts: spec[1], required: section === 'required' })\n }\n }\n return out\n}\n\n/** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */\nconst parseDynamicOptions = (options: unknown[]): DynamicComboOption[] | null => {\n if (options.length === 0) return null\n const out: DynamicComboOption[] = []\n for (const entry of options) {\n if (!isRecord(entry)) return null\n const key = entry['key']\n const inputs = entry['inputs']\n if (typeof key !== 'string' || !isRecord(inputs)) return null\n out.push({ key, inputs: flattenInputSections(inputs) })\n }\n return out\n}\n\n/**\n * autogrow (`template` WITH a nested `input` section): instances are always\n * link slots named `decl.<name_i>` (the backend force-inputs widget\n * templates), the first `min` of them required WHEN the template input\n * section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.\n */\nconst parseContainer = (template: Record<string, unknown>): InputWidgetKind => {\n const input = template['input']\n const min = typeof template['min'] === 'number' ? template['min'] : 1\n const prefix = typeof template['prefix'] === 'string' ? template['prefix'] : ''\n const max = typeof template['max'] === 'number' ? template['max'] : 100\n const rawNames = template['names']\n const names = Array.isArray(rawNames)\n ? rawNames.filter((n): n is string => typeof n === 'string')\n : Array.from({ length: max }, (_, i) => `${prefix}${i}`)\n const templateRequired = isRecord(input) && isRecord(input['required']) && Object.keys(input['required']).length > 0\n return {\n kind: 'dynamic-container',\n instanceNames: names,\n requiredCount: templateRequired ? Math.min(min, names.length) : 0,\n }\n}\n\n/**\n * the single template sub-input's slot type of an autogrow container\n * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an\n * autogrow template or the template has several sub-inputs (corpus-absent\n * 2026-07-30, 27/27 single on the cloud catalog) — then codegen emits no\n * typed instance keys and the container stays builderBase territory.\n */\nexport const containerInstanceSlotType = (opts: unknown): string | null => {\n const o = isRecord(opts) ? opts : null\n const template = o?.['template']\n if (!isRecord(template) || !isRecord(template['input'])) return null\n const subs = flattenInputSections(template['input'])\n const first = subs[0]\n if (subs.length !== 1 || first == null || typeof first.type !== 'string') return null\n return first.type\n}\n\n/**\n * frontend-registered widgets whose object_info opts carry NO config signal —\n * the one exception to config-only classification (architecture.md rule 8).\n * Every entry must quote the frontend widget-creation source.\n *\n * LOAD_3D (ComfyUI_frontend src/extensions/core/load3d.ts, verified\n * 2026-07-31): the LOAD_3D custom widget handler runs\n * node.addWidget('button', 'upload 3d model', 'upload3dmodel', …)\n * node.addWidget('button', 'upload extra resources', 'uploadExtraResources', …)\n * node.addWidget('button', 'clear', 'clear', …)\n * THEN creates the scene widget, so the serialized run is\n * [btn, btn, btn, value] with the real value LAST. Lax domain: '' in saved\n * files, an {image, mask, normal, camera_info, …} dict at queue time.\n */\nconst EMPTY_CONFIG_FRONTEND_WIDGETS: Record<string, { prefixValues: readonly unknown[] }> = {\n LOAD_3D: { prefixValues: ['upload3dmodel', 'uploadExtraResources', 'clear'] },\n}\n\nexport const classifyWidgetInput = (p: {\n name: string\n type: string | readonly unknown[]\n opts: unknown\n /** true when type is a generated `E_*` union name (parsed 2024-era enum) */\n isEnumUnion?: boolean\n}): InputWidgetKind => {\n const o = isRecord(p.opts) ? p.opts : null\n // 1. forceInput gates widget creation upstream, whatever the type says\n if (o?.['forceInput'] === true) return { kind: 'slot' }\n // 2. enum arrays / parsed E_ unions are combo widgets\n if (Array.isArray(p.type) || p.isEnumUnion === true) {\n const tn = typeof p.type === 'string' ? p.type : 'COMBO'\n return { kind: 'widget', consumes: controlConsumes(o, tn, p.name), strictValues: true, prefixValues: [] }\n }\n if (typeof p.type !== 'string') return { kind: 'slot' }\n // 3. widgetType names the widget for multi-type unions (frontend: widgets.get(widgetType ?? type))\n const widgetTypeName = typeof o?.['widgetType'] === 'string' ? o['widgetType'] : p.type\n // 4. primitives\n if (ComfyPrimitiveMapping[widgetTypeName] != null)\n return {\n kind: 'widget',\n consumes: controlConsumes(o, widgetTypeName, p.name),\n strictValues: true,\n prefixValues: [],\n }\n // 5. options array: dynamic {key, inputs} family, else plain combo\n const options = o?.['options']\n if (Array.isArray(options)) {\n const dynOptions = parseDynamicOptions(options)\n if (dynOptions != null) {\n const first = dynOptions[0]\n if (first == null) return { kind: 'slot' } // unreachable: parseDynamicOptions rejects empty\n const defaultKey = typeof o?.['default'] === 'string' ? o['default'] : first.key\n return { kind: 'dynamic-combo', options: dynOptions, defaultKey }\n }\n return { kind: 'widget', consumes: controlConsumes(o, p.type, p.name), strictValues: true, prefixValues: [] }\n }\n // 6. template WITH nested input = autogrow container; WITHOUT = matchtype slot typing\n const template = o?.['template']\n if (isRecord(template)) {\n if (isRecord(template['input'])) return parseContainer(template)\n return { kind: 'slot' }\n }\n // 7. socketless: a widget that never has a socket (IMAGECOMPARE, COLOR); value domain unknown\n if (o?.['socketless'] === true) return { kind: 'widget', consumes: 1, strictValues: false, prefixValues: [] }\n // 8. known empty-config frontend widgets (LOAD_3D), the one non-config exception\n const emptyConfigEntry = EMPTY_CONFIG_FRONTEND_WIDGETS[widgetTypeName]\n if (emptyConfigEntry != null)\n return {\n kind: 'widget',\n consumes: emptyConfigEntry.prefixValues.length + 1,\n strictValues: false,\n prefixValues: emptyConfigEntry.prefixValues,\n }\n return { kind: 'slot' }\n}\n\nexport const classifySchemaInput = (input: NodeInputExt): InputWidgetKind =>\n classifyWidgetInput({\n name: input.nameInComfy,\n type: input.typeName,\n opts: input.opts,\n isEnumUnion: input.isEnum,\n })\n\n/**\n * what ComfyUI's frontend gives a widget created with no serialized value\n * (`getWidgetDefaultValue` semantics), used when a positional array is\n * shorter than the schema's widget list. `null` for custom widgets — the\n * backend accepts an explicit null but errors on an ABSENT required key.\n */\nexport const defaultValueForWidget = (p: {\n type: string\n opts: unknown\n /** resolved values when the type is a generated E_ union or an inline enum array */\n enumValues?: readonly (string | boolean | number)[]\n}): unknown => {\n const o = isRecord(p.opts) ? p.opts : null\n if (o != null && o['default'] !== undefined) return o['default']\n const widgetTypeName = typeof o?.['widgetType'] === 'string' ? o['widgetType'] : p.type\n if (widgetTypeName === 'INT' || widgetTypeName === 'FLOAT') return 0\n if (widgetTypeName === 'BOOLEAN') return false\n if (widgetTypeName === 'STRING') return ''\n const options = o?.['options']\n if (Array.isArray(options) && options.length > 0) {\n const first: unknown = options[0]\n if (typeof first === 'string' || typeof first === 'number' || typeof first === 'boolean') return first\n }\n if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0]\n return null\n}\n","import type {\n CanonicalInput,\n CanonicalLink,\n CanonicalNode,\n CanonicalWorkflow,\n} from 'src/litegraph/CanonicalWorkflow.ts'\nimport type { LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport type { NodeInputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { howManyWidgetValuesForThisInputType } from 'src/sdk-generator/Primitives.ts'\nimport {\n classifySchemaInput,\n classifyWidgetInput,\n defaultValueForWidget,\n isRecord,\n type DynamicComboOption,\n type RawInputSpecEntry,\n} from 'src/sdk-generator/inputWidgetKind.ts'\n\ntype PromptInputValue = ComfyApiNodeJson['inputs'][string]\n\nexport type WorkflowConvertErrorCode =\n | 'unknown-node'\n | 'missing-widget-value'\n | 'invalid-widget-value'\n | 'unknown-dynamic-combo-option'\n | 'dangling-link'\n | 'missing-required-input'\n | 'unsupported-feature'\n\n/** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */\nexport class WorkflowConvertError extends Error {\n constructor(\n public code: WorkflowConvertErrorCode,\n message: string,\n public node?: { id: number; type: string },\n ) {\n super(`[workflow ${code}] ${message}`)\n this.name = 'WorkflowConvertError'\n }\n}\n\n/**\n * closed set: frontend-only node types that NEVER execute. PrimitiveString /\n * PrimitiveInt / PrimitiveBoolean etc are REAL backend nodes — do not add them.\n */\nconst VIRTUAL_NODE_TYPES: ReadonlySet<string> = new Set(['Note', 'MarkdownNote', 'Reroute', 'PrimitiveNode'])\n\nconst isNeverExecuted = (node: CanonicalNode): boolean => node.isVirtualNode || VIRTUAL_NODE_TYPES.has(node.type)\n\n/** exact match, or `*` wildcard on either side (Reroute-style slots) */\n/** frontend isValidConnection parity: exact, `*` wildcard, or any member of a comma-separated multi-type */\nconst linkTypeMatches = (a: string, b: string): boolean => {\n if (a === b || a === '*' || b === '*') return true\n if (!a.includes(',') && !b.includes(',')) return false\n const as = a.split(',')\n const bs = b.split(',')\n return as.some((x) => bs.includes(x))\n}\n\n/** what an inlined PrimitiveNode may contribute: scalar widget values only */\nconst isPromptScalar = (v: unknown): v is string | number | boolean | null =>\n v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'\n\n/**\n * convert a normalized workflow (CanonicalWorkflow — see parseWorkflowJson)\n * into the api.json (prompt format) ComfyUI's POST /prompt takes.\n * Handles: muted nodes (skipped, consumers resolve unconnected), bypassed\n * nodes (mode 4: link resolution walks through to the first type-matching\n * input), Note/MarkdownNote/Reroute/PrimitiveNode virtual nodes (reroutes\n * unwrapped, primitives inlined into their consumers), widget values both\n * positional (with the phantom `control_after_generate` offset after seeds)\n * and named (object-form widgets_values + subgraph promotion overrides —\n * named wins, but a live link wins over both). Widget-ness is decided from\n * the input CONFIG (inputWidgetKind.ts): V3 string-spelled widget types\n * (COMBO options, dynamic combos, autogrow containers, socketless customs)\n * and 2024-era enums go through ONE classifier; a positional array shorter\n * than the schema's widget list fills schema defaults, never throws\n * (agent/architecture.md owns both decisions).\n */\nexport const convertLiteGraphToPrompt = (\n /** the ComfySchema object (to look for references/definitions) */\n schema: ComfySchema,\n /** the normalized litegraph document */\n workflow: CanonicalWorkflow,\n opts: { verbose?: boolean } = {},\n): ComfyApiJson => {\n const prompt: ComfyApiJson = {}\n const LOG = opts.verbose ? (...args: unknown[]): void => console.log('[🔥] converter:', ...args) : (): void => {}\n\n // 1. cache primitive node values so links from PrimitiveNode inline as values.\n // A PrimitiveNode may serialize WITHOUT a value (real corpus case): its\n // consumers then resolve unconnected and fall back to their OWN serialized\n // widget values — the primitive only mirrors the consumer's widget.\n const PRIMITIVE_VALUES: { [nodeId: string]: unknown } = {}\n for (const node of workflow.nodes) {\n if (node.type !== 'PrimitiveNode') continue\n if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0]\n else if (Object.hasOwn(node.widgets.named, 'value')) PRIMITIVE_VALUES[node.id] = node.widgets.named['value']\n }\n\n // 2. every executable node\n for (const node of workflow.nodes) {\n if (isNeverExecuted(node)) continue // frontend-only nodes (reroutes/primitives unwrapped below)\n if (node.mode !== 'normal') continue // muted skipped, bypassed passthrough'd at link resolution\n\n const inputs: ComfyApiNodeJson['inputs'] = {}\n const fieldNamesPresent = new Set(node.inputs.map((i) => i.name))\n const nodeSchema_ = schema.nodesByNameInComfy[node.type]\n if (nodeSchema_ == null)\n throw new WorkflowConvertError(\n 'unknown-node',\n `node ${node.id}(${node.type}) has no schema on this host; a custom node is missing`,\n node,\n )\n const nodeSchema: ComfyNodeSchema = nodeSchema_\n\n // 2.a widget values, walked in schema order. Widget-ness comes from the\n // input CONFIG (classifySchemaInput — agent/architecture.md): named wins,\n // else positional cursor, else SCHEMA-DEFAULT FILL (what the frontend\n // does when an old file meets a grown schema — a throw would reject files\n // ComfyUI runs fine). The offset advances past named-shadowed slots\n // whenever a positional array exists (promotion case). A LIVE LINK on\n // the field wins over both — the widget value is kept as the fallback\n // for dead-end link resolution (muted/bypassed parents).\n let offset = 0\n const positional = node.widgets.positional\n const named = node.widgets.named\n const widgetFallback = new Map<string, PromptInputValue>()\n const inputsInNodeJSON: CanonicalInput[] = node.inputs\n const inputsInNodeSchema: NodeInputExt[] = nodeSchema.inputs\n\n /** arrays ride wrapped (a bare 2-list is a link server-side); objects pass only in lax (custom-widget) domains */\n const toPromptValue = (value: unknown, p: { promptName: string; strict: boolean }): PromptInputValue => {\n if (value == null) return null\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value\n if (Array.isArray(value)) return { __value__: value }\n if (!p.strict && isRecord(value)) return value\n throw new WorkflowConvertError(\n 'invalid-widget-value',\n `node ${node.id}(${node.type}) has an invalid widget value for \"${p.promptName}\": ${JSON.stringify(value)}`,\n node,\n )\n }\n\n /** named wins, then positional cursor (+prefixLen skips leading button values, LOAD_3D); filled=true when both miss (caller falls back to the schema default) */\n const resolveWidgetValue = (p: {\n promptName: string\n consumes: number\n prefixLen: number\n }): { value: unknown; filled: boolean } => {\n let value: unknown\n let has = false\n if (Object.hasOwn(named, p.promptName)) {\n value = named[p.promptName]\n has = true\n } else if (offset + p.prefixLen < positional.length) {\n value = positional[offset + p.prefixLen]\n has = true\n }\n if (positional.length > 0) offset += p.consumes // named-shadow still advances (promotion case)\n return { value, filled: !has }\n }\n\n const consumePlainWidget = (p: {\n promptName: string\n typeName: string\n opts: unknown\n consumes: number\n prefixLen: number\n strict: boolean\n enumValues?: readonly (string | boolean | number)[]\n linkedInput: CanonicalInput | undefined\n }): void => {\n const r = resolveWidgetValue({ promptName: p.promptName, consumes: p.consumes, prefixLen: p.prefixLen })\n const raw = r.filled\n ? defaultValueForWidget({\n type: p.typeName,\n opts: p.opts,\n enumValues: p.enumValues ?? schema.knownUnionByName.get(p.typeName)?.values,\n })\n : r.value\n const value = toPromptValue(raw, { promptName: p.promptName, strict: p.strict })\n if (r.filled) LOG(`${node.type}#${node.id}.${p.promptName} = ${JSON.stringify(value)} (schema-default fill)`)\n if (p.linkedInput?.link != null) widgetFallback.set(p.promptName, value)\n else inputs[p.promptName] = value\n }\n\n /** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */\n const consumeDynamicCombo = (p: { path: string; options: DynamicComboOption[]; defaultKey: string }): void => {\n const r = resolveWidgetValue({ promptName: p.path, consumes: 1, prefixLen: 0 })\n const key = r.filled ? p.defaultKey : r.value\n if (typeof key !== 'string')\n throw new WorkflowConvertError(\n 'invalid-widget-value',\n `node ${node.id}(${node.type}): dynamic combo \"${p.path}\" key is not a string: ${JSON.stringify(key)}`,\n node,\n )\n const opt = p.options.find((o) => o.key === key)\n // own code: usually the template is NEWER than this host's node\n // (version drift, same class as unknown-node), not a garbage value\n if (opt == null)\n throw new WorkflowConvertError(\n 'unknown-dynamic-combo-option',\n `node ${node.id}(${node.type}): \"${key}\" is not an option of dynamic combo \"${p.path}\" (options: ${p.options.map((o) => o.key).join(', ')})`,\n node,\n )\n if (r.filled) LOG(`${node.type}#${node.id}.${p.path} = ${key} (schema-default fill)`)\n inputs[p.path] = key\n for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub)\n }\n\n const consumeBranchInput = (subPath: string, sub: RawInputSpecEntry): void => {\n const kind = classifyWidgetInput({ name: sub.name, type: sub.type, opts: sub.opts })\n // slots and containers materialize as dotted serialized inputs, resolved as links in 2.b\n if (kind.kind === 'slot' || kind.kind === 'dynamic-container') return\n if (kind.kind === 'dynamic-combo')\n return consumeDynamicCombo({ path: subPath, options: kind.options, defaultKey: kind.defaultKey })\n const inlineEnum = Array.isArray(sub.type)\n ? sub.type.filter(\n (v): v is string | number | boolean =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean',\n )\n : undefined\n consumePlainWidget({\n promptName: subPath,\n typeName: typeof sub.type === 'string' ? sub.type : 'COMBO',\n opts: sub.opts,\n consumes: kind.consumes,\n prefixLen: kind.prefixValues.length,\n strict: kind.strictValues,\n enumValues: inlineEnum,\n linkedInput: inputsInNodeJSON.find((i) => i.name === subPath),\n })\n }\n\n for (const field of inputsInNodeSchema) {\n const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy)\n let kind = classifySchemaInput(field)\n // era drift: the file serialized this input widget-backed while the\n // schema now says slot (e.g. forceInput added later) — the file\n // proves a widget value was written, so consume per the file's era\n if (kind.kind === 'slot' && input?.widgetName != null) {\n const legacyConsumes = howManyWidgetValuesForThisInputType(input.type, field.nameInComfy)\n kind = { kind: 'widget', consumes: legacyConsumes === 2 ? 2 : 1, strictValues: true, prefixValues: [] }\n }\n\n if (kind.kind === 'widget') {\n consumePlainWidget({\n promptName: field.nameInComfy,\n typeName: field.typeName,\n opts: field.opts,\n consumes: kind.consumes,\n prefixLen: kind.prefixValues.length,\n strict: kind.strictValues,\n linkedInput: input,\n })\n } else if (kind.kind === 'dynamic-combo') {\n consumeDynamicCombo({ path: field.nameInComfy, options: kind.options, defaultKey: kind.defaultKey })\n } else if (kind.kind === 'dynamic-container') {\n // the declaration itself never appears; the first template.min\n // instances must be connected (backend requires them by name)\n for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {\n const iname = `${field.nameInComfy}.${instName}`\n const inst = inputsInNodeJSON.find((i) => i.name === iname)\n if (inst?.link == null)\n throw new WorkflowConvertError(\n 'missing-required-input',\n `node ${node.id}(${node.type}): autogrow \"${field.nameInComfy}\" requires instance \"${iname}\" connected (template.min = ${kind.requiredCount})`,\n node,\n )\n }\n } else if (!fieldNamesPresent.has(field.nameInComfy)) {\n if (field.required)\n throw new WorkflowConvertError(\n 'missing-required-input',\n `node ${node.id}(${node.type}): required input \"${field.nameInComfy}\" (${field.typeName}) has neither widget value nor link`,\n node,\n )\n }\n }\n\n // 2.b links\n type ParentInfo = { node: CanonicalNode; link: CanonicalLink }\n const getParentNode = (linkId: LiteGraphLinkID): ParentInfo => {\n const link = workflow.links.find((link) => link.id === linkId)\n if (link == null)\n throw new WorkflowConvertError(\n 'dangling-link',\n `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`,\n node,\n )\n const parentNode = workflow.nodes.find((n) => n.id === link.originId)\n if (parentNode == null)\n throw new WorkflowConvertError(\n 'dangling-link',\n `link ${linkId} references a non-existent parent node ${link.originId}`,\n node,\n )\n return { node: parentNode, link }\n }\n\n // mirrors frontend ExecutableNodeDTO._getBypassSlotIndex (verified\n // 2026-07-29, agent/architecture.md \"Bypass passthrough\"): wildcard\n // consumer type short-circuits to the same-slot input; else same-slot\n // preferred when connection-valid against output AND consumer type; else\n // first EXACT consumer-type match; else first wildcard-tolerant match.\n // The pick ignores link-state on purpose — an unlinked winner resolves\n // unconnected, like the frontend's null link.\n const pickBypassInput = (p: {\n inputs: CanonicalInput[]\n outSlot: number\n outputType: string\n consumerType: string\n }): CanonicalInput | null => {\n const sameSlot = p.inputs[p.outSlot]\n if (p.consumerType === '*' || p.consumerType === '') return sameSlot ?? p.inputs[0] ?? null\n if (\n sameSlot != null &&\n linkTypeMatches(sameSlot.type, p.outputType) &&\n linkTypeMatches(sameSlot.type, p.consumerType)\n )\n return sameSlot\n const exact = p.inputs.find((i) => i.type === p.consumerType)\n if (exact != null) return exact\n return (\n p.inputs.find((i) => linkTypeMatches(i.type, p.outputType) && linkTypeMatches(i.type, p.consumerType)) ??\n null\n )\n }\n\n // walk through follow-through parents: Reroute unwraps, bypassed nodes\n // redirect per pickBypassInput above. The match type is RE-DERIVED at\n // each bypass hop from the picked input (frontend resolveOutput calls\n // resolveInput WITHOUT the type param, so the next hop matches on that\n // input's own type); muted parents and dead-end bypasses resolve\n // UNCONNECTED. Visited-set guards link cycles.\n type LinkResolution =\n | { kind: 'link'; nodeId: number; slot: number }\n | { kind: 'primitive'; nodeId: number }\n | { kind: 'unconnected'; reason: string }\n const resolveThroughParents = (startLink: LiteGraphLinkID, consumerType: string): LinkResolution => {\n const visited = new Set<number>()\n let linkId = startLink\n let effectiveType = consumerType\n while (true) {\n const parent: ParentInfo = getParentNode(linkId)\n if (visited.has(parent.node.id))\n throw new WorkflowConvertError(\n 'dangling-link',\n `node ${node.id}(${node.type}): link resolution loops through node ${parent.node.id}`,\n node,\n )\n visited.add(parent.node.id)\n if (parent.node.type === 'Reroute') {\n const rerouteIn = parent.node.inputs[0]?.link\n if (rerouteIn == null) return { kind: 'unconnected', reason: 'reroute chain ends on an empty slot' }\n linkId = rerouteIn\n continue\n }\n if (parent.node.mode === 'muted')\n return { kind: 'unconnected', reason: `parent ${parent.node.id}(${parent.node.type}) is muted` }\n if (parent.node.mode === 'bypassed') {\n const outputType = parent.node.outputs[parent.link.originSlot]?.type ?? parent.link.type\n const through = pickBypassInput({\n inputs: parent.node.inputs,\n outSlot: parent.link.originSlot,\n outputType,\n consumerType: effectiveType,\n })\n if (through?.link == null)\n return {\n kind: 'unconnected',\n reason: `bypassed parent ${parent.node.id}(${parent.node.type}) has no connected ${effectiveType} input to pass through`,\n }\n linkId = through.link\n effectiveType = through.type\n continue\n }\n if (parent.node.type === 'PrimitiveNode') {\n if (!(parent.node.id in PRIMITIVE_VALUES))\n return { kind: 'unconnected', reason: `PrimitiveNode#${parent.node.id} has no widget value` }\n return { kind: 'primitive', nodeId: parent.node.id }\n }\n return { kind: 'link', nodeId: parent.node.id, slot: parent.link.originSlot }\n }\n }\n\n for (const ipt of node.inputs) {\n if (ipt.link == null) {\n LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (widget-backed or optional)`)\n continue\n }\n const resolved = resolveThroughParents(ipt.link, ipt.type)\n if (resolved.kind === 'primitive') {\n // inline primitive nodes as plain values — GUARDED: primitives are\n // scalar widgets, a non-scalar value would cast garbage (or a\n // fake link 2-array) into the prompt\n const pv: unknown = PRIMITIVE_VALUES[resolved.nodeId]\n if (!isPromptScalar(pv))\n throw new WorkflowConvertError(\n 'invalid-widget-value',\n `node ${node.id}(${node.type}): PrimitiveNode#${resolved.nodeId} value is not a scalar: ${JSON.stringify(pv)}`,\n node,\n )\n inputs[ipt.name] = pv\n LOG(`${node.type}#${node.id}.${ipt.name} = ${pv} (inlined primitive)`)\n continue\n }\n if (resolved.kind === 'link') {\n LOG(`${node.type}#${node.id}.${ipt.name} = [${resolved.nodeId}, ${resolved.slot}] (link)`)\n inputs[ipt.name] = [String(resolved.nodeId), resolved.slot]\n continue\n }\n // unconnected: the serialized widget value covers it, else loud when required\n if (widgetFallback.has(ipt.name)) {\n inputs[ipt.name] = widgetFallback.get(ipt.name) ?? null\n LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (widget fallback, ${resolved.reason})`)\n continue\n }\n const field = inputsInNodeSchema.find((f) => f.nameInComfy === ipt.name)\n if (field?.required)\n throw new WorkflowConvertError(\n 'missing-required-input',\n `node ${node.id}(${node.type}): required input \"${ipt.name}\" resolves unconnected (${resolved.reason}) and no widget value covers it`,\n node,\n )\n LOG(`${node.type}#${node.id}.${ipt.name}: resolves unconnected (${resolved.reason})`)\n }\n\n prompt[String(node.id)] = { inputs, class_type: node.type }\n }\n\n return prompt\n}\n\n/** alias cause I keep forgetting about this */\nexport const convertWorkflowToPrompt = convertLiteGraphToPrompt\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","// ComfyUI's own words for a refused prompt. The body carries `error` (what went wrong overall)\n// and `node_errors` (per node, with the offending value), and those sentences are the only\n// thing that says WHICH input the host would not take.\nimport { isRecord } from 'src/utils/isRecord.ts'\n\nfunction str(v: unknown): string {\n return typeof v === 'string' ? v.trim() : ''\n}\n\nexport function describePromptRejection(body: unknown): string {\n if (!isRecord(body)) return 'no reason given'\n const parts: string[] = []\n const err = body['error']\n if (isRecord(err)) {\n const head = str(err['message'])\n const detail = str(err['details'])\n if (head !== '') parts.push(detail === '' ? head : `${head} (${detail})`)\n }\n const nodes = body['node_errors']\n if (isRecord(nodes)) {\n for (const [nodeId, raw] of Object.entries(nodes)) {\n if (!isRecord(raw)) continue\n const list = raw['errors']\n if (!Array.isArray(list)) continue\n for (const e of list) {\n if (!isRecord(e)) continue\n const detail = str(e['details'])\n const msg = str(e['message'])\n parts.push(`node ${nodeId}: ${[msg, detail].filter((x) => x !== '').join(' — ')}`)\n }\n }\n }\n return parts.length === 0 ? 'no reason given' : parts.join(' · ')\n}\n","import type { ExecutionSnapshot } from 'src/runner/ComfyWorkflow.ts'\n\nexport class InvalidPromptError extends Error {\n constructor(\n public override message: string,\n /** exactly what was sent to the host when the error happened */\n public snapshot: ExecutionSnapshot,\n public details: unknown,\n ) {\n super(message)\n }\n}\n","export const palette = {\n primitive: 'var(--comfy-primitive)',\n loader: 'var(--comfy-loader)',\n latent: 'var(--comfy-latent)',\n conditioning: 'var(--comfy-conditioning)',\n sampl: 'var(--comfy-sampl)',\n image: 'var(--comfy-image)',\n}\n\nexport const paletteKeys = Object.keys(palette) as (keyof typeof palette)[]\n\nexport const comfyColors: { [category: string]: string } = {\n loaders: palette.loader,\n latent: palette.latent,\n 'latent/transform': palette.latent,\n conditioning: palette.conditioning, // '#0d430d',\n 'conditioning/style_model': palette.conditioning,\n sampling: palette.sampl,\n image: palette.image,\n primitive: palette.primitive,\n}\n\nexport const getColorForCategory = (_category: string): string | undefined => {\n const category = _category.toLowerCase()\n if (category in comfyColors) return comfyColors[category]\n return 'var(--comfy-default)'\n}\n\n// INPUT ----------------------------------------------------------------\nexport const getColorForInputNameInComfy = (nameInComfy: string): string | undefined => {\n const name = nameInComfy.toLowerCase()\n if (name.includes('width')) return palette.primitive\n if (name.includes('height')) return palette.primitive\n for (const k of paletteKeys) if (name.startsWith(k)) return palette[k]\n return 'var(--comfy-default)'\n}\n\n// OUTPUTS ----------------------------------------------------------------\n","import type { Branded } from 'src/types/index.ts'\n\n/**\n * a fake value that is detected at serialization\n * time to try to magically inject stuff\n * */\nexport type AUTO = Branded<{ ___AUTO___: true }, { AUTO: true }>\n\n/**\n * you can use this as a placeholder anywhere in your graph\n * comfy-ts wires the most recent output of a matching type at serialization time\n */\n// sanctioned cast (agent/coding.md): auto() is a SENTINEL detected at\n// serialization time and replaced by a real link — it never survives to runtime\nexport const auto = <T>(): T => auto_ as T\n\nexport const auto_: AUTO = { ___AUTO___: true } as AUTO\n","import type { ComfyNode } from 'src/graph/ComfyNode.ts'\n\nexport class ComfyNodeOutput<T extends string = string, Ix extends number = number> {\n constructor(\n public node: ComfyNode<object>,\n public slotIx: Ix,\n public type: T,\n /**\n * as of 2024-11-16, output slots have no name in comfy, only a type.\n * Problem is that some nodes have multiple outputs of the same type.\n * so subsequent outputs with a previous used name will be suffixed\n * and have named like `output_2`, `output_3`, etc.\n */\n public name: string,\n ) {}\n}\n","import type { ComfyWorkflow, ProgressReport } from 'src/runner/ComfyWorkflow.ts'\nimport type { NodeProgress } from 'src/runner/ComfyWsApi.ts'\nimport type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport type { NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { ComfyDefaultNodeWhenUnknown_Name } from 'src/sdk-generator/Primitives.ts'\nimport { classifySchemaInput, defaultValueForWidget } from 'src/sdk-generator/inputWidgetKind.ts'\nimport type { DynamicComboOption } from 'src/sdk-generator/inputWidgetKind.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { comfyColors } from 'src/utils/ComfyColors.ts'\nimport { auto_ } from 'src/graph/autoValue.ts'\nimport type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'\nimport { NodeSlotSize, NodeTitleHeight, nodeLineHeight } from 'src/graph/NodeSlotSize.ts'\n\ntype NodeExecutionStatus = 'executing' | 'done' | 'error' | 'waiting' | 'cached' | null\n\nconst isScalarValue = (x: unknown): x is string | number | boolean =>\n typeof x === 'string' || typeof x === 'number' || typeof x === 'boolean'\n\nexport type NodePort = {\n id: string\n label: string\n width: number\n height: number\n type: string\n x: number\n y: number\n toNode?: ComfyNode<object, object> | undefined\n fromNode?: ComfyNode<object, object> | undefined\n}\n\nexport type ComfyNodeUID = string\n\n/** ComfyNode\n * - correspond to a signal in the graph\n * - belongs to a script\n */\nexport class ComfyNode<\n //\n ComfyNode_input extends object = object,\n ComfyNode_output extends object = object,\n> {\n storeAs(storeName: string): this {\n this.meta.storeAs = storeName\n return this\n }\n\n tag(tagName: string): this {\n this.addTag(tagName)\n return this\n }\n\n addTag(tag: string): this {\n if (this.meta.tags == null) this.meta.tags = [tag]\n else this.meta.tags.push(tag)\n return this\n }\n // ---------------------------------------\n\n /** reported though websocket by ComfyUI */\n status: NodeExecutionStatus = null\n\n /** last raw progress message reported by comfy */\n progress: NodeProgress | null = null\n\n /**\n * updated on websocket progress report from the progress property just above\n * between [0, 1]\n * */\n progressRatio: number = 0\n\n get progressReport(): ProgressReport {\n const percent = this.status === 'done' ? 100 : this.progressRatio * 100\n const isDone = this.status === 'done'\n return { percent, isDone, countDone: this.progressRatio * 100, countTotal: 100 }\n }\n\n $schema: ComfyNodeSchema\n updatedAt: number = Date.now()\n json: ComfyApiNodeJson\n\n get isExecuting(): boolean {\n return this.status === 'executing'\n }\n\n disabled: boolean = false\n\n disable(): void {\n this.disabled = true\n }\n\n get inputs(): ComfyNode_input {\n // sanctioned cast (agent/coding.md): runtime graph json <-> generated\n // static face; both derive from the same object_info\n return this.json.inputs as ComfyNode_input\n }\n\n /** update a node */\n set(p: Partial<ComfyNode_input>): this {\n for (const [key, value] of Object.entries(p)) {\n const next = this.serializeValue(key, value)\n const prev = this.json.inputs[key]\n if (next === prev) continue\n this.json.inputs[key] = next as any // 🔴\n }\n return this\n // 🔴 wrong resonsibility\n // console.log('CHANGES', changes)\n }\n\n get color(): string {\n return comfyColors[this.$schema.category] ?? '#aaa'\n }\n\n uidNumber: number\n $outputs: ComfyNodeOutput<string>[] = []\n outputs: ComfyNode_output\n uidPrefixed: string\n\n constructor(\n public graph: ComfyWorkflow,\n public uid: ComfyNodeUID, // = graph.getUID(),\n jsonExt: ComfyApiNodeJson,\n public meta: ComfyNodeMetadata = {},\n ) {\n // strictly-numeric uids keep uid === uidNumber (litegraph export must agree\n // with prompt keys); anything else gets the next free number ('12abc' must\n // NOT partial-parse to 12 — that collides with node '12')\n const parsedUid = /^\\d+$/.test(uid) ? Number(uid) : Number.NaN\n this.uidNumber = Number.isNaN(parsedUid) ? this.graph._uidNumber++ : parsedUid\n if (this.uidNumber >= this.graph._uidNumber) this.graph._uidNumber = this.uidNumber + 1\n if (jsonExt == null) throw new Error('invariant violation: jsonExt is null')\n // this.json = graph.data.apiJson[uid]\n // if (this.json == null) graph.data.apiJson = {}\n // console.log('CONSTRUCTING', xxx.class_type, uid)\n\n // this.uidNumber = parseInt(uid) // 🔴 ugly\n const exactSchema = graph.schema.nodesByNameInComfy[jsonExt.class_type]\n if (exactSchema == null) {\n // loud fallback: imported json referencing a node this host doesn't have\n graph.recordProblem(\n `unknown node type \"${jsonExt.class_type}\" — schema fallback to ${ComfyDefaultNodeWhenUnknown_Name}; install the missing custom node on the host`,\n )\n }\n this.$schema = exactSchema ?? graph.schema.nodesByNameInComfy[ComfyDefaultNodeWhenUnknown_Name]!\n\n if (this.$schema == null) {\n console.log(`❌ available nodes:`, Object.keys(graph.schema.nodesByNameInComfy).join(','))\n throw new Error(`❌ no schema found for node \"${jsonExt.class_type}\"`)\n // throw new Error('')\n }\n this.uidPrefixed = `${this.$schema.nodeKey}_${this.uidNumber}`\n let ix = 0\n\n // 🔶 1 this declare the json locally,\n // but Node are not live instances, they're local subinstances to a LiveGraph\n this.json = this._convertPromptExtToPrompt(jsonExt)\n // 🔶 2 so we need to ensure the json is properly synced with the LiveGraph data\n // register node ensure this\n this.graph.registerNode(this)\n\n // dynamically add properties for every outputs\n const outputs: { [key: string]: any } = {}\n for (const x of this.$schema.outputs) {\n const output = new ComfyNodeOutput(this, ix++, x.typeName, x.nameInComfy)\n outputs[x.outKey] = output\n this.$outputs.push(output)\n // console.log(` - .${x.outKey} as ComfyNodeOutput(${ix})`)\n }\n this.outputs = outputs as ComfyNode_output\n\n // implements the _<typeName> properties (HasSingle interfaces)\n const extensions: { [key: string]: any } = {}\n for (const x of this.$schema.singleOutputs) {\n extensions[`_${x.typeName}`] = outputs[x.outKey]\n }\n Object.assign(this, extensions)\n }\n\n _convertPromptExtToPrompt(promptExt: ComfyApiNodeJson): ComfyApiNodeJson {\n const inputs: { [inputName: string]: any } = {}\n const _done = new Set<string>()\n /** every dotted key of every branch: the selected ones are written here, the rest are dropped */\n const _comboBranchKeys = new Set<string>()\n for (const i of this.$schema.inputs) {\n _done.add(i.nameInComfy)\n const kind = classifySchemaInput(i)\n if (kind.kind === 'dynamic-combo') {\n this._writeDynamicCombo({\n name: i.nameInComfy,\n options: kind.options,\n defaultKey: kind.defaultKey,\n provided: promptExt.inputs,\n out: inputs,\n claimed: _comboBranchKeys,\n })\n continue\n }\n const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy])\n // absent optionals (autogrow containers included) stay OUT of the\n // prompt: an `undefined` value would already be dropped by JSON\n // serialization, keeping the key would only lie to Object.keys\n if (value !== undefined) inputs[i.nameInComfy] = value\n }\n for (const [nameInComfy, rawVal] of Object.entries(promptExt.inputs)) {\n if (_done.has(nameInComfy) || _comboBranchKeys.has(nameInComfy)) continue\n const value = this.serializeValue(nameInComfy, rawVal)\n inputs[nameInComfy] = value\n }\n return { class_type: this.$schema.nameInComfy, inputs }\n }\n\n /** dynamic combo → the key plus ONLY the selected branch's dotted inputs, absent ones\n * filled from the schema (agent/architecture.md, dynamic-combo fill). The host declares\n * those branch inputs required and default-fills none of them */\n private _writeDynamicCombo(p: {\n name: string\n options: DynamicComboOption[]\n defaultKey: string\n provided: { [k: string]: unknown }\n out: { [k: string]: any }\n claimed: Set<string>\n }): void {\n for (const opt of p.options) for (const e of opt.inputs) p.claimed.add(`${p.name}.${e.name}`)\n const raw = p.provided[p.name]\n const key = typeof raw === 'string' ? raw : p.defaultKey\n const branch = p.options.find((o) => o.key === key)\n if (branch == null) {\n const known = p.options.map((o) => o.key).join(', ')\n console.error(`🔴 unknown \"${p.name}\" option ${JSON.stringify(key)} (known: ${known})`)\n this.graph.recordProblem(\n `🔴 unknown \"${p.name}\" option ${JSON.stringify(key)} on ${this.$schema.nodeKey}#${this.uid} (known: ${known})`,\n )\n return\n }\n p.out[p.name] = key\n for (const e of branch.inputs) {\n const dotted = `${p.name}.${e.name}`\n const given = p.provided[dotted]\n p.out[dotted] =\n given === undefined\n ? defaultValueForWidget({\n type: typeof e.type === 'string' ? e.type : 'COMBO',\n opts: e.opts,\n enumValues: Array.isArray(e.type) ? e.type.filter(isScalarValue) : undefined,\n })\n : this.serializeValue(dotted, given)\n }\n }\n\n /** return the list of nodes piped into this node */\n _incomingNodes(): ComfyNodeId[] {\n const incomingNodes: ComfyNodeId[] = []\n for (const [_name, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) {\n const [from, _slotIx] = val\n incomingNodes.push(from)\n }\n }\n return incomingNodes\n }\n\n _primitives(): { inputName: string; value: string }[] {\n const primitives: { inputName: string; value: string }[] = []\n for (const [inputName, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) continue\n primitives.push({ inputName: inputName, value: val?.toString() })\n }\n return primitives\n }\n\n /** return true if the given node is plugged into this one */\n isChildrenOf(node: ComfyNode<any>): boolean {\n return this._incomingNodes().includes(node.uid)\n }\n\n get parents(): ComfyNode<any>[] {\n return this._incomingNodes().map((id) => this.graph.getNode(id)!)\n }\n // get children(): ComfyNode<any>[] {\n // return this._incomingNodes().map((id) => this.graph.getNode(id)!)\n // }\n\n _visible: boolean = true\n set visible(value: boolean) {\n this._visible = value\n } // biome-ignore format: misc\n get visible(): boolean {\n return this._visible\n } // biome-ignore format: misc\n\n _x: number = 0\n get x(): number {\n return this._x\n } // biome-ignore format: misc\n set x(value: number) {\n this.isDirty = true\n this._x = value\n }\n\n _y: number = 0\n get y(): number {\n return this._y\n } // biome-ignore format: misc\n set y(value: number) {\n this.isDirty = true\n this._y = value\n }\n\n isDirty = true\n\n tagDirty(value: boolean): void {\n this.isDirty = value\n }\n\n col: number = 0\n selected: boolean = false\n get outgoingPorts(): NodePort[] {\n return this.$outputs.map(\n (o, ix): NodePort => ({\n id: this.uid + '#' + o.slotIx,\n label: o.type,\n width: NodeSlotSize,\n height: NodeSlotSize,\n fromNode: this,\n toNode: o.node ?? undefined,\n type: o.type,\n x: this.x + this.width, // + NodeSlotSize / 2,\n y:\n this.y + // start\n NodeTitleHeight + // title\n ix * nodeLineHeight + // e.fromSlotIx * 10,\n nodeLineHeight / 2, //\n }),\n )\n }\n\n get incomingPorts(): NodePort[] {\n return this._incomingEdges().map(\n (e, ix): NodePort => ({\n id: this.uid + '<-' + e.from + '#' + e.fromSlotIx,\n width: NodeSlotSize,\n height: NodeSlotSize,\n fromNode: this.graph.getNode(e.from) ?? undefined,\n toNode: this,\n label: e.inputName,\n type: e.type,\n x: this.x, // - NodeSlotSize / 2,\n y:\n this.y + // start\n NodeTitleHeight + // title\n ix * nodeLineHeight + // e.fromSlotIx * 10,\n nodeLineHeight / 2,\n }),\n )\n }\n\n _incomingEdges(): {\n from: ComfyNodeId\n inputName: string\n type: string\n fromSlotIx: number\n }[] {\n const incomingEdges: {\n from: ComfyNodeId\n inputName: string\n fromSlotIx: number\n type: string\n }[] = []\n\n for (const [inputName, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) {\n const [from, _slotIx] = val as [ComfyNodeId, number]\n const type = this.graph.getNode(from)?.$outputs[_slotIx]?.type ?? 'UNKNOWN'\n incomingEdges.push({ from, inputName, fromSlotIx: _slotIx, type })\n }\n }\n return incomingEdges\n }\n\n /** number of primitive fields in this node */\n primitivesCount(): number {\n return Object.values(this.inputs).filter((val) => !Array.isArray(val)).length\n }\n\n /** width dimensions for autolayout algorithm */\n get width(): number {\n return 200\n }\n\n /** height dimensions for autolayout algorithm */\n get height(): number {\n const inputLen = this._incomingEdges().length\n const outputLen = this.$schema.outputs.length\n const headerCount = Math.max(inputLen, outputLen)\n\n // max height since some nodes have many invisible inputs\n return (this.primitivesCount() + headerCount + 1) * nodeLineHeight\n }\n\n serializeValue(field: string, value: unknown): unknown {\n if (value == null) {\n const schema = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === field)\n if (schema == null) throw new Error(`❌ no schema for field \"${field}\" (of node ${this.$schema.nodeKey})`)\n // console.log('def1=', field, schema.opts.default)\n const opts = schema.opts == null || typeof schema.opts !== 'object' ? undefined : schema.opts\n if (opts?.default != null) return opts.default\n // console.log('def2=', field, schema.required)\n if (!schema.required) return undefined\n console.error(field, 'is required but value is ', value, this.json) //, this)\n this.graph.recordProblem(\n `🔴 [serializeValue] field \"${field}\" (of node ${this.$schema.nodeKey}#${this.uid}) value is null but field is not optional`,\n )\n return undefined\n // throw new Error(\n // `🔴 [serializeValue] field \"${field}\" (of node ${this.$schema.nodeKey}#${this.uid}) value is null`,\n // )\n }\n if (typeof value === 'function') {\n return this.serializeValue(field, value(this.graph.builder, this.graph))\n }\n if (value === auto_) {\n const expectedType = this._getExpectedTypeForField(field)\n console.info(`🔍 looking for type ${expectedType} for field ${field}`)\n for (const node of this.graph.nodes.slice().reverse()) {\n const output = node._getOutputForTypeOrNull(expectedType)\n if (output != null) return [node.uid, output.slotIx]\n }\n throw new Error(`🔴 [AUTO failed] field \"${field}\" (of node ${this.$schema.nodeKey}) value is null`)\n }\n if (value instanceof ComfyNodeOutput) return [value.node.uid, value.slotIx]\n if (value instanceof ComfyNode) {\n const expectedType = this._getExpectedTypeForField(field)\n const output = value._getOutputForTypeOrCrash(expectedType)\n return [value.uid, output.slotIx]\n }\n return value\n }\n\n private _getExpectedTypeForField(name: string): string {\n const input = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name)\n if (input == null) throw new Error('🔴 input not found asdf')\n return input.typeName\n }\n\n private _getOutputForTypeOrCrash(type: string): ComfyNodeOutput<any> {\n const i: NodeOutputExt = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)!\n const val = (this.outputs as any)[i.outKey]\n // console.log(`this[i.name] = ${this.$schema.name}[${i.name}] = ${val}`)\n if (val instanceof ComfyNodeOutput) return val\n throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)\n }\n\n private _getOutputForTypeOrNull(type: string): ComfyNodeOutput<any> | null {\n const i: Maybe<NodeOutputExt> = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)\n if (i == null) return null\n const val = (this.outputs as any)[i.outKey]\n if (val == null) return null\n if (val instanceof ComfyNodeOutput) return val\n throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)\n }\n}\n","import { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\n\n/**\n * runtime builder: one factory method per node of the live schema, defined\n * dynamically. The typed face is `SdkForHost<ID>['Builder']`, obtained via\n * `workflow.builder` (see ComfyWorkflow). The index signature below is what\n * makes the cast between the two legal.\n */\nexport interface ComfyWorkflowBuilder {\n [nodeName: string]: unknown\n}\nexport class ComfyWorkflowBuilder {\n constructor(public graph: ComfyWorkflow) {\n const schema = graph.host.schema\n\n for (const node of schema.nodes) {\n try {\n Object.defineProperty(this, node.nodeKey, {\n value: (inputs: ComfyApiNodeJson['inputs'], meta?: ComfyNodeMetadata) => {\n const uidString = this.___allocateNodeUID(meta)\n const nodePayload: ComfyApiNodeJson = {\n class_type: node.nameInComfy,\n inputs,\n }\n return new ComfyNode(graph, uidString, nodePayload, meta ?? {})\n },\n })\n } catch (e) {\n console.log(e)\n console.error('impossible to create builder for node')\n console.log(`current:`, JSON.stringify(node.nameInComfy), JSON.stringify(node.nodeKey))\n const prev = schema.nodes.find((n) => n.nodeKey === node.nodeKey)\n console.log(`prev`, JSON.stringify(prev?.nameInComfy), JSON.stringify(prev?.nodeKey))\n throw e\n }\n }\n }\n\n /**\n * helper function to allocate an unique node Id while\n * while respecting user provided metadata id if present.\n */\n private ___allocateNodeUID(meta?: ComfyNodeMetadata): string {\n let uidString: string\n if (meta?.id != null && meta.id !== '') {\n // increment the graph _uiNumber, so if we modify this later\n // we won't reuse the same uid and have broken conflicts\n const uidNumber = parseInt(meta.id, 10)\n if (!Number.isNaN(uidNumber) && uidNumber > this.graph._uidNumber)\n this.graph._uidNumber = Math.round(uidNumber + 1)\n uidString = meta.id\n } else {\n uidString = (this.graph._uidNumber++).toString()\n }\n return uidString\n }\n}\n","import type { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { classifySchemaInput } from 'src/sdk-generator/inputWidgetKind.ts'\nimport type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'\nimport type { LiteGraphLinkTuple } from 'src/litegraph/LiteGraphLink.ts'\nimport { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'\nimport type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'\nimport type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'\nimport type { LiteGraphNodeOutput } from 'src/litegraph/LiteGraphNodeOutput.ts'\nimport { asLiteGraphSlotIndex } from 'src/litegraph/LiteGraphSlotIndex.ts'\n\nexport const convertFlowToLiteGraphJSON = (graph: ComfyWorkflow): LiteGraphJSON => {\n const ctx = new LiteGraphCtx(graph)\n const last_node_id = Math.max(...graph.nodes.map((n) => n.uidNumber))\n const xxx = graph.nodes.map((comfyNode) => ({\n liteGraphNode: convertNodeToLiteGraphNode(ctx, comfyNode),\n comfyNode,\n }))\n for (const xx of xxx) {\n const n = xx.liteGraphNode\n n.pos[0] = bang(xx.comfyNode.x)\n n.pos[1] = bang(xx.comfyNode.y)\n for (const o of n.outputs ?? []) {\n o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0])\n }\n }\n return {\n last_node_id,\n last_link_id: ctx.nextLinkId,\n nodes: xxx.map((n) => n.liteGraphNode),\n links: ctx.links,\n config: {},\n extra: {},\n groups: [],\n version: 0.4,\n }\n}\n\nconst convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): LiteGraphNode => {\n const inputs: LiteGraphNodeInput[] = []\n const widgets_values: unknown[] = []\n for (const ipt of node.$schema.inputs) {\n const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy])\n const kind = classifySchemaInput(ipt)\n if (_isLink(raw)) {\n const nodeUidNumber = bang(\n ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber,\n `link target node \"${raw[0]}\" not found in graph`,\n )\n inputs.push({\n name: ipt.nameInComfy,\n type: ipt.typeName,\n // target_slot = index within THIS node's litegraph inputs array,\n // not the schema input index (widget inputs are not litegraph slots)\n link: ctx.allocateLink(\n nodeUidNumber,\n raw[1],\n node.uidNumber,\n asLiteGraphSlotIndex(inputs.length),\n ipt.typeName,\n ),\n })\n } else if (kind.kind === 'widget') {\n // frontend button-widget values ride BEFORE the real value (LOAD_3D)\n widgets_values.push(...kind.prefixValues, raw)\n // control_after_generate phantom AFTER the value: the classifier's\n // consumes covers prefix + value + control, config-driven (the 2024\n // INT-named-seed heuristic lives inside controlConsumes), so export\n // and import can never disagree on the run length\n const phantoms = kind.consumes - 1 - kind.prefixValues.length\n for (let i = 0; i < phantoms; i++) widgets_values.push(false)\n } else {\n // unconnected link-kind input: a litegraph slot with no link —\n // NEVER a widget value (that would misalign the round-trip import)\n inputs.push({ name: ipt.nameInComfy, type: ipt.typeName, link: null })\n }\n }\n const outputs = node.$schema.outputs.map(\n (i, ix): LiteGraphNodeOutput => ({\n // ❌9 name: i.nameInComfy,\n type: i.typeName,\n links: [], // empty links by default 🔴\n slot_index: asLiteGraphSlotIndex(ix),\n name: i.outKey,\n }),\n )\n return {\n type: node.$schema.nameInComfy,\n id: node.uidNumber,\n inputs,\n outputs,\n pos: [0, 0],\n size: [node.width, node.height],\n widgets_values,\n }\n}\n\nconst _isLink = (v: unknown): v is [string, number] => {\n return Array.isArray(v) && v.length === 2 && typeof v[0] === 'string' && typeof v[1] === 'number'\n}\n\nexport class LiteGraphCtx {\n constructor(public graph: ComfyWorkflow) {}\n nextLinkId: number = 0\n links: LiteGraphLinkTuple[] = []\n allocateLink = (\n fromNodeId: number,\n fromNodeOutputIx: number,\n toNodeId: number,\n toNodeInputIx: number,\n linkType: string,\n ): LiteGraphLinkID => {\n const linkId = asLiteGraphLinkID(++this.nextLinkId)\n this.links.push([linkId, fromNodeId, fromNodeOutputIx, toNodeId, toNodeInputIx, linkType])\n return linkId\n }\n}\n","/**\n * local output naming, relative to `.comfy-ts/outputs/`:\n * the server filename is NOT unique — cloud hosts reset the\n * `_00001_` counter every run, so trusting it overwrote the same file — and\n * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name\n * prefix. Local names are ours: dir from the prompt's own filename_prefix\n * (or an explicit save.prefix override), then\n * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically\n * per stem and nothing ever collides.\n */\nexport const localOutputPath = (p: {\n /** explicit local dir override (SaveOptions.prefix) — wins when set */\n localDir?: string\n /** the SaveImage node's own filename_prefix as sent in the prompt */\n filenamePrefix?: string\n /** server-reported subfolder (fallback when no prefix is known) */\n subfolder: string\n /** server-reported filename, e.g. krea_00001_.png */\n filename: string\n /** run timestamp, YYYYMMDD-HHmmss */\n timestamp: string\n}): string => {\n // server name → stem / counter / extension: `krea_00001_.png`\n const dot = p.filename.lastIndexOf('.')\n const ext = dot === -1 ? '' : p.filename.slice(dot)\n const base = dot === -1 ? p.filename : p.filename.slice(0, dot)\n const counterMatch = /_(\\d+)_$/.exec(base)\n const counter = counterMatch?.[1]\n const serverStem = counterMatch != null ? base.slice(0, base.length - counterMatch[0].length) : base\n\n // directory + stem intent: explicit local dir > prompt prefix > server\n // layout. The stem SURVIVES a localDir override — identity keeps sorting\n let dir: string\n let stem: string\n if (p.filenamePrefix != null && p.filenamePrefix !== '') {\n const slash = p.filenamePrefix.lastIndexOf('/')\n dir = slash === -1 ? '' : p.filenamePrefix.slice(0, slash)\n stem = slash === -1 ? p.filenamePrefix : p.filenamePrefix.slice(slash + 1)\n } else {\n dir = p.subfolder\n stem = serverStem\n }\n if (p.localDir != null) dir = p.localDir\n\n const name = [stem === '' ? null : stem, p.timestamp, counter].filter((x) => x != null).join('_') + ext\n return dir === '' ? name : `${dir}/${name}`\n}\n\n/** REPLACE the extension (never append one): a re-encoded save owns its whole\n * name now that local naming is ours, so `save: {format:'image/webp'}` writes\n * `shot_20260731-154210_00001.webp`, not `…_00001.png.webp` — appending\n * described the bytes twice and the first description was a lie */\nexport const withExtension = (path: string, ext: string): string => {\n const slash = path.lastIndexOf('/')\n const dot = path.lastIndexOf('.')\n const stem = dot > slash ? path.slice(0, dot) : path\n return `${stem}.${ext}`\n}\n\n/**\n * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR\n * was already CLAIMED by a still-downloading retrieval (two same-second runs\n * on a counter-resetting cloud host compute the same name).\n * The chosen path is claimed before returning.\n */\nexport const uniquifyOutputPath = (p: {\n path: string\n exists: (path: string) => boolean\n claimed: Set<string>\n}): string => {\n let out = p.path\n if (p.exists(out) || p.claimed.has(out)) {\n const dot = out.lastIndexOf('.')\n const stem = dot === -1 ? out : out.slice(0, dot)\n const ext = dot === -1 ? '' : out.slice(dot)\n for (let n = 2; p.exists(out) || p.claimed.has(out); n++) out = `${stem}-${n}${ext}`\n }\n p.claimed.add(out)\n return out\n}\n\n/** YYYYMMDD-HHmmss, local time — sortable, text-encodable, no colons for filesystems */\nexport const runTimestamp = (d: Date): string => {\n const pad = (n: number): string => String(n).padStart(2, '0')\n return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`\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","// sharp is node-only; the web graph must never carry it (architecture item 13).\n// The import specifier is a VARIABLE on purpose: bundlers cannot statically\n// chase it, so browser builds of comfy-ts/web don't try to resolve sharp —\n// in a browser the import throws at runtime and callers get the loud error.\nimport type SharpNS from 'sharp'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\n\nexport type SharpModule = typeof SharpNS\n\nlet cached: SharpModule | null = null\n\nexport async function importSharp(reason: string): Promise<SharpModule> {\n if (cached != null) return cached\n const specifier = 'sharp'\n try {\n const mod = (await import(specifier)) as { default: SharpModule }\n cached = mod.default\n return cached\n } catch (e) {\n throw new Error(\n `sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`,\n { cause: e },\n )\n }\n}\n","// #region Safety\nexport type Flavor<T, FlavorT> = T & { __tag?: FlavorT }\nexport type Tagged<O, Tag> = O & { __tag?: Tag }\nexport type Branded<O, Brand extends { [key: string]: true }> = O & Brand\n\n// #region Utils\nexport type Maybe<T> = T | null | undefined\n/**\n * Make some keys optional\n * Usage: PartialOmit<{ a: string, b: string }, 'a'> -> { a?: string, b: string }\n */\nexport type PartialOmit<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>\nexport type IsEqual<T, S> = [T] extends [S] ? ([S] extends [T] ? true : false) : false\nexport type EmptyRecord = Record<never, never>\n\n// #region Misc\nexport type number_Timestamp = Tagged<number, 'Timestamp'>\n\n// #region Paths\nexport type AbsolutePath = Tagged<string, { AbsolutePath: true }>\nexport type RelativePath = Tagged<string, { RelativePath: true }>\nexport const asAbsolutePath = (path: string): AbsolutePath => path as AbsolutePath\nexport const asRelativePath = (path: string): RelativePath => path as RelativePath\n\n// #region Image\nexport type ConvertibleImageFormat = 'image/png' | 'image/jpeg' | 'image/webp' | 'raw'\n/** local disk saving is OPT-IN per run: `save: true` = raw bytes, an object re-encodes/relocates */\nexport type SaveOptions = {\n /** 'raw' (default) writes the bytes untouched; an image/* mime re-encodes through sharp */\n format?: ConvertibleImageFormat\n /** local dir under `.comfy-ts/outputs/` (wins over the prompt's own filename_prefix) */\n prefix?: string\n /** 0..1, re-encode only */\n quality?: number\n}\n\n// #region Either\nexport type Either<L, R> = { success: false; value: L } | { success: true; value: R }\nexport const resultSuccess = <T>(value: T): Either<never, T> => ({ success: true, value })\nexport const resultFailure = <T>(value: T): Either<T, never> => ({ success: false, value })\n\n// #region Result\nexport type ResultFailure = { success: false; message: string; error: unknown; value: undefined }\nexport type Result<R> = { success: true; value: R } | ResultFailure\nexport const __OK = <T>(value: T): Result<T> => ({ success: true, value })\nexport const __FAIL = (message: string, error?: unknown): Result<any> => ({\n success: false,\n message,\n error,\n value: undefined,\n})\n\n// #region Markdown\nexport type MDContent = Branded<string, { MDContent: true }>\nexport const asMDContent = (s: string): MDContent => s as MDContent\n\n// #region HTML\nexport type HTMLContent = Branded<string, { HTML: true }>\nexport const asHTMLContent = (s: string): HTMLContent => s as HTMLContent\n","import { type Either, resultFailure, resultSuccess } from 'src/types/index.ts'\n\nexport type TextChunks = {\n [key: string]: string\n}\n\nexport const getPngMetadataFromUint8Array = (pngData: Uint8Array): Either<string, TextChunks> => {\n const dataView = new DataView(\n pngData.buffer,\n pngData.byteOffset, // <-- it just doesn't work without this\n pngData.byteLength, // <-- it just doesn't work without this\n )\n\n // console.log('🟢', dataView.getUint32(0))\n // console.log('🟢', dataView)\n\n // Check that the PNG signature is present\n if (dataView.getUint32(0) !== 0x89504e47) {\n // 🔴 showErrorMessage('Not a valid PNG file')\n return resultFailure('Not a valid PNG file')\n }\n\n // Start searching for chunks after the PNG signature\n let offset = 8\n\n const txt_chunks: TextChunks = {}\n\n // Loop through the chunks in the PNG file\n while (offset < pngData.length) {\n // Get the length of the chunk\n const length = dataView.getUint32(offset)\n // Get the chunk type\n const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8))\n if (type === 'tEXt') {\n // Get the keyword\n let keyword_end = offset + 8\n while (pngData[keyword_end] !== 0) {\n keyword_end++\n }\n const keyword = String.fromCharCode(...pngData.slice(offset + 8, keyword_end))\n // Get the text\n const contentArraySegment = pngData.slice(keyword_end + 1, offset + 8 + length)\n const contentJson = Array.from(contentArraySegment)\n .map((s) => String.fromCharCode(s))\n .join('')\n txt_chunks[keyword] = contentJson\n }\n\n offset += 12 + length\n }\n\n return resultSuccess(txt_chunks)\n}\n","/* please, keep this file as minimal as possible; it's imported by many apps */\nexport function exhaust(x: never): never {\n return x\n}\n","// 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","import { sha1Hex } from 'src/utils/sha1.ts'\n\nexport const hashArrayBuffer = (buffer: Uint8Array): string => {\n return sha1Hex(buffer)\n}\n","import { type } from 'arktype'\nimport type { Maybe, Tagged } from 'src/types/index.ts'\n\n// #region ComfyNodeID\nexport type ComfyNodeId = Tagged<string, 'ComfyNodeId'>\nexport const ComfyNodeId_ark = type.string.as<ComfyNodeId>()\n\n// #region ComfyNodeMetadata\nexport type ComfyNodeMetadata = {\n id?: Maybe<ComfyNodeId>\n\n tag?: string\n\n /** list of tags;\n * those tags will be copied to assets generated by this node.\n * e.g. you can add tags to SaveImage or PreviewImage to automatically tag images they'll produce. */\n tags?: string[]\n\n /** If the node produces an image, image will be stored in an ImageStore with given name.\n * ImageStore are useful for example to always have access to the image when re-running a workflow despite ComfyUI caching. */\n storeAs?: string\n}\nexport const ComfyNodeMetadata_ark = type({\n 'id?': ComfyNodeId_ark,\n 'tag?': 'string',\n 'tags?': 'string[]',\n 'storeAs?': 'string',\n}).as<ComfyNodeMetadata>()\n","import { scope, type } from 'arktype'\nimport { ComfyNodeId_ark } from 'src/graph/ComfyNodeID.ts'\nimport type { Tagged } from 'src/types/index.ts'\n\n/** the id ComfyUI assigns to one queued execution (wire-level name kept) */\nexport type PromptID = Tagged<string, { PromptID: true }>\nexport const PromptID_ark = type.string.as<PromptID>()\n\n// Define the scope and export its types for inference\nconst tempScope = scope({\n PromptID: PromptID_ark,\n ComfyNodeID: ComfyNodeId_ark, // Use the aliased schema\n Timestamp: 'number', // Define Timestamp directly in the scope\n\n ApiPromptInput: {\n client_id: 'string',\n extra_data: { extra_pnginfo: 'unknown' },\n prompt: 'unknown',\n },\n\n NodeProgress: { value: 'number', max: 'number' },\n\n ComfyStatusData: {\n 'sid?': 'string',\n status: {\n exec_info: { queue_remaining: 'number' },\n 'sid?': 'string',\n },\n },\n WsMsgStatus: {\n type: \"'status'\",\n data: 'ComfyStatusData',\n },\n\n _WsMsgExecutionStartData: { prompt_id: 'PromptID' },\n WsMsgExecutionStart: {\n type: \"'execution_start'\",\n data: '_WsMsgExecutionStartData',\n },\n\n _WsMsgExecutionCachedData: { nodes: 'ComfyNodeID[]', prompt_id: 'PromptID' },\n WsMsgExecutionCached: {\n type: \"'execution_cached'\",\n data: '_WsMsgExecutionCachedData',\n },\n\n // node is null on the final 'executing' message (prompt done)\n _WSMsgExecutingData: {\n prompt_id: 'PromptID',\n 'node?': 'ComfyNodeID | null',\n },\n WsMsgExecuting: {\n type: \"'executing'\",\n data: '_WSMsgExecutingData',\n },\n\n ComfyImageInfo: {\n filename: 'string',\n subfolder: 'string',\n type: 'string',\n },\n _WsMsgExecutedData: {\n node: 'ComfyNodeID',\n output: {\n 'previews?': [{ filepath: 'string' }, '[]'],\n 'images?': 'ComfyImageInfo[]',\n // ui payload of a text output node (PreviewAny, and how TextGenerate\n // results reach the client); entries are soft, non-strings are dropped\n 'text?': 'unknown[]',\n },\n prompt_id: 'PromptID',\n },\n WsMsgExecuted: {\n type: \"'executed'\",\n data: '_WsMsgExecutedData',\n },\n\n WsMsgExecutionSuccessData: {\n prompt_id: 'PromptID',\n timestamp: 'Timestamp',\n },\n WsMsgExecutionSuccess: {\n type: \"'execution_success'\",\n data: 'WsMsgExecutionSuccessData',\n },\n\n _WsMsgExecutionErrorData: {\n prompt_id: 'PromptID',\n node_id: 'ComfyNodeID',\n node_type: 'string',\n executed: 'ComfyNodeID[]',\n exception_message: 'string',\n exception_type: 'string',\n traceback: 'string[]',\n current_inputs: 'Record<string, unknown>',\n current_outputs: 'Record<string, unknown>',\n },\n WsMsgExecutionError: {\n type: \"'execution_error'\",\n data: '_WsMsgExecutionErrorData',\n },\n\n WSMsgManagerFeedbackData: { data: 'string' },\n WSMsgManagerFeedback: {\n type: \"'manager-terminal-feedback'\",\n data: 'WSMsgManagerFeedbackData',\n },\n\n // server console stream (/internal/logs): entries are WRITE CHUNKS, not lines\n LogEntry: { t: 'string', m: 'string' },\n _WsMsgLogsData: { entries: 'LogEntry[]', 'size?': 'unknown' },\n WsMsgLogs: {\n type: \"'logs'\",\n data: '_WsMsgLogsData',\n },\n\n // WsMsgProgress must be after NodeProgress\n WsMsgProgress: { type: \"'progress'\", data: 'NodeProgress' },\n\n // per-node progress map (ComfyUI ≥ 0.3.x)\n _WsMsgProgressStateData: {\n prompt_id: 'PromptID',\n nodes: 'Record<string, unknown>',\n },\n WsMsgProgressState: {\n type: \"'progress_state'\",\n data: '_WsMsgProgressStateData',\n },\n\n // UNION TYPES\n PromptRelated_WsMsg:\n 'WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess',\n WsMsg: 'WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg',\n})\n\nexport const types = tempScope.export()\n\n// REQUEST PAYLOADS ------------------------------------------------\nexport type ApiPromptInput = typeof types.ApiPromptInput.infer\n\n// MISC -------------------------------------------------------------\nexport type NodeProgress = typeof types.NodeProgress.infer\n\n// LIVE UPDATES ----------------------------------------------------\nexport type PromptRelated_WsMsg = typeof types.PromptRelated_WsMsg.infer\n\n/** a binary preview-kind ws frame buffered IN ORDER with the json messages\n * during the pre-registration window (ComfyHost._pendingMsgs) — replayed by\n * ComfyExecution.onCreate, which decides output-vs-latent at replay time */\nexport type PendingBinaryFrame = { type: 'binary_preview_frame'; bytes: Uint8Array; mime: string }\nexport type PendingWsItem = PromptRelated_WsMsg | PendingBinaryFrame\nexport type WsMsg = typeof types.WsMsg.infer\nexport type ComfyStatusData = typeof types.ComfyStatusData.infer\nexport type WsMsgStatus = typeof types.WsMsgStatus.infer\nexport type WsMsgExecutionStart = typeof types.WsMsgExecutionStart.infer\nexport type WsMsgExecutionCached = typeof types.WsMsgExecutionCached.infer\nexport type _WSMsgExecutingData = typeof types._WSMsgExecutingData.infer\nexport type WsMsgExecuting = typeof types.WsMsgExecuting.infer\nexport type WsMsgProgress = typeof types.WsMsgProgress.infer\nexport type WsMsgProgressState = typeof types.WsMsgProgressState.infer\nexport type WsMsgExecuted = typeof types.WsMsgExecuted.infer\nexport type WsMsgExecutionSuccess = typeof types.WsMsgExecutionSuccess.infer\nexport type WsMsgExecutionError = typeof types.WsMsgExecutionError.infer\nexport type WSMsgManagerFeedback = typeof types.WSMsgManagerFeedback.infer\nexport type LogEntry = typeof types.LogEntry.infer\nexport type WsMsgLogs = typeof types.WsMsgLogs.infer\nexport type _WsMsgExecutionStartData = typeof types._WsMsgExecutionStartData.infer\nexport type _WsMsgExecutionCachedData = typeof types._WsMsgExecutionCachedData.infer\nexport type ComfyImageInfo = typeof types.ComfyImageInfo.infer\nexport type _WsMsgExecutedData = typeof types._WsMsgExecutedData.infer\nexport type _WsMsgExecutionErrorData = typeof types._WsMsgExecutionErrorData.infer\nexport type PromptId = typeof types.PromptID.infer\n\nexport type PromptInfo = { prompt_id: PromptID }\nexport const PromptInfo_ark = type({ prompt_id: types.PromptID }).as<PromptInfo>()\n\nexport const WsMsg_ark = types.WsMsg\nexport const ComfyImageInfo_ark = types.ComfyImageInfo\nexport const WsMsgLogsData_ark = types._WsMsgLogsData\n","import { type } from 'arktype'\nimport { type ImageMeta, imageMeta } from 'image-meta'\nimport { basename } from 'pathe'\nimport type { Sharp } from 'sharp'\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { importSharp } from 'src/utils/lazySharp.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport { type AbsolutePath, asAbsolutePath, type Maybe } from 'src/types/index.ts'\nimport type { NodeOf } from 'src/types/comfy-sdk.ts'\nimport type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { hashArrayBuffer } from 'src/utils/hashArrayBuffer.ts'\nimport type { ComfyExecution } from 'src/runner/ComfyExecution.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport { type ComfyImageInfo, ComfyImageInfo_ark } from 'src/runner/ComfyWsApi.ts'\nimport { ComfyNode } from 'src/graph/ComfyNode.ts'\n\n/** base64 image loader nodes we know how to wire, in preference order — each\n * verified against a real object_info dump before entering the table */\nexport const BASE64_IMAGE_LOADERS: { nameInComfy: string; inputs: (b64: string) => ComfyApiNodeJson['inputs'] }[] = [\n // comfyui-tooling-nodes: outputs IMAGE + MASK (alpha)\n { nameInComfy: 'ETN_LoadImageBase64', inputs: (b64) => ({ image: b64 }) },\n // ComfyUI-Easy-Use: image_output 'Hide' + empty prefix so the node itself saves nothing\n {\n nameInComfy: 'easy loadImageBase64',\n inputs: (b64) => ({ base64_data: b64, image_output: 'Hide', save_prefix: '' }),\n },\n]\n\nexport type MediaImageData = {\n /** absent = in-memory image (ws output with local saving off) — the buffer is then required */\n path?: Maybe<AbsolutePath>\n\n // to avoid having to read the file if we already have the buffer around\n buffer?: Uint8Array\n\n // provenance ?\n execution?: ComfyExecution\n promptNodeID?: string | null\n\n comfyUIInfos?: ImageInfos_ComfyGenerated\n}\n\nexport type ImageInfos_ComfyGenerated = {\n comfyHostHttpURL: string\n comfyImageInfo: ComfyImageInfo\n}\n\nexport const ImageInfos_ComfyGenerated_ark = type({\n comfyHostHttpURL: 'string',\n comfyImageInfo: ComfyImageInfo_ark,\n})\n\nexport class MediaImage {\n /** null for in-memory images (local saving is opt-in — architecture.md item 14) */\n absPath: AbsolutePath | null\n\n /** the execution this image came from (null when not generated via comfy-ts) */\n execution: Maybe<ComfyExecution>\n\n /** return the workflow from which this image was generated */\n get workflow(): ComfyWorkflow | undefined {\n return this.execution?.workflow\n }\n\n promptNodeID: Maybe<string>\n\n constructor(data: MediaImageData) {\n this.absPath = data.path ?? null\n this.execution = data.execution\n this.promptNodeID = data.promptNodeID\n if (data.path == null && data.buffer == null)\n throw new Error('❌ MediaImage: an in-memory image (no path) requires a buffer')\n if (data.buffer != null) this.updateBuffer(data.buffer)\n }\n\n /** free-form labels; filled from ComfyNodeMetadata.tag(s) when generated via a prompt */\n tags: string[] = []\n\n /** the image as a Blob, e.g. to feed FormData uploads */\n getAsBlob(): Blob {\n return new Blob([this.buffer as Uint8Array<ArrayBuffer>], { type: `image/${this.metadata.type ?? 'png'}` })\n }\n\n /** return the image filename (in-memory images get a stable hash-derived name) */\n get filename(): string {\n if (this.absPath != null) return basename(this.absPath)\n return `image-${this.hash.slice(0, 8)}.${this.metadata.type ?? 'png'}`\n }\n\n get baseNameWithoutExtension(): string {\n const fname = this.filename\n return fname.slice(0, fname.lastIndexOf('.'))\n }\n\n /**\n * return file extension including dot\n * e.g. `.png`, or `.webp`\n * */\n get extension(): string {\n const fname = this.filename\n return fname.slice(((fname.lastIndexOf('.') - 1) >>> 0) + 1)\n }\n\n /** get the expected enum name (hash) */\n get enumName(): ComfyImageName {\n return `${this.hash}${this.extension}` as ComfyImageName\n }\n\n uploadAndReturnEnumName = async (host: ComfyHost): Promise<ComfyImageName> => {\n const finalName = await host.uploader.uploadImage(this, { type: 'input', override: true })\n return finalName\n }\n\n /** upload the media (hash-named, deduped) and load it in the given workflow as a `LoadImage` node */\n loadInWorkflow_viaLoadImageNode = async <WID extends string>(\n workflow: ComfyWorkflow<WID>,\n ): Promise<NodeOf<WID, 'LoadImage'>> => {\n const enumName = await this.uploadAndReturnEnumName(workflow.host)\n const img = bang(workflow.builderBase.LoadImage, 'host has no LoadImage node')({ image: enumName })\n // sanctioned cast: uploaded names are runtime-known; the node itself is the host's LoadImage\n return img as NodeOf<WID, 'LoadImage'>\n }\n\n /** load an image as mask in a comfy workflow beeing created */\n loadInWorkflowAsMask_viaLoadImageMask = async <WID extends string>(\n /** \"alpha\" | \"blue\" | \"green\" | \"red\" */\n channel: 'alpha' | 'blue' | 'green' | 'red',\n /** workflow to load image as mask into */\n workflow: ComfyWorkflow<WID>,\n ): Promise<NodeOf<WID, 'LoadImageMask'>> => {\n const enumName = await this.uploadAndReturnEnumName(workflow.host)\n const mask = bang(\n workflow.builderBase.LoadImageMask,\n 'host has no LoadImageMask node',\n )({\n image: enumName,\n channel,\n })\n // sanctioned cast: same as above\n return mask as NodeOf<WID, 'LoadImageMask'>\n }\n\n /** load this image into the workflow WITHOUT any server-side file: the\n * image rides base64 inside the prompt JSON (architecture.md item 14 —\n * the prompt still enters server history; `scrubHistory` covers that).\n * Feature-detected against the host schema; no supported node = loud throw. */\n loadInWorkflow_viaBase64Node = <WID extends string>(workflow: ComfyWorkflow<WID>): NodeOf<WID, 'LoadImage'> => {\n const schema = workflow.host.schema\n const entry = BASE64_IMAGE_LOADERS.find((t) => schema.nodes.some((n) => n.nameInComfy === t.nameInComfy))\n if (entry == null) {\n throw new Error(\n `❌ host '${workflow.host.data.id}' has no base64 image loader node ` +\n `(looked for: ${BASE64_IMAGE_LOADERS.map((t) => `'${t.nameInComfy}'`).join(', ')}). ` +\n `Install one (e.g. comfyui-tooling-nodes) or fall back to loadInWorkflow_viaLoadImageNode (uploads persist server-side).`,\n )\n }\n const node = new ComfyNode(\n workflow,\n (workflow._uidNumber++).toString(),\n { class_type: entry.nameInComfy, inputs: entry.inputs(this.getBase64Payload()) },\n {},\n )\n // sanctioned cast (family 1, like the two sibling loaders): both table\n // nodes output IMAGE+MASK, the LoadImage face is the shape consumers wire\n return node as NodeOf<WID, 'LoadImage'>\n }\n\n /** return the json of the ComfyNode that led to this image */\n get ComfyNode(): Maybe<ComfyApiNodeJson> {\n const nodeID = this.promptNodeID\n if (nodeID == null) return null\n return this.workflow?.apiJson[nodeID]\n }\n\n /**\n * return the metadata of the ComfyNode that led to this image\n * null if not generated by comfy through a ComfyTS prompt\n * null if no metadata associated in the node in ComfyTS\n */\n get ComfyNodeMetadata(): Maybe<ComfyNodeMetadata> {\n const nodeID = this.promptNodeID\n if (nodeID == null) return null\n return this.workflow?.data.metadata[nodeID]\n }\n\n get width(): number | undefined {\n return this.metadata.width\n } // biome-ignore format: misc\n get height(): number | undefined {\n return this.metadata.height\n } // biome-ignore format: misc\n\n get width_orCrash(): number {\n return bang(this.metadata.width)\n } // biome-ignore format: misc\n get height_orCrash(): number {\n return bang(this.metadata.height)\n } // biome-ignore format: misc\n\n /**\n * return the base64 url for this file, regardless of it's exact representation\n * includes the prefix `data:image/<type>;base64,`\n */\n getBase64Url(): string {\n const imgType = this.metadata.type ?? 'png'\n return `data:image/${imgType};base64,${this.getBase64Payload()}`\n }\n\n /**\n * return the base64 url for this file, regardless of it's exact representation\n * does not includes the prefix `data:image/png;base64,`\n */\n getBase64Payload(): string {\n const bytes = this.buffer\n let bin = ''\n const chunk = 0x8000 // String.fromCharCode arg-count limit\n for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk))\n return btoa(bin)\n }\n\n /** return the ArrayBuffer for this file, regardless it's exact representation */\n\n /** lazilly loaded, call recomputeMetadata to expire */\n private _buffer: Maybe<Uint8Array> = null\n get buffer(): Uint8Array {\n if (this._buffer != null) return this._buffer\n this._buffer = getComfyStorage().readBytes(bang(this.absPath, 'in-memory MediaImage lost its buffer'))\n return this._buffer\n }\n /** no-op on in-memory images: the buffer is the only copy */\n freeBuffer = (): void => {\n if (this.absPath != null) this._buffer = null\n }\n updateBuffer = (buff: Uint8Array): void => {\n this._buffer = buff\n this._metadata = null // expire metadata\n this._hash = null // expire hash\n }\n reloadBuffer = (): Uint8Array => {\n this._buffer = null // expire buffer\n this._metadata = null // expire metadata\n this._hash = null // expire hash\n return this.buffer\n }\n\n /** lazilly computed, call recomputeMetadata to expire */\n private _metadata: Maybe<ImageMeta> = null\n get metadata(): ImageMeta {\n if (this._metadata != null) return this._metadata\n this._metadata = imageMeta(this.buffer)\n return this._metadata\n }\n\n private _hash: Maybe<string> = null\n get hash(): string {\n if (this._hash != null) return this._hash\n this._hash = hashArrayBuffer(this.buffer)\n return this._hash\n }\n\n /**\n * Modify the image directly (inplace) by passing it though a `Sharp` pipeline\n * Sharp is a high performance image processing library.\n */\n processWithSharp_inplace = async (\n /** processing function */\n fn: (sharp: Sharp) => Sharp,\n ): Promise<this> => {\n const sharp = await importSharp('processWithSharp_inplace')\n const buff = await fn(sharp(this.buffer)).toBuffer()\n if (this.absPath != null) getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff))\n this.updateBuffer(new Uint8Array(buff))\n return this\n }\n\n /**\n * Allow to run an image though some `Sharp` pipeline to produce an other image.\n * Sharp is a high performance image processing library.\n * to modify the image directly (inplace), use `processWithSharp_inplace` instead.\n */\n processWithSharp = async (\n /** processing function */\n fn: (sharp: Sharp) => Sharp,\n /** where to save the resulting image */\n path?: AbsolutePath,\n ): Promise<MediaImage> => {\n const sharp = await importSharp('processWithSharp')\n path ??=\n this.absPath != null ? asAbsolutePath(this.absPath + `.processed-${Date.now()}` + this.extension) : undefined\n const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer())\n if (path != null) getComfyStorage().writeBytes(path, buffer)\n return new MediaImage({ path, buffer })\n }\n}\n","import type { FormatEnum } from 'sharp'\nimport { localOutputPath, runTimestamp, uniquifyOutputPath, withExtension } from 'src/runner/outputPath.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { importSharp } from 'src/utils/lazySharp.ts'\nimport { getPngMetadataFromUint8Array } from 'src/image-utils/_getPngMetadata.ts'\nimport type { ComfyNodeId } from 'src/graph/ComfyNodeID.ts'\nimport { type AbsolutePath, asAbsolutePath, type Maybe, type SaveOptions } from 'src/types/index.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { exhaust } from 'src/utils/exhaust.ts'\nimport type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'\nimport type { ComfyWorkflow, ComfyWorkflowID, ExecutionSnapshot, ProgressReport } from 'src/runner/ComfyWorkflow.ts'\n\nimport type {\n ComfyImageInfo,\n PromptID,\n PendingWsItem,\n WsMsgExecuted,\n WsMsgExecuting,\n WsMsgExecutionError,\n WsMsgExecutionSuccess,\n} from 'src/runner/ComfyWsApi.ts'\nimport { MediaImage } from 'src/runner/MediaImage.ts'\n\n/** paths claimed by in-flight retrievals: two same-second runs on a\n * counter-resetting cloud host compute the same name before either writes.\n * A claim is released as soon as the write lands (the file itself then holds\n * the name) or fails (the name is free again) — the set never accumulates */\nconst CLAIMED_OUTPUT_PATHS = new Set<string>()\n\nexport type ComfyExecutionData = {\n id: PromptID\n graphID: ComfyWorkflowID\n executed: boolean\n error?: WsMsgExecutionError | null\n status?: ComfyExecutionStatus | null\n}\n\n/** one text output as an output node published it (`nodeKey` is null when the node left the snapshot) */\nexport type ComfyTextOutput = {\n nodeId: ComfyNodeId\n nodeKey: string | null\n text: string\n}\n\nexport type ExecutionProgress = ProgressReport & {\n promptId: PromptID\n nodeName: string | null\n elapsedMs: number\n /** the executing node's OWN counter, in its own unit: sampler steps, or generated\n * tokens on a text node. Null between nodes. The global percent normalizes this away,\n * and the unit is the only live detail worth reading on a long node */\n nodeProgress: { value: number; max: number } | null\n /** the executing node's live display text, when it publishes one. A streaming generator\n * puts its partial answer here every few tokens */\n progressText: string | null\n}\n\nexport class ComfyExecution {\n get host(): ComfyHost {\n return this.workflow.host\n }\n\n constructor(\n public workflow: ComfyWorkflow,\n public data: ComfyExecutionData,\n init: {\n snapshot?: ExecutionSnapshot\n save?: Maybe<boolean | SaveOptions>\n scrubHistory?: boolean\n ephemeral?: boolean\n onProgress?: Maybe<(p: ExecutionProgress) => void>\n logProgress?: boolean\n } = {},\n ) {\n // settings FIRST: onCreate flushes buffered ws messages whose handlers read them\n this.snapshot = init.snapshot ?? null\n this.save = init.save === true ? {} : init.save === false ? null : (init.save ?? null)\n this.scrubHistory = init.scrubHistory ?? false\n this.ephemeral = init.ephemeral ?? false\n this.onProgress = init.onProgress ?? null\n this.logProgress = init.logProgress ?? false\n // register with the host so websocket messages route here,\n // then flush messages that arrived before we existed\n this.host.executions.set(data.id, this)\n this.onCreate()\n }\n\n /** local disk saving, OPT-IN (architecture.md item 14); null = outputs stay in memory */\n save: Maybe<SaveOptions> = null\n /** delete this run's server history entry after `done` */\n scrubHistory: boolean = false\n /** this run's SaveImage nodes were rewritten to SaveImageWebsocket in the snapshot */\n ephemeral: boolean = false\n\n /** exactly what was sent to the host, frozen at send time (replayable) */\n snapshot: Maybe<ExecutionSnapshot> = null\n\n // ---- progress ----------------------------------------------------------\n /** called on every progress-relevant websocket message */\n onProgress: Maybe<(p: ExecutionProgress) => void> = null\n /** render a live single-line progress report to the console */\n logProgress: boolean = false\n readonly startedAt: number = Date.now()\n\n get progress(): ExecutionProgress {\n const report = this.progressGlobal\n return {\n ...report,\n promptId: this.data.id,\n nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,\n elapsedMs: Date.now() - this.startedAt,\n nodeProgress: this.workflow.currentExecutingNode?.progress ?? null,\n progressText: this.progressText,\n }\n }\n\n private _lastLoggedLine: string = ''\n private emitProgress(): void {\n const p = this.progress\n this.onProgress?.(p)\n if (!this.logProgress) return\n const width = 12\n const filled = Math.round((p.percent / 100) * width)\n const bar = '█'.repeat(filled) + '░'.repeat(width - filled)\n const node = p.nodeName ? ` · ${p.nodeName}` : ''\n // the node's own counter: sampler steps, or generated tokens. Core TextGenerate\n // publishes no partial text, so on it this is the only thing that moves\n const count = p.nodeProgress ? ` ${p.nodeProgress.value}/${p.nodeProgress.max}` : ''\n const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node}${count} · ${(p.elapsedMs / 1000).toFixed(0)}s`\n // a streaming node's newest words, on the same line: the run stays ONE line, and what\n // the model is writing is the thing worth watching on it\n const tail = p.progressText?.replaceAll('\\n', ' ').trimEnd().slice(-60)\n const full = tail == null || tail === '' ? line : `${line} · …${tail}`\n if (full === this._lastLoggedLine) return\n this._lastLoggedLine = full\n if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\\r\\x1b[2K${full}`)\n else console.log(full)\n }\n\n private finishProgressLine(): void {\n if (!this.logProgress) return\n const p = this.progress\n const outputs = [`${this.images.length} image(s)`]\n if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`)\n const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${outputs.join(' · ')}`\n if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\\r\\x1b[2K${line}\\n`)\n else console.log(line)\n }\n\n // promise handle so that we can wait for this execution to finish.\n // resolves in BOTH success and failure — inspect `status` / `data.error`.\n private _resolve!: (value: this) => void\n done: Promise<this> = new Promise((resolve) => {\n this._resolve = resolve\n })\n\n log(...args: unknown[]): void {\n console.log(`[ComfyExecution#${this.data.id}]`, ...args)\n }\n\n onCreate(): void {\n const data: ComfyExecutionData = this.data\n const pending = this.host._pendingMsgs.get(data.id)\n if (pending == null) return\n this.log(`🟢 onCreate: ${pending.length} pending messages`)\n this.host._pendingMsgs.delete(data.id) // buffered once, never again\n for (const msg of pending) this.onPromptRelatedMessage(msg)\n }\n\n get progressGlobal(): ProgressReport {\n if (this.data.status === 'Success') return { countDone: 1, countTotal: 1, isDone: true, percent: 100 }\n return this.workflow.progressGlobal\n }\n\n get status(): 'New' | 'Scheduled' | 'Running' | 'Success' | 'Failure' {\n return this.data.status ?? 'New'\n }\n\n onPromptRelatedMessage = (msg: PendingWsItem): void => {\n const graph = this.workflow\n // replayed pre-registration binary frame: an OUTPUT only when the ws\n // saver was executing at this point of the stream; stale latents drop\n if (msg.type === 'binary_preview_frame') {\n if (this.wsOutputNodeExecuting) this.onWsImageOutput({ bytes: msg.bytes, mime: msg.mime })\n return\n }\n if (msg.type === 'execution_start') return\n else if (msg.type === 'execution_cached') graph.onExecutionCached(msg)\n else if (msg.type === 'executing') this.onExecuting(msg)\n else if (msg.type === 'progress') graph.onProgress(msg)\n else if (msg.type === 'progress_state') {\n // per-node progress map; global progress is derived from the msgs above\n } else if (msg.type === 'executed') this.onExecuted(msg)\n else if (msg.type === 'execution_error') return void this.onError(msg)\n else if (msg.type === 'execution_success') return void this.onExecutionSuccess(msg)\n else {\n console.log(`🔴 UNEXPECTED MESSAGE:`, msg)\n return exhaust(msg)\n }\n this.emitProgress()\n }\n\n /** update pointer to the currently executing node */\n private onExecuting = (msg: WsMsgExecuting): void => {\n this.workflow.onExecuting(msg)\n }\n\n private onExecutionSuccess = async (_msg: WsMsgExecutionSuccess): Promise<void> => {\n await Promise.all(this.pendingPromises)\n return this._finish({ status: 'Success' })\n }\n\n private onError = async (msg: WsMsgExecutionError): Promise<void> => {\n console.error('❌ Execution error:')\n console.error(msg)\n return this._finish({ status: 'Failure', error: msg })\n }\n\n /** update execution list */\n private onExecuted = (msg: WsMsgExecuted): void => {\n const promptNodeID = msg.data.node\n // a STRING output reaches the client ONLY through an output node's ui\n // payload (PreviewAny), never through the prompt result\n for (const entry of msg.data.output?.text ?? []) {\n if (typeof entry !== 'string') continue\n const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null\n this.texts.push({ nodeId: promptNodeID, nodeKey, text: entry })\n }\n const images = msg.data.output?.images\n if (images) {\n for (const img of images) {\n // guard every retrieval: one failed download must not hang `done`\n this.pendingPromises.push(\n this.retrieveImage(img, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to retrieve ${img.filename}:`, e)\n this.imageErrors.push({ image: img, error: e })\n }),\n )\n }\n }\n }\n private pendingPromises: Promise<void>[] = []\n\n /** image retrievals that failed (their images are missing from `images`);\n * `image` is null for SaveImageWebsocket frames (no server-side file info exists) */\n imageErrors: { image: Maybe<ComfyImageInfo>; error: unknown }[] = []\n\n retrieveImage = async (\n //\n comfyImageInfo: ComfyImageInfo,\n promptNodeID: ComfyNodeId,\n ): Promise<void> => {\n // retrieve the node\n const promptNode = this.workflow.data.apiJson?.[promptNodeID]\n if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`)\n\n // image route on the host (cloud answers a 302 signed url — fetchFile follows it unauthed)\n const imgRoute = '/view?' + new URLSearchParams(comfyImageInfo).toString()\n const response = await this.host.fetchFile(imgRoute)\n const bytes = new Uint8Array(await response.arrayBuffer())\n\n const comfyUIInfos = { comfyImageInfo, comfyHostHttpURL: this.host.getServerHostHTTP() }\n\n // local saving is OPT-IN (architecture.md item 14): no save → in-memory only\n const sf = this.save\n if (sf == null) {\n return this.pushImage(\n new MediaImage({ buffer: bytes, execution: this, promptNodeID: promptNodeID, comfyUIInfos }),\n promptNodeID,\n )\n }\n\n const promptPrefix = promptNode.inputs['filename_prefix']\n const written = await this.encodeAndWrite({\n bytes,\n sf,\n filenamePrefix: typeof promptPrefix === 'string' ? promptPrefix : undefined,\n subfolder: comfyImageInfo.subfolder,\n filename: comfyImageInfo.filename,\n })\n this.pushImage(\n new MediaImage({\n path: written.path,\n buffer: written.bytes,\n execution: this,\n promptNodeID: promptNodeID,\n comfyUIInfos,\n }),\n promptNodeID,\n )\n }\n\n /** re-encode when asked, then write under OUR local naming — never the raw\n * server filename: a cloud host resets its _00001_ counter per run, so the\n * server name overwrote the same local file on every run */\n private encodeAndWrite = async (p: {\n bytes: Uint8Array\n sf: SaveOptions\n filenamePrefix?: string\n subfolder: string\n filename: string\n }): Promise<{ path: AbsolutePath; bytes: Uint8Array }> => {\n let bytes = p.bytes\n const reencode = p.sf.format != null && p.sf.format !== 'raw'\n if (reencode) {\n // PNG text chunk (workflow provenance) survives the re-encode as EXIF\n let textChunk = {}\n try {\n const res = getPngMetadataFromUint8Array(p.bytes)\n if (res.success) textChunk = res.value\n } catch {}\n\n const format = ((): keyof FormatEnum => {\n if (p.sf.format === 'image/jpeg') return 'jpeg'\n if (p.sf.format === 'image/webp') return 'webp'\n return 'png'\n })()\n\n // node-only branch: re-encoding needs sharp (save 'raw' is the web path)\n const sharp = await importSharp(`save format '${p.sf.format}' re-encoding`)\n const encoded = await sharp(p.bytes)\n .withMetadata()\n .withExif({ IFD0: textChunk })\n // sharp expect quality between 1 and 100\n .toFormat(format, p.sf.quality ? { quality: Math.round(p.sf.quality * 100) } : undefined)\n .toBuffer()\n bytes = new Uint8Array(encoded)\n }\n\n let absPath: string = comfyts.resolveFromOutput(\n localOutputPath({\n localDir: p.sf.prefix,\n filenamePrefix: p.filenamePrefix,\n subfolder: p.subfolder,\n filename: p.filename,\n timestamp: runTimestamp(new Date(this.startedAt)),\n }),\n )\n if (reencode) absPath = withExtension(absPath, bang(bang(p.sf.format).split('/')[1]))\n // last-resort uniquifier: bump past files on disk AND paths claimed by\n // still-downloading retrievals — never overwrite\n const storage = getComfyStorage()\n absPath = uniquifyOutputPath({ path: absPath, exists: (x) => storage.exists(x), claimed: CLAIMED_OUTPUT_PATHS })\n try {\n storage.writeBytes(asAbsolutePath(absPath), bytes)\n } finally {\n // the file (or the failure) now owns the name — holding the claim\n // forever would grow the set for the whole life of a `serve` process\n CLAIMED_OUTPUT_PATHS.delete(absPath)\n }\n return { path: asAbsolutePath(absPath), bytes }\n }\n\n /** accumulate an output on the prompt; tags from node metadata ride along */\n private pushImage(img: MediaImage, promptNodeID: Maybe<string>): void {\n const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null\n if (promptMeta?.tag) img.tags.push(promptMeta.tag)\n if (promptMeta?.tags) img.tags.push(...promptMeta.tags)\n this.images.push(img)\n }\n\n /** true while the currently executing node is a SaveImageWebsocket in the\n * SENT snapshot (the ephemeral rewrite only touches the snapshot, so the\n * live graph may still say SaveImage) — binary frames are then OUTPUTS */\n get wsOutputNodeExecuting(): boolean {\n const uid = this.workflow.currentExecutingNode?.uid\n if (uid == null) return false\n const apiJson = this.snapshot?.apiJson ?? this.workflow.apiJson\n return apiJson[uid]?.class_type === 'SaveImageWebsocket'\n }\n\n /** one binary ws frame = one output image of the executing SaveImageWebsocket\n * node (architecture.md item 14 — the zero-server-disk path) */\n onWsImageOutput = (p: { bytes: Uint8Array; mime: string }): void => {\n const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null\n this.pendingPromises.push(\n this.storeWsImage(p, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to store a SaveImageWebsocket output:`, e)\n this.imageErrors.push({ image: null, error: e })\n }),\n )\n }\n\n private storeWsImage = async (\n p: { bytes: Uint8Array; mime: string },\n promptNodeID: Maybe<string>,\n ): Promise<void> => {\n const sf = this.save\n if (sf == null) {\n return this.pushImage(new MediaImage({ buffer: p.bytes, execution: this, promptNodeID }), promptNodeID)\n }\n const ext = p.mime === 'image/jpeg' ? 'jpg' : (p.mime.split('/')[1] ?? 'png')\n const written = await this.encodeAndWrite({\n bytes: p.bytes,\n sf,\n subfolder: '',\n // ws frames carry no server filename — the workflow id is the stem\n filename: `${this.workflow.id}.${ext}`,\n })\n this.pushImage(\n new MediaImage({ path: written.path, buffer: written.bytes, execution: this, promptNodeID }),\n promptNodeID,\n )\n }\n\n /** images retrieved for this execution, in arrival order (final once `done` resolves) */\n images: MediaImage[] = []\n\n /** text outputs emitted for this execution, in arrival order (final once `done` resolves) */\n texts: ComfyTextOutput[] = []\n\n /** live display text per node WHILE it runs, newest wins (`send_progress_text` is a\n * replacement, not a delta). This is the only channel carrying text DURING a node: a\n * generator that streams its tokens shows up here, and nowhere in the final outputs */\n progressTexts: Map<string, string> = new Map()\n\n /** the node that most recently published live text — what \"watch it work\" means */\n progressText: string | null = null\n\n /** @internal a live-text frame for one node */\n onProgressText(p: { nodeId: string; text: string }): void {\n this.progressTexts.set(p.nodeId, p.text)\n this.progressText = p.text\n this.emitProgress()\n }\n\n /** the last text output, the one a single-generator workflow means by \"the result\" */\n get text(): string | null {\n return this.texts.at(-1)?.text ?? null\n }\n\n update(data: Partial<ComfyExecutionData>): void {\n Object.assign(this.data, data)\n }\n\n private alreadyDone: boolean = false\n private _finish = async (p: Pick<ComfyExecutionData, 'status' | 'error'>): Promise<void> => {\n if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`)\n this.alreadyDone = true\n this.update({ ...p, executed: true })\n await Promise.all(this.pendingPromises)\n // finished executions receive no further messages — free the routing maps\n this.host.executions.delete(this.data.id)\n this.host._pendingMsgs.delete(this.data.id)\n\n // the inputs gap, stated loud (item 14): ephemeral covers OUTPUTS only —\n // uploaded inputs persist in the server's input/ dir, no upstream delete API\n if (this.ephemeral) {\n const classTypes = Object.values(this.snapshot?.apiJson ?? {}).map((n) => n.class_type)\n if (classTypes.includes('LoadImage') || classTypes.includes('LoadImageMask')) {\n console.warn(\n `🟡 ephemeral run ${this.data.id}: outputs never touched the server disk, but the graph's ` +\n `LoadImage nodes reference files in the host's input/ folder (uploads persist — ComfyUI has ` +\n `no delete API). Use MediaImage.loadInWorkflow_viaBase64Node to keep inputs off the server too.`,\n )\n }\n }\n\n // history scrub AFTER retrievals: loud but never fatal — a privacy\n // feature that crashes the run would push users to disable it\n if (this.scrubHistory) {\n await this.host.deleteHistory(this.data.id).catch((e: unknown) => {\n console.error(`🔴 failed to scrub history entry ${this.data.id} on host ${this.host.data.id}:`, e)\n })\n }\n\n this.finishProgressLine()\n this._resolve(this)\n }\n}\n","import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'\n\n/**\n * the `ephemeral: true` rewrite (architecture.md item 14): every SaveImage\n * node in the SENT snapshot becomes a SaveImageWebsocket (core node, `images`\n * input only), so outputs stream over the ws and never touch the server disk.\n * Mutates the given apiJson IN PLACE — callers pass the run's deep-copied\n * snapshot, never the live graph. Returns how many nodes were rewritten so\n * callers can warn when a graph had nothing to rewrite.\n */\nexport function rewriteSaveNodesToWebsocket(apiJson: ComfyApiJson): number {\n let rewritten = 0\n for (const node of Object.values(apiJson)) {\n if (node.class_type !== 'SaveImage') continue\n const images = node.inputs['images']\n node.class_type = 'SaveImageWebsocket'\n node.inputs = images == null ? {} : { images }\n rewritten++\n }\n return rewritten\n}\n","export const deepCopyNaive = <T>(x: T): T => JSON.parse(JSON.stringify(x))\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","// 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","import type { ArkErrors } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { isQuiet } from 'src/utils/log.ts'\n\nconst MAX_PRINTED_ERRORS = 10\n\nexport function printArkResultInConsole(res: ArkErrors): void {\n if (isQuiet()) return\n console.log(chalk.red(' ❌ Ark validation failed:'))\n for (const error of res.slice(0, MAX_PRINTED_ERRORS)) {\n console.log(chalk.red(` - ${error.path.join('.')} : ${error.message}`))\n }\n if (res.length > MAX_PRINTED_ERRORS) {\n console.log(chalk.red(` … ${res.length - MAX_PRINTED_ERRORS} more (${res.length} total)`))\n }\n}\n","import { type Type, type } from 'arktype'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\n\nexport const softValidate = <T>(schema: Type<T>, stuff: unknown): T => {\n const res = schema(stuff)\n if (res instanceof type.errors) printArkResultInConsole(res)\n return stuff as T\n}\n","type ObjMap<T> = { [key: string]: T }\n\nexport type TNode = string\nexport type TEdge = [TNode, TNode]\n\nexport function toposort(nodes: TNode[], edges: TEdge[]): TNode[] {\n return toposortAlgo(nodes, edges)\n}\n\nfunction toposortAlgo(nodes: TNode[], edges: TEdge[]) {\n let cursor = nodes.length\n const sorted = Array.from<TNode>({ length: cursor })\n const visited: ObjMap<boolean> = {}\n let k = cursor\n\n while (k--) {\n if (!visited[k]) visit(BONG(nodes[k]), k, [])\n }\n\n return sorted\n\n function visit(node: TNode, ix: number, predecessors: TNode[]): void {\n let i = ix\n if (predecessors.indexOf(node) >= 0) {\n console.log(predecessors, node)\n throw new Error('Cyclic dependency: ' + JSON.stringify(node))\n }\n\n if (nodes.indexOf(node) === -1) {\n throw new Error(\n '[toposort] Found unknown node. Make sure to provided all involved nodes. Unknown node: ' +\n JSON.stringify(node) +\n '; known nodes are ' +\n JSON.stringify(nodes),\n )\n }\n\n if (visited[i]) return\n visited[i] = true\n\n // outgoing edges\n const outgoing = edges.filter((edge) => edge[0] === node)\n i = outgoing.length\n if (i) {\n const preds = predecessors.concat(node)\n do {\n const child = BONG(outgoing[--i])[1]\n visit(child, nodes.indexOf(child), preds)\n } while (i)\n }\n\n sorted[--cursor] = node\n }\n}\n\nfunction BONG<T>(x: T): NonNullable<T> {\n if (x == null) throw new Error('BONG')\n return x\n}\n","/** biome-ignore-all lint/style/noNonNullAssertion: later */\nimport type { ComfyNode, ComfyNodeUID } from 'src/graph/ComfyNode.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { type TEdge, toposort } from 'src/utils/toposort.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\n\n/**\n * compute autolayout\n *\n * 💬 2025-06-11 rvion: I tried various autolayout algorithm, but those massive\n * libraries were pretty bad; ended up writing my own simple algorithm, and I'm\n * happy with it. Feel free to improve it, but I think it works well enough.\n * I will accept PRs for new layout algorithms if they don't have massive dependencies.\n **/\nexport function comfyWorkflowAutoLayout(\n this: ComfyWorkflow,\n p?: {\n /** @default: 40 */\n node_vsep?: number\n /** @default: 100 */\n node_hsep?: number\n /** @default false */\n forceLeft?: boolean\n },\n): ComfyWorkflow {\n const nodeIds = toposort(\n this.nodes.map((n) => n.uid),\n this.nodes.flatMap((n) => n._incomingNodes().map((from) => [from, n.uid] as TEdge)),\n )\n const nodes = nodeIds.map((id) => bang(this.getNode(id), `Node not found: ${id}`))\n const cols: ComfyNode[][] = Array.from({ length: nodeIds.length })\n\n type NodePlacement = {\n node: ComfyNode\n minCol: number\n maxCol?: number\n }\n const ranges: {\n [nodeId: ComfyNodeUID]: NodePlacement\n } = {}\n\n // console.log(`[🤠] 1/3 ----------------------------`)\n for (const node of nodes) {\n // must be at least 1 after the closest parent\n const parentCols = node.parents.map((p) => ranges[p.uid]!.minCol)\n const minCol = Math.max(...parentCols, -1) + 1\n const range: NodePlacement = { node: node, minCol: minCol }\n ranges[node.uid] = range\n }\n\n // console.log(`[🤠] 2/3 ----------------------------`)\n if (!p?.forceLeft === true) {\n for (const node of nodes) {\n const range = ranges[node.uid]!\n for (const p of node.parents) {\n const parentRange = ranges[p.uid]!\n parentRange.maxCol =\n parentRange.maxCol != null\n ? Math.min(parentRange.maxCol, (range.maxCol ?? range.minCol) - 1)\n : (range.maxCol ?? range.minCol) - 1\n }\n }\n }\n\n // console.log(`[🤠] 3/3 ----------------------------`)\n for (const node of nodes) {\n const range = ranges[node.uid]!\n const at = range.maxCol ?? range.minCol\n if (cols[at]) cols[at]!.push(node)\n else cols[at] = [node]\n }\n\n // real ComfyUI nodes render wider than the 200px layout estimate, so the\n // horizontal gap is generous to keep pasted graphs readable\n const HSEP = p?.node_hsep ?? 100\n const VSEP = p?.node_vsep ?? 40\n // cols.reverse()\n let colX = 0\n let maxY = 0\n for (const col of cols) {\n if (col == null) continue\n let colWidth = 0\n let currNodeY = 32\n const nodesSorted = col.toSorted((a, b) => b.height - a.height)\n for (const node of nodesSorted) {\n colWidth = Math.max(colWidth, node.width)\n node.x = colX\n node.y = currNodeY\n currNodeY += node.height + VSEP /* V SEP */\n }\n maxY = Math.max(maxY, currNodeY)\n colX += colWidth + HSEP /* H SEP */\n }\n\n this.height = maxY\n this.width = colX\n return this\n}\n","import { nanoid } from 'nanoid'\nimport { describePromptRejection } from 'src/runner/describePromptRejection.ts'\nimport { join } from 'pathe'\nimport { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'\nimport { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'\nimport type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'\nimport { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport { ComfyExecution, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'\nimport { rewriteSaveNodesToWebsocket } from 'src/runner/ephemeral.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport { type AbsolutePath, type Maybe, type SaveOptions, type Tagged } from 'src/types/index.ts'\nimport type { SdkForHost } from 'src/types/comfy-sdk.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { deepCopyNaive } from 'src/utils/deepCopyNaive.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport { comfyWorkflowAutoLayout } from 'src/runner/ComfyWorkflowLayout.ts'\nimport {\n type ApiPromptInput,\n type PromptInfo,\n PromptInfo_ark,\n type WsMsgExecuting,\n type WsMsgExecutionCached,\n type WsMsgProgress,\n} from 'src/runner/ComfyWsApi.ts'\n\nexport type ProgressReport = {\n percent: number\n isDone: boolean\n countDone: number\n countTotal: number\n}\n\nexport type ComfyNodeIdMode = 'use_stringified_numbers_only' | 'use_class_name_and_number'\n\nexport type RunSettings = {\n /** local disk saving is OPT-IN: unset/false keeps outputs in memory only\n * (`execution.images` buffers); `true` = raw save, an object re-encodes/relocates */\n save?: boolean | SaveOptions\n /** rewrite every SaveImage node to SaveImageWebsocket in the SENT prompt —\n * outputs never touch the server disk. Implies `scrubHistory` unless that\n * is explicitly false. (architecture.md item 14) */\n ephemeral?: boolean\n /** delete this run's server history entry (workflow JSON, prompts, filenames)\n * after `done` — loud but non-fatal on failure */\n scrubHistory?: boolean\n idMode?: ComfyNodeIdMode\n /** render a live single-line progress report to the console */\n log?: boolean\n /** called on every progress-relevant websocket message */\n onProgress?: (p: ExecutionProgress) => void\n}\n\n/** exactly what was sent to the host for one execution, frozen at send time */\nexport type ExecutionSnapshot = {\n apiJson: ComfyApiJson\n workflowJson: LiteGraphJSON\n}\n\n/**\n * ComfyWorkflowL\n * - holds the nodes\n * - can be instanciated in both extension and webview\n * - so no link to workspace or run\n */\n\n// #region ComfyWorkflow\nexport type ComfyWorkflow_metadata = { [key: ComfyNodeId]: ComfyNodeMetadata }\n\nexport type ComfyWorkflowID = Tagged<string, { ComfyWorkflowID: true }>\nexport const asComfyWorkflowID = (x: string): ComfyWorkflowID => x\n\nexport type ComfyWorkflowData = {\n id?: Maybe<ComfyWorkflowID>\n\n apiJson?: ComfyApiJson\n metadata: ComfyWorkflow_metadata\n}\n\nexport class ComfyWorkflow<ID extends string = string> {\n id: ComfyWorkflowID\n apiJson: ComfyApiJson\n outputFolder: AbsolutePath\n\n constructor(\n public host: ComfyHost<ID>,\n public data: ComfyWorkflowData,\n ) {\n this.id = data.id ?? (nanoid(8) as ComfyWorkflowID)\n // ONE json object, shared by the field and the data record (registerNode writes there)\n this.apiJson = data.apiJson ?? {}\n data.apiJson = this.apiJson\n this.outputFolder = join(comfyts.outputPath, `workflow-${this.id}`)\n }\n\n /** nodes, in creation order */\n nodes: ComfyNode[] = []\n\n /** @internal every node constructor must call this */\n registerNode = (node: ComfyNode): void => {\n if (this.data.apiJson == null) throw new Error('graph not hydrated')\n this.data.apiJson[node.uid] = node.json\n this.data.metadata[node.uid] = node.meta\n this.nodesIndex.set(node.uid, node)\n this.nodes.push(node)\n }\n\n /** number of node in the graph */\n get size(): number {\n return this.nodes.length\n }\n\n setMetadata = (nodeID: ComfyNodeId, meta: ComfyNodeMetadata): void => {\n this.data.metadata[nodeID] = meta\n }\n\n getMetadata = (nodeID: ComfyNodeId): Maybe<ComfyNodeMetadata> => {\n return this.data.metadata[nodeID] ?? null\n }\n\n /** problem accumulator */\n problems: { title: string; data?: unknown }[] = []\n\n recordProblem = (title: string, data?: unknown): void => {\n this.problems.push({ title, data })\n }\n\n /** workflow builder, typed from the generated per-host sdk when one is in scope */\n private _builder: ComfyWorkflowBuilder | null = null\n get builder(): SdkForHost<ID>['Builder'] {\n if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this)\n // sanctioned cast (see agent/coding.md): the runtime builder defines its\n // methods dynamically from the live schema; the static face comes from\n // the generated per-host sdk. Both derive from the same object_info.\n return this._builder as SdkForHost<ID>['Builder']\n }\n\n /** base (untyped) view of the same builder, for generic library code */\n get builderBase(): Comfy.Builder {\n if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this)\n return this._builder as Comfy.Builder\n }\n\n onUpdate = (prev: Maybe<ComfyWorkflowData>, next: ComfyWorkflowData): void => {\n if (prev != null) {\n this.nodes = []\n this.nodesIndex.clear()\n this.currentExecutingNode = null\n }\n for (const [uid, node] of Object.entries(bang(next.apiJson))) {\n const meta: Maybe<ComfyNodeMetadata> = next.metadata?.[uid]\n new ComfyNode(this, uid, node, meta)\n }\n }\n\n /** proxy to this.db.schema */\n get schema(): ComfySchema {\n return this.host.schema\n }\n\n /** nodes that are still pending execution */\n get pendingNodes(): ComfyNode[] {\n return this.nodes.filter((n) => n.status == null || n.status === 'waiting')\n }\n\n get nodesByUpdatedAt(): ComfyNode[] {\n return this.nodes //\n .filter((n) => n.status != null && n.status !== 'waiting')\n .sort((a, b) => b.updatedAt - a.updatedAt)\n // return this.nodes.slice().sort((a, b) => b.updatedAt - a.updatedAt)\n }\n\n // findNodeByType = <T extends keyof ComfySetup>(nodeKey: T): Maybe<ReturnType<ComfySetup[T]>> => {\n // return this.nodes.find((n) => n.$schema.nodeKey === nodeKey) as any\n // }\n\n /** nodes, indexed by nodeID */\n nodesIndex = new Map<string, ComfyNode>()\n\n /** convert to mermaid DSL expression for nice graph rendering */\n toMermaid = (DIR: 'LR' | 'TD' = 'LR'): string => {\n const out = [\n `graph ${DIR}`,\n this.nodes.map((n) => `${n.uid}[${n.$schema.nodeKey}]`).join('\\n'),\n this.nodes\n .map((n) =>\n n\n ._incomingEdges()\n .map((i) => {\n const from = this.nodesIndex.get(i.from)\n\n return `${from?.uid ?? i.from}[${from?.$schema.nodeKey ?? i.from}] --> |${i.inputName}|${n.uid}[${\n n.$schema.nodeKey\n }]`\n })\n .join('\\n'),\n )\n .join('\\n'),\n ].join('\\n')\n return out\n }\n\n /** export the graph in ComfyUI's saved-workflow format (autolayouted by default) */\n toWorkflowJson = async (p: { layout?: boolean } = {}): Promise<LiteGraphJSON> => {\n if (p.layout !== false) this.autoLayout()\n return convertFlowToLiteGraphJSON(this)\n }\n\n /** export the graph in ComfyUI's api format (what POST /prompt takes) */\n toApiJson = (ns: ComfyNodeIdMode = 'use_stringified_numbers_only'): ComfyApiJson => {\n const json: ComfyApiJson = {}\n const keyOf = (uid: string): string =>\n ns === 'use_stringified_numbers_only' ? uid : (this.nodesIndex.get(uid)?.uidPrefixed ?? uid)\n for (const node of this.nodes) {\n if (node.disabled) continue\n const key = ns === 'use_stringified_numbers_only' ? node.uid : node.uidPrefixed\n // links reference node keys — remap them to whatever key scheme we emit\n const inputs: ComfyApiNodeJson['inputs'] = {}\n for (const [name, value] of Object.entries(node.json.inputs)) {\n inputs[name] =\n Array.isArray(value) && typeof value[0] === 'string' && typeof value[1] === 'number'\n ? [keyOf(value[0]), value[1]]\n : value\n }\n json[key] = { class_type: node.json.class_type, inputs }\n }\n return json\n }\n\n /** @internal pointer to the currently executing node */\n currentExecutingNode: ComfyNode | null = null\n\n get progressCurrentNode(): Maybe<ProgressReport> {\n return this.currentExecutingNode?.progressReport\n }\n\n get progressGlobal(): ProgressReport {\n const totalNode = this.nodes.length\n const doneNodes = this.nodes.filter((n) => n.status === 'done' || n.status === 'cached').length\n const bonus = this.currentExecutingNode?.progressRatio ?? 0\n const score = (doneNodes + bonus) / totalNode\n const percent = this.done ? 100 : score * 100\n const isDone = this.done\n return { percent, isDone, countDone: doneNodes + bonus, countTotal: totalNode }\n }\n\n /** @internal update the progress value of the currently focused onde */\n onProgress = (msg: WsMsgProgress): void => {\n if (this.currentExecutingNode == null) return void console.log('❌ no current executing node', msg)\n this.currentExecutingNode.progress = msg.data\n this.currentExecutingNode.progressRatio = (msg.data.value ?? 0) / (msg.data.max || 1)\n }\n\n getTargetWorkflowFilePath = (): AbsolutePath => {\n return join(this.cacheFolderPath, 'workflow.json')\n }\n\n getTargetPromptFilePath = (): AbsolutePath => {\n return join(this.cacheFolderPath, 'prompt.json')\n }\n\n get cacheFolderPath(): AbsolutePath {\n return comfyts.resolveFromOutput(`workflows/${this.id}`)\n }\n\n // private outputs: WsMsgExecuted[] = []\n // images: ImageL[] = []\n\n done: boolean = false\n\n /** @internal update pointer to the currently executing node */\n onExecuting = (msg: WsMsgExecuting): void => {\n // 1. mark currentExecutingNode as done\n if (this.currentExecutingNode) {\n this.currentExecutingNode.status = 'done'\n // this.currentExecutingNode.updatedAt = Date.now() + 1000\n }\n // 2. then two cases:\n // 2.A. no node => the prompt is done\n if (msg.data.node == null) {\n this.currentExecutingNode = null\n this.done = true\n return\n }\n\n this.done = false\n // 2.B. a node => node evaluation is starting\n const node = this.getNodeOrCrash(msg.data.node)\n this.currentExecutingNode = node\n node.status = 'executing'\n node.updatedAt = Date.now()\n }\n\n onExecutionCached = (msg: WsMsgExecutionCached): void => {\n for (const x of msg.data.nodes) {\n const node = this.getNodeOrCrash(x)\n node.status = 'cached'\n }\n }\n\n // onExecuted = (msg: WsMsgExecuted) => {\n // const node = this.getNodeOrCrash(msg.data.node)\n // const images = msg.data.output.images.map((i) => new PromptOutputImage(this, i))\n\n // // console.log(`🟢 `, images.length, `CushyImages`)\n // // accumulate in self\n // this.outputs.push(msg)\n // this.images.push(...images)\n // // console.log(`🟢 `, this.uid, 'has', this.images.length, `CushyImages`)\n\n // // accumulate in node\n // node.artifacts.push(msg.data)\n // node.images.push(...images)\n // }\n\n _uidNumber: number = 0\n\n getNodeOrCrash = (nodeID: ComfyNodeId): ComfyNode => {\n const node = this.nodesIndex.get(nodeID)\n if (node == null) throw new Error('Node not found:' + nodeID)\n return node\n }\n\n getNode = (nodeID: ComfyNodeId): Maybe<ComfyNode> => {\n const node = this.nodesIndex.get(nodeID)\n return node\n }\n\n width: number = 100\n height: number = 100\n\n /** compute autolayout **/\n autoLayout = comfyWorkflowAutoLayout.bind(this)\n\n /** send the workflow and wait for it to finish (with all outputs downloaded) */\n run = async (p: RunSettings = {}): Promise<ComfyExecution> => {\n const execution = await this.start(p)\n await execution.done\n return execution\n }\n\n /** reset per-run node state so the same workflow can run again cleanly */\n private resetRunState(): void {\n this.done = false\n this.currentExecutingNode = null\n for (const node of this.nodes) {\n node.status = null\n node.progress = null\n node.progressRatio = 0\n }\n }\n\n /** send the workflow; returns the live execution (await `execution.done` yourself) */\n start = async (p: RunSettings = {}): Promise<ComfyExecution> => {\n // without a ws the prompt still RUNS on the host, but its messages route to a session\n // that is not ours, so `execution.done` never settles: a silent forever-hang, the one\n // failure mode with no error to read. DefinedWorkflow.run() connects for you\n if (this.host.ws == null)\n throw new Error(\n `🔴 host '${this.host.data.id}' was never connected — call \\`await host.connect()\\` before running a workflow`,\n )\n this.resetRunState()\n // snapshot: exactly what runs, frozen at send time (the live workflow stays editable)\n const snapshot: ExecutionSnapshot = {\n apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? 'use_stringified_numbers_only')),\n workflowJson: await this.toWorkflowJson(),\n }\n // ephemeral: rewrite in the SNAPSHOT only — the live graph stays editable/exportable as authored\n if (p.ephemeral) {\n const rewritten = rewriteSaveNodesToWebsocket(snapshot.apiJson)\n const hasWsSaver = Object.values(snapshot.apiJson).some((n) => n.class_type === 'SaveImageWebsocket')\n if (rewritten === 0 && !hasWsSaver)\n console.warn(\n `🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`,\n )\n }\n const out: ApiPromptInput = {\n client_id: this.host.comfySessionId,\n prompt: snapshot.apiJson,\n extra_data: {\n extra_pnginfo: {\n // regular ComfyUI metadata (drag the file in the editor -> the graph)\n workflow: snapshot.workflowJson,\n comfy_ts_workflow_id: this.id,\n comfy_ts_version: comfyts.version,\n },\n },\n }\n\n const res = await this.host.fetch('/prompt', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(out),\n })\n const promptInfoJson: unknown = await res.json()\n // a REJECTED prompt is not a malformed success: ComfyUI answers non-200 with its own\n // reason and no prompt_id, so validating first reported \"prompt_id must be a string\"\n // and threw away the sentence that says which node and which value it refused\n if (res.status !== 200) {\n throw new InvalidPromptError(\n `ComfyUI refused the prompt: ${describePromptRejection(promptInfoJson)}`,\n snapshot,\n promptInfoJson,\n )\n }\n const promptInfo: PromptInfo = softValidate(PromptInfo_ark, promptInfoJson)\n // settings + snapshot go through the constructor: the ctor flushes ws\n // messages that raced ahead, and those handlers need the settings\n const execution = new ComfyExecution(\n this,\n {\n id: promptInfo.prompt_id,\n executed: false,\n graphID: this.id,\n },\n {\n snapshot,\n save: p.save,\n ephemeral: p.ephemeral ?? false,\n // ephemeral implies the scrub unless the caller explicitly opted out\n scrubHistory: p.scrubHistory ?? p.ephemeral ?? false,\n onProgress: p.onProgress,\n logProgress: p.log ?? false,\n },\n )\n return execution\n }\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","/** having a bunch of sensible default will help slightly */\nexport function getUnionNameBasedOnFirstFoundEnumName(\n //\n enumName: string,\n hash: string,\n hashContent: string,\n): string {\n // core enums\n if (enumName === 'KSampler.sampler_name') return 'E_SamplerName'\n if (enumName === 'KSampler.scheduler') return 'E_SchedulerName'\n if (enumName === 'CheckpointLoaderSimple.ckpt_name') return 'E_CkptName'\n if (enumName === 'VAELoader.vae_name') return 'E_VaeName'\n if (enumName === 'LoraLoader.lora_name') return 'E_LoraName'\n // upscape methods\n if (enumName === 'LatentUpscale.upscale_method') return 'E_LatentUpscaleMethod'\n if (enumName === 'ImageScale.upscale_method') return 'E_ImageUpscaleMethod'\n // core objects\n if (enumName === 'LoadImage.image') return 'E_Image'\n if (enumName === 'LoadImageMask.channel') return 'E_Channel'\n // misc\n if (enumName === 'KSamplerAdvanced.add_noise') return 'E_EnableOrDisable'\n if (enumName === 'LatentRotate.rotation') return 'E_Rotation'\n if (enumName === 'LatentFlip.flip_method') return 'E_FlipMethod'\n if (enumName === 'CLIPLoader.type') return 'E_ClipType'\n if (enumName === 'UNETLoader.weight_dtype') return 'E_WeightDType'\n if (enumName === 'DualCLIPLoader.type') return 'E_DualClipType'\n if (enumName === 'CheckpointLoader.config_name') return 'E_CkptConfigName'\n\n // civitai_comfy_nodes\n if (enumName === 'civitai_comfy_nodes.CivitAI_Checkpoint_Loader.ckpt_name') return 'E_CivitAICkptName'\n\n // Impact-Specific\n if (enumName === 'Impact-Pack.SAMDetectorCombined.detection_hint') return 'E_ImpactDetectionHint'\n\n // Misc\n if (hashContent === 'false|true') return 'E_TrueOrFalse'\n if (hashContent === 'CPU|GPU') return 'E_CpuOrGpu'\n return 'E_' + hash\n}\n","export function pythonModuleToPrefix(pythonModule: string): string {\n // if (pythonModule == null) console.error(`[🔴🔴🔴🔴🔴🔴] `, pythonModule)\n if (pythonModule === 'nodes') return ''\n if (pythonModule.startsWith('comfy_extras.')) return '' //''\n // ships INSIDE the ComfyUI repo (upstream parks it under custom_nodes/):\n // the ephemeral-outputs saver reads `b.SaveImageWebsocket` like the core node it is\n if (pythonModule === 'custom_nodes.websocket_image_save') return ''\n if (pythonModule.startsWith('comfy_api_nodes.')) return pythonModule.replace('comfy_api_nodes.', 'api.')\n if (pythonModule.startsWith('custom_nodes.')) {\n // return `${pythonModuleToNamespace_(pythonModule.replace('custom_nodes.', ''))}.`\n return (\n pythonModule //\n // remove always present \"custom_nodes.\" prefix\n .replace(/^custom_nodes\\./i, '')\n // remove common ~comfyui prefixes and suffixes\n .replace(/^comfyui[-_]/i, '')\n .replace(/[-_]comfyui$/i, '')\n // remove common ~comfy prefixes and suffixes\n .replace(/^comfy[-_]/i, '')\n .replace(/[-_]comfy$/i, '')\n // remove common ~nodes prefixes and suffixes\n .replace(/^nodes[-_]/i, '')\n .replace(/[-_]node[-_]suite$/i, '') + '.'\n )\n }\n // unknown module layout: fall back to a sanitized module prefix instead of\n // crashing the whole codegen because of one unusual custom node\n console.warn(`[comfy-ts] unexpected pythonModule \"${pythonModule}\", using it as prefix as-is`)\n return `${pythonModule}.`\n}\n","import { pythonModuleToPrefix } from 'src/sdk-generator/_pythonModuleToNamespace.ts'\n\nexport const toQualifiedNodeKey = (pythonModule: string, nameInComfy: string): string => {\n return `${pythonModuleToPrefix(pythonModule)}${nameInComfy}`\n}\n","/** this class is used to buffer text and then write it to a file */\nexport class CodeBuffer {\n public tab: string = ' '\n constructor(\n private _indent: number = 0,\n lines: string[] = [],\n ) {\n for (const line of lines) this.writeLine(line)\n }\n\n content: string = ''\n\n // #region adding text\n newLine = (): string => (this.content += '\\n')\n line = (...txts: string[]): this => this.writeLine(txts.join(''))\n append = (str: string): string => (this.content += str)\n writeLine = (txt: string): this => {\n this.content +=\n txt\n .split('\\n')\n .map((line) => repeatStr(this._indent, this.tab) + line)\n .join('\\n') + '\\n'\n return this\n }\n w = (txt: string, opts: { if: boolean } = { if: true }): void => {\n if (opts.if) this.writeLine(txt)\n }\n\n // #region indentations\n indent = (): number => this._indent++\n deindent = (): number => this._indent--\n indented = (fn: () => void): void => {\n this._indent++\n fn()\n this._indent--\n }\n\n bar = (text: string): void => this.w(renderBar(text, '// '))\n\n // writeTS = (path: string) => {\n // // const prefix = `// FILE GENERATED: do not edit. Changes made manually will be overwritten.\\n\\n`\n // // const outPretty = prefix + prettify(this.content)\n // const outPretty = prettify(this.content)\n // writeFileSync(path, outPretty, 'utf-8')\n // }\n}\n\nexport const repeatStr = (x: number, str: string): string => {\n let out = ''\n for (let i = 0; i < x; i++) out += str\n return out\n}\n\nexport const renderBar = (text: string, prefix: string = ''): string => {\n const ___bar___ = '============================================================================='\n return (\n `${prefix}|${___bar___}|\\n` +\n `${prefix}| ${text} ${repeatStr(___bar___.length - text.length - 4, ' ')} |\\n` +\n `${prefix}|${___bar___}|`\n )\n}\n","const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/\n\nconst isValidJSKey = (s: string): boolean => {\n return regex.test(s)\n}\n\nexport const escapeJSKey = (s: string): string => {\n if (typeof s !== 'string') {\n return 'string'\n // console.log(s)\n // debugger\n }\n // ❌ probably wrong\n if (!isValidJSKey(s)) {\n // debugger\n return `\"${s}\"`\n }\n return s\n}\n\nexport const asJSAccessor = (s: string): string => {\n if (typeof s !== 'string') {\n return 'string'\n // console.log(s)\n // debugger\n }\n if (!isValidJSKey(s)) {\n // debugger\n return `[\"${s}\"]`\n }\n return `.${s}`\n}\n","import type { Maybe } from 'src/types/index.ts'\nimport { CodeBuffer } from 'src/utils/CodeBuffer.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport type { ComfyInputOpts, ComfyNodeSchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport type { ComfyUnionInfo, NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { ComfyPrimitiveMapping } from 'src/sdk-generator/Primitives.ts'\n\nexport type NodeOwnEnum = {\n in: 'input' | 'output'\n ownName: string\n enum: ComfyUnionInfo\n}\n\nexport class ComfyNodeSchema {\n /** list of types the node has a single output of */\n _singleOutputs: Maybe<NodeOutputExt[]> = null\n\n get singleOutputs(): NodeOutputExt[] {\n if (this._singleOutputs != null) return this._singleOutputs\n const x: { [key: string]: number } = {}\n for (const i of this.outputs) x[i.typeName] = (x[i.typeName] ?? 0) + 1\n this._singleOutputs = this.outputs.filter((i) => x[i.typeName] === 1)\n return this._singleOutputs\n }\n\n constructor(\n public raw: ComfyNodeSchemaJSON,\n public nameInComfy: string,\n public nodeKey: string, // same but qualified to keep track of pythonNamespace\n public category: string,\n public inputs: NodeInputExt[],\n public outputs: NodeOutputExt[],\n public pythonModule: string,\n ) {\n this.category = this.category.replaceAll('/', '_')\n }\n\n codegenUI(): string {\n const b = new CodeBuffer()\n const p = b.w\n p(` ${escapeJSKey(this.nodeKey)}: {`)\n this.inputs.forEach((i, _ix) => {\n // 1/3\n if (i.isPrimitive) {\n const tsType = ComfyPrimitiveMapping[i.typeName]\n if (tsType == null) return console.log(`[🔶] invariant violation`)\n p(` ${escapeJSKey(i.nameInComfy)}: { kind: '${tsType}', type: ${tsType} }`)\n }\n // 2/3\n else if (i.isEnum) {\n p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: Union['${i.typeName}'] }`)\n // p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: '${this.nodeKey}.${i.nameInComfy}' }`) // prettier-ignore\n }\n // 3/3\n else {\n p(` // ${escapeJSKey(i.nameInComfy)}: { kind: 'object', type: ${i.typeName} }`)\n }\n })\n p(` }`)\n return b.content\n }\n\n renderOpts(opts?: ComfyInputOpts): Maybe<string> {\n if (opts == null) return null\n if (typeof opts === 'string') return null\n let out = '/**'\n if (opts.default != null) out += ` default=${JSON.stringify(opts.default)}`\n if (opts.min != null) out += ` min=${JSON.stringify(opts.min)}`\n if (opts.max != null) out += ` max=${JSON.stringify(opts.max)}`\n if (opts.step != null) out += ` step=${JSON.stringify(opts.step)}`\n out += ' */'\n return out\n }\n}\n\nexport const wrapQuote = (s: string): string => {\n if (s.includes(\"'\")) return `\"${s}\"`\n return `'${s}'`\n}\n","import type { Maybe } from 'src/types/index.ts'\nimport { CodeBuffer } from 'src/utils/CodeBuffer.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\n\nimport { type ComfyNodeSchema, wrapQuote } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport {\n classifySchemaInput,\n containerInstanceSlotType,\n isRecord,\n type DynamicComboOption,\n type RawInputSpecEntry,\n} from 'src/sdk-generator/inputWidgetKind.ts'\n\nconst isScalar = (x: unknown): x is string | number | boolean =>\n typeof x === 'string' || typeof x === 'number' || typeof x === 'boolean'\n\n/** a dynamic-combo branch input, typed the way its dotted prompt key is filled: inline enums\n * and COMBO option lists become literal unions, everything else stays a named slot */\nconst branchInputType = (entry: RawInputSpecEntry): string => {\n const opts = isRecord(entry.opts) ? entry.opts : null\n const literals = Array.isArray(entry.type) ? entry.type : Array.isArray(opts?.['options']) ? opts['options'] : []\n const scalars = literals.filter(isScalar)\n if (scalars.length > 0) return scalars.map((o) => JSON.stringify(o)).join(' | ')\n if (typeof entry.type === 'string') return `Accepts[${JSON.stringify(entry.type)}]`\n return 'string | number | boolean'\n}\n\n/** `& ({key:'a'; 'name.x'?: …} | {key:'b'})` — one member per branch, so a key from a branch\n * you did not select is a type error. Branch fields are optional: ComfyNode fills them\n * from the schema at serialization (agent/architecture.md, dynamic-combo fill) */\nconst dynamicComboUnion = (p: {\n name: string\n nameEscaped: string\n options: DynamicComboOption[]\n keyOptional: boolean\n}): string => {\n const members = p.options.map((opt) => {\n const fields = opt.inputs.map(\n (e) => `${escapeJSKey(`${p.name}.${e.name}`)}?: ${branchInputType(e)}`, //\n )\n const key = `${p.nameEscaped}${p.keyOptional ? '?' : ''}: ${JSON.stringify(opt.key)}`\n return `{ ${[key, ...fields].join('; ')} }`\n })\n return ` & (${members.join(' | ')})`\n}\n\n/**\n * convert a host id to the namespace name it gets inside the global `Comfy` namespace\n * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'\n */\nexport function hostIdToNamespace(hostId: string): string {\n const parts = hostId.split(/[^a-zA-Z0-9]+/).filter(Boolean)\n const ns = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('')\n if (ns.length === 0) throw new Error(`cannot derive a namespace from host id \"${hostId}\"`)\n // namespaces can't start with a digit\n return /^[0-9]/.test(ns) ? `Host${ns}` : ns\n}\n\nexport type CodegenOptions = {\n /** host id; drives both the `Comfy.Hosts` registry key and the namespace name */\n hostId: string\n /** module to import runtime-facing types from (default: 'comfy-ts') */\n packageName?: string\n}\n\n/**\n * emit the typed SDK for one host:\n *\n * declare global {\n * namespace Comfy {\n * namespace <HostNs> { IN / OUT / Node / Builder / Slots / Accepts / Union / ... }\n * interface Hosts { '<host-id>': <HostNs>.Sdk }\n * }\n * }\n */\nexport function codegenSDK(this: ComfySchema, opts: CodegenOptions): string {\n const ns = hostIdToNamespace(opts.hostId)\n const packageName = opts.packageName ?? 'comfy-ts'\n const b = new CodeBuffer()\n const p = b.w\n\n p(`/** generated by comfy-ts for host \"${opts.hostId}\" — do not edit */`)\n p(``)\n p(`import type { ComfyNode, ComfyNodeOutput, ComfyNodeMetadata, ComfyNodeSchemaJSON } from '${packageName}'`)\n p(``)\n p(`declare global {`)\n b.indent()\n\n p(`namespace Comfy {`)\n b.indent()\n\n p(`namespace ${ns} {`)\n b.indent()\n\n // #region PythonModules ----------------------------------------------------------------------\n p(`// #${''}region PythonModules`)\n p(`/** list of all python modules installed on this host */`)\n p(`export type PythonModules =`)\n b.indent()\n const pythonModulesArr: [string, string[]][] = Array.from(this.pythonModules.entries()) //\n .toSorted((a, b) => a[0].localeCompare(b[0]))\n for (const [k, v] of pythonModulesArr) {\n p(`/**`)\n p(`* Nodes: ${v.join(', ')}`)\n p(`*/`)\n p(`| ${wrapQuote(k)}`)\n }\n b.deindent()\n p(`// #${''}endregion`)\n\n // #region IN ---------------------------------------------------------------------------------\n const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey))\n p(`interface IN {`)\n b.indent()\n for (const n of nodes) {\n p(`${escapeJSKey(n.nodeKey)}: {`)\n // dynamic combos leave the flat body and come back as an intersected\n // union suffix, one member per branch (agent/sdk-codegen.md)\n const comboSuffixes: string[] = []\n for (const i of n.inputs) {\n // autogrow container: emit dotted instance keys, never the container\n // decl itself — the backend prompt input is `<name>.<inst>`, the\n // first template.min instances required (agent/sdk-codegen.md)\n const kind = classifySchemaInput(i)\n if (kind.kind === 'dynamic-container') {\n const instType = containerInstanceSlotType(i.opts)\n if (instType != null) {\n kind.instanceNames.forEach((instName, ix) => {\n const opt = ix >= kind.requiredCount ? '?' : ''\n p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`)\n })\n }\n continue\n }\n if (kind.kind === 'dynamic-combo') {\n const optsDyn = typeof i.opts === 'string' ? null : i.opts\n comboSuffixes.push(\n dynamicComboUnion({\n name: i.nameInComfy,\n nameEscaped: i.nameInComfyEscaped,\n options: kind.options,\n keyOptional: optsDyn?.default !== undefined || !i.required,\n }),\n )\n continue\n }\n const opts_ = typeof i.opts === 'string' ? null : i.opts\n let type = `Accepts[${JSON.stringify(i.typeName)}]`\n // COMBO inputs (ComfyUI ≥ 0.3.x) carry literal choices in opts.options\n const comboOptions =\n i.typeName === 'COMBO' && Array.isArray(opts_?.options)\n ? opts_.options.filter(\n (o): o is string | number | boolean =>\n typeof o === 'string' || typeof o === 'number' || typeof o === 'boolean',\n )\n : []\n if (comboOptions.length > 0) {\n type = `${comboOptions.map((o) => JSON.stringify(o)).join(' | ')} | ${type}`\n }\n // custom text/primitive widget types (placeholder/multiline/default in opts)\n // also accept the raw literal, e.g. AUTOCOMPLETE_TEXT_LORAS is just a string\n else if (opts_ && !i.isPrimitive && !i.isEnum) {\n if (typeof opts_.default === 'string' || opts_.placeholder != null || opts_.multiline != null) {\n type = `string | ${type}`\n } else if (typeof opts_.default === 'number') {\n type = `number | ${type}`\n } else if (typeof opts_.default === 'boolean') {\n type = `boolean | ${type}`\n }\n }\n if (opts_) {\n const rendered = n.renderOpts(opts_)\n if (rendered) p(` ${rendered}`)\n }\n const canBeOmmited = opts_?.default !== undefined || !i.required\n p(` ${i.nameInComfyEscaped}${canBeOmmited ? '?' : ''}: ${type}`)\n }\n p(`}${comboSuffixes.join('')},`)\n }\n b.deindent()\n p('}')\n p('')\n\n // #region OUT --------------------------------------------------------------------------------\n p(`interface OUT {`)\n b.indent()\n for (const n of nodes) {\n p(`${escapeJSKey(n.nodeKey)}: {`)\n n.outputs.forEach((i, ix) => {\n p(` ${escapeJSKey(i.outKey)}: ComfyNodeOutput<'${i.typeName}', ${ix}>,`)\n })\n p(`}`)\n }\n b.deindent()\n p('}')\n\n // #region Node -------------------------------------------------------------------------------\n p(`interface Node {`)\n for (const n of nodes) {\n p(\n ` ${escapeJSKey(n.nodeKey)}: ComfyNode<IN[${JSON.stringify(n.nodeKey)}], OUT[${JSON.stringify(n.nodeKey)}]> & {`,\n )\n for (const hassingle of n.singleOutputs) {\n p(` ${escapeJSKey(`_${hassingle.typeName}`)}: ComfyNodeOutput<'${hassingle.typeName}'>`)\n }\n p(` }`)\n }\n p('}')\n\n // #region Builder ----------------------------------------------------------------------------\n p(`interface Builder {`)\n for (const n of nodes) {\n const baseDescription = `displayName=\"${n.raw.display_name}\" category=\"${n.category}\" name=\"${n.nameInComfy}\" output=[${n.outputs.map((o) => o.outKey).join(', ')}]`\n if (n.raw.description) {\n p(` /**`)\n p(\n n.raw.description\n .split('\\n')\n .map((i) => ` * ${i}`)\n .join('\\n'),\n )\n p(` * ${baseDescription}`)\n p(` **/`)\n } else {\n p(` /** ${baseDescription} */`)\n }\n p(\n ` ${escapeJSKey(n.nodeKey)}(p: IN[${JSON.stringify(n.nodeKey)}], meta?: ComfyNodeMetadata): Node[${JSON.stringify(n.nodeKey)}]`,\n )\n }\n p(`}`)\n\n // #region Slots ------------------------------------------------------------------------------\n p(`interface Slots {`)\n for (const e of this.knownUnionByHash.values()) {\n p(' // ' + e.unionName)\n for (const alias of e.enumNames) {\n p(` ${escapeJSKey(alias)}: Union['${e.unionName}']`)\n }\n }\n p(`}`)\n\n // #region Embeddings -------------------------------------------------------------------------\n p(`type Embeddings = ${this.data.embeddings.map((e) => wrapQuote(e)).join(' | ') || '\"\"'}`)\n\n const slotTypes = [...this.knownSlotTypes.values()] //\n .map((comfyType) => ({\n comfyType,\n tsType: this.toTSType(comfyType),\n tsType2: this.toAcceptsType(comfyType),\n }))\n .sort((a, b) => b.tsType.length - a.tsType.length)\n\n // #region Producer ---------------------------------------------------------------------------\n p('')\n p('interface Producer {')\n b.indent()\n for (const tp of slotTypes) {\n const allProducingNodes: Maybe<ComfyNodeSchema[]> = this.nodesByProduction[tp.comfyType]\n if (allProducingNodes) {\n p(`${escapeJSKey(tp.comfyType)}: Pick<Builder, ${allProducingNodes.map((i) => `'${i.nodeKey}'`).join(' | ')}>`)\n } else {\n p(`${escapeJSKey(tp.comfyType)}: {}, // no node can output this type.`)\n }\n }\n b.deindent()\n p('}')\n\n // #region Accepts -----------------------------------------------------------------------------\n p(`interface Accepts {`)\n b.indent()\n // 1/3\n p('// injected bottom type (broken/null input specs land here)')\n p(`INVALID_null: any`)\n\n // 2/3\n p('')\n p('// named slot types: everything an input of that type accepts')\n for (const t of slotTypes) {\n p(\n `${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`,\n )\n }\n\n // 3/3\n p('')\n p('// enum unions: literal values or an output carrying one')\n for (const t of this.knownUnionByHash.values()) {\n p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`)\n }\n b.deindent()\n p(`}\\n`)\n\n // #region Union ------------------------------------------------------------------------------\n p('interface Union {')\n for (const e of this.knownUnionByHash.values()) {\n if (e.values.length > 0) {\n p(` // ${JSON.stringify(e.enumNames)}`)\n p(` ${e.unionName}: ${e.values.map((v) => `${JSON.stringify(v)}`).join(' | ')}`)\n } else {\n p(` ${e.unionName}: '🔴' // never`)\n }\n }\n p('}')\n\n // #region HasSingle --------------------------------------------------------------------------\n p(`export interface HasSingle {`)\n for (const t of slotTypes) {\n p(` ${escapeJSKey(t.comfyType)}: { '_${t.comfyType}': ${t.tsType} }`)\n }\n p(`}`)\n\n for (const t of this.enumsAppearingInOutput.values()) {\n p(`export interface HasSingle_${t} { _${t}: Union['${t}'] }`)\n }\n\n // #region Schemas ----------------------------------------------------------------------------\n p(`export type Schemas = { [k in NodeType]: ComfyNodeSchemaJSON }`)\n p(`export type NodeType = ${this.nodes.map((i) => `'${i.nodeKey}'`).join(' | ')}`)\n\n // #region Sdk --------------------------------------------------------------------------------\n p(``)\n p(`/** everything above, packaged for the Comfy.Hosts registry */`)\n p(`interface Sdk {`)\n p(` IN: IN`)\n p(` OUT: OUT`)\n p(` Node: Node`)\n p(` Builder: Builder`)\n p(` Slots: Slots`)\n p(` Accepts: Accepts`)\n p(` Union: Union`)\n p(` Producer: Producer`)\n p(` Embeddings: Embeddings`)\n p(` Schemas: Schemas`)\n p(` NodeType: NodeType`)\n p(`}`)\n\n b.deindent()\n p(`}`) // end namespace <HostNs>\n\n p(``)\n p(`interface Hosts {`)\n p(` ${wrapQuote(opts.hostId)}: ${ns}.Sdk`)\n p(`}`)\n\n b.deindent()\n p('}') // end namespace Comfy\n\n b.deindent()\n p('}') // end declare global\n p(``)\n p(`export {}`)\n\n return b.content\n}\n","import type { Branded } from 'src/types/index.ts'\nimport type { ComfyInputOpts } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\n\nexport type ComfyUnionHash = string // '26c34bf761d4be4554ab944105c5a3c017c99453\nexport type ComfyUnionName = string // 'E_26c34bf761d4be4554ab944105c5a3c017c99453'\nexport type ComfyUnionValue = string | boolean | number\n\nexport type ComfyPythonModule = string\nexport type NodeNameInComfy = string\nexport type QualifiedNodeKey = string\n\n/**\n * the textual name of a slot type (slot = input or output of a node),\n * e.g. 'MODEL', 'IMAGE', 'E_CkptName'.\n * Branded string — internals never depend on the global Comfy namespace\n * (that would break host encapsulation: slot types are per-host).\n */\nexport type ComfyNodeSlotTypeName = Branded<string, { SlotTypeName: true }>\nexport const asComfyNodeSlotTypeName = (x: string): ComfyNodeSlotTypeName => x as ComfyNodeSlotTypeName\n\n/** a fully-qualified slot name, e.g. 'LoadImage.image' or 'KSampler.LATENT.OUT' */\nexport type ComfyNodeSlotName = Branded<string, { SlotName: true }>\nexport const asComfyNodeSlotName = (x: string): ComfyNodeSlotName => x as ComfyNodeSlotName\n\nexport type EmbeddingName = Branded<string, { Embedding: true }>\n\nexport type NodeInputExt = {\n slotName: ComfyNodeSlotName\n nameInComfy: string\n nameInComfyEscaped: string\n typeName: ComfyNodeSlotTypeName\n opts?: ComfyInputOpts\n isPrimitive: boolean\n isEnum: boolean\n required: boolean\n index: number\n}\n\nexport type NodeOutputExt = {\n slotName: ComfyNodeSlotName\n typeName: ComfyNodeSlotTypeName\n outKey: string\n nameInComfy: string\n isPrimitive: boolean\n}\n\nexport type ComfyUnionInfo = {\n hash: ComfyUnionHash\n unionName: ComfyUnionName\n values: ComfyUnionValue[]\n enumNames: ComfyNodeSlotName[]\n}\n\n/** an image file name as known by the host (hash-named upload or existing input) */\nexport type ComfyImageName = Branded<string, { ComfyImageName: true }>\nexport const asComfyImageName = (x: string): ComfyImageName => x as ComfyImageName\n","import { sha1HexOfString } from 'src/utils/sha1.ts'\nimport { statelessRegex } from 'src/utils/matchesRegex.ts'\nimport { getUnionNameBasedOnFirstFoundEnumName } from 'src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts'\nimport { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'\nimport { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyEnumDef, ComfyNodeSchemaJSON, ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport { codegenSDK } from 'src/sdk-generator/comfyui-sdk-codegen.ts'\nimport { classifyWidgetInput, containerInstanceSlotType } from 'src/sdk-generator/inputWidgetKind.ts'\nimport {\n asComfyNodeSlotName,\n asComfyNodeSlotTypeName,\n type ComfyImageName,\n type ComfyNodeSlotName,\n type ComfyNodeSlotTypeName,\n type ComfyPythonModule,\n type ComfyUnionHash,\n type ComfyUnionInfo,\n type ComfyUnionName,\n type ComfyUnionValue,\n type EmbeddingName,\n type NodeInputExt,\n type NodeNameInComfy,\n type NodeOutputExt,\n type QualifiedNodeKey,\n} from 'src/sdk-generator/comfyui-types.ts'\nimport {\n ComfyDefaultNodeWhenUnknown_Name,\n ComfyDefaultNodeWhenUnknown_Schema,\n ComfyPrimitiveMapping,\n ComfyPrimitives,\n} from 'src/sdk-generator/Primitives.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport { logInfo } from 'src/utils/log.ts'\n\nexport type ComfySchemaId = string\n\nexport type ComfySchemaData = {\n spec: ComfySchemaJSON\n embeddings: string[]\n}\n\n/**\n * ONE host's schema: the parsed view of its object_info.json + embeddings.\n * Owns union dedup (by sha1 of values), node indexing, and the per-host\n * sdk codegen (`codegenDTS`).\n */\nexport class ComfySchema {\n codegenDTS = codegenSDK.bind(this)\n\n constructor(public data: ComfySchemaData) {\n this.parse()\n }\n\n update(data: Partial<ComfySchemaData>): void {\n const prev: ComfySchemaData = { spec: this.data.spec, embeddings: this.data.embeddings }\n Object.assign(this.data, data)\n try {\n this.parse()\n this.isInvalid = false\n } catch (error) {\n console.error(`❌ [ComfySchema.update] bad schema — keeping the previous one`, error)\n // roll back: a failed update must not leave half-built indexes in use\n this.data = prev\n try {\n this.parse()\n } catch {\n // previous data unparsable too (first update): indexes stay empty\n }\n this.isInvalid = true\n }\n }\n\n isInvalid: boolean = false\n\n /** number of nodes in the current schema (quick way to check your instance infos) */\n get size(): number {\n return Object.keys(this.data.spec).length\n }\n\n // #region parsed indexes\n knownSlotTypes = new Set<ComfyNodeSlotTypeName>()\n knownUnionBySlotName = new Map<ComfyNodeSlotName, ComfyUnionInfo>()\n knownUnionByHash = new Map<ComfyUnionHash, ComfyUnionInfo>()\n knownUnionByName = new Map<ComfyUnionName, ComfyUnionInfo>()\n nodes: ComfyNodeSchema[] = []\n pythonModuleByNodeKey: Map<QualifiedNodeKey, ComfyPythonModule> = new Map()\n pythonModuleByNodeNameInComfy: Map<NodeNameInComfy, ComfyPythonModule> = new Map()\n nodesByNameInComfy: { [key: NodeNameInComfy]: ComfyNodeSchema } = {}\n nodesByKey: { [key: QualifiedNodeKey]: ComfyNodeSchema } = {}\n nodesByProduction: { [key in ComfyNodeSlotTypeName]?: ComfyNodeSchema[] } = {}\n\n // some nodes output anonymous unions. we need to keep track of them for codegen\n enumsAppearingInOutput = new Set<ComfyNodeSlotTypeName>()\n\n pythonModules = new Map<string, NodeNameInComfy[]>()\n\n // #region parse\n private parse(): void {\n // reset all indexes: parse() re-runs on every update()\n this.knownSlotTypes.clear()\n this.knownUnionBySlotName.clear()\n this.knownUnionByHash.clear()\n this.knownUnionByName.clear()\n this.nodes = []\n this.pythonModuleByNodeKey.clear()\n this.pythonModuleByNodeNameInComfy.clear()\n this.nodesByNameInComfy = {}\n this.nodesByKey = {}\n this.nodesByProduction = {}\n this.enumsAppearingInOutput.clear()\n this.pythonModules.clear()\n\n // skip log for the initial dummy empty data\n if (this.data.embeddings.length > 0 || Object.keys(this.data.spec).length > 0)\n this.log(`parsing ComfyUI object_info.json`)\n\n const entries: [string, ComfyNodeSchemaJSON][] = Object.entries(this.data.spec)\n entries.push([ComfyDefaultNodeWhenUnknown_Name, ComfyDefaultNodeWhenUnknown_Schema])\n\n for (const [KK, VV] of entries) {\n // record python module\n const pythonModule = VV.python_module\n const prev = this.pythonModules.get(pythonModule)\n if (prev == null) this.pythonModules.set(pythonModule, [KK])\n else prev.push(KK)\n\n const nodeNameInComfy = KK\n const nodeDef = VV\n const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy)\n\n if (typeof nodeDef.output === 'string') {\n console.log(\n `[❌ ERROR] nodeDef ${nodeDef.name} has an invalid output definition: ${JSON.stringify(nodeDef.output)}`,\n )\n nodeDef.output = []\n }\n this.pythonModuleByNodeKey.set(nodeKey, pythonModule)\n this.pythonModuleByNodeNameInComfy.set(nodeNameInComfy, pythonModule)\n\n const inputs: NodeInputExt[] = []\n const outputs: NodeOutputExt[] = []\n const node = new ComfyNodeSchema(VV, nodeNameInComfy, nodeKey, nodeDef.category, inputs, outputs, pythonModule)\n\n // INDEX NODE\n this.nodesByNameInComfy[nodeNameInComfy] = node\n this.nodesByKey[nodeKey] = node\n this.nodes.push(node)\n\n // #region outputs ----------------------------------------------------------------------\n const nameCountDict: { [key: string]: number } = {}\n for (const [ix, slotType] of nodeDef.output.entries()) {\n const rawOutputSlotName =\n nodeDef.output_name[ix] || //\n (typeof slotType === 'string' ? slotType : `input_${ix}`)\n\n const outputNameInComfy = rawOutputSlotName\n const at = (nameCountDict[outputNameInComfy] ??= 0)\n const outKeyValue = at === 0 ? outputNameInComfy : `${outputNameInComfy}_${at}`\n nameCountDict[outputNameInComfy]++\n\n let slotTypeName: ComfyNodeSlotTypeName\n const outputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${outKeyValue}.OUT`)\n\n // 1. Primitive\n if (typeof slotType === 'string') {\n slotTypeName = asComfyNodeSlotTypeName(slotType)\n this.knownSlotTypes.add(slotTypeName)\n }\n // 2. ENUM\n else if (Array.isArray(slotType)) {\n const RESX = this.processSlot({ pythonModule, slotName: outputSlotName, comfyUnionDef: slotType })\n slotTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n this.enumsAppearingInOutput.add(slotTypeName)\n }\n // 3. ????\n else {\n throw new Error(`invalid output ${ix} \"${slotType}\" in node \"${nodeNameInComfy}\"`)\n }\n\n // index production\n const arr = this.nodesByProduction[slotTypeName]\n if (arr == null) this.nodesByProduction[slotTypeName] = [node]\n else arr.push(node)\n\n outputs.push({\n slotName: outputSlotName,\n typeName: slotTypeName,\n nameInComfy: outputNameInComfy,\n outKey: outKeyValue,\n isPrimitive: false,\n })\n }\n\n // #region inputs ----------------------------------------------------------------------\n const optionalInputs = Object.entries(nodeDef.input?.optional ?? {}) //\n .map(([name, spec]) => ({ required: false, name, spec }))\n\n const requiredInputs = Object.entries(nodeDef.input?.required ?? {}) //\n .map(([name, spec]) => ({ required: true, name, spec }))\n // when an input is BOTH required and optional (seen in the wild), keep the optional one\n .filter((i) => optionalInputs.find((oi) => oi.name === i.name) == null)\n const allInputs = [...requiredInputs, ...optionalInputs]\n\n for (const ipt of allInputs) {\n const inputNameInComfy = ipt.name\n const typeDef = ipt.spec\n const slotType = typeDef[0]\n const slotOpts = typeDef[1]\n\n let inputTypeName: ComfyNodeSlotTypeName\n const inputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${inputNameInComfy}`)\n\n // 1/4 broken input (null type)\n if (slotType == null) {\n const RESX = this.processSlot({ pythonModule, slotName: inputSlotName, comfyUnionDef: ['❌'] })\n inputTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n }\n // 2/4 named slot type\n else if (typeof slotType === 'string') {\n inputTypeName = asComfyNodeSlotTypeName(slotType)\n this.knownSlotTypes.add(inputTypeName)\n }\n // 3/4 inline enum\n else if (Array.isArray(slotType)) {\n const RESX = this.processSlot({ pythonModule, slotName: inputSlotName, comfyUnionDef: slotType })\n inputTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n }\n // 4/4\n else {\n throw new Error(\n `invalid schema (${JSON.stringify(slotType)}) for input \"${\n ipt.name\n }\" in node \"${nodeNameInComfy}\" (type: ${typeof slotType}; expected: Array | string)`,\n )\n }\n\n // autogrow container: the declaration is never a prompt input\n // (instances are `<name>.<inst>` link slots) — never required, and\n // its template sub-input slot type registers like any slot so\n // codegen can type the dotted instance keys (agent/sdk-codegen.md)\n const widgetKind =\n typeof slotType === 'string'\n ? classifyWidgetInput({ name: ipt.name, type: slotType, opts: slotOpts })\n : null\n const isAutogrowContainer = widgetKind?.kind === 'dynamic-container'\n if (isAutogrowContainer) {\n const instType = containerInstanceSlotType(slotOpts)\n if (instType != null) this.knownSlotTypes.add(asComfyNodeSlotTypeName(instType))\n }\n // dynamic combo: a branch input is typed by its dotted prompt key,\n // so its slot type must register like any slot (agent/sdk-codegen.md)\n if (widgetKind?.kind === 'dynamic-combo') {\n for (const opt of widgetKind.options) {\n for (const entry of opt.inputs) {\n if (typeof entry.type === 'string') this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type))\n }\n }\n }\n\n node.inputs.push({\n slotName: inputSlotName,\n required: ipt.required && !isAutogrowContainer,\n nameInComfy: inputNameInComfy,\n nameInComfyEscaped: escapeJSKey(inputNameInComfy),\n typeName: inputTypeName,\n opts: slotOpts,\n isPrimitive: ComfyPrimitives.includes(inputTypeName),\n isEnum: this.knownUnionByName.has(inputTypeName),\n index: node.inputs.length,\n })\n }\n }\n }\n\n // #region processSlot\n processSlot = (p: {\n pythonModule: string\n slotName: ComfyNodeSlotName\n comfyUnionDef: ComfyEnumDef\n }): ComfyUnionInfo => {\n // 1. build enum\n const enumValues: ComfyUnionValue[] = []\n for (const enumValue of p.comfyUnionDef) {\n if (typeof enumValue === 'string') enumValues.push(enumValue)\n else if (typeof enumValue === 'boolean') enumValues.push(enumValue)\n else if (typeof enumValue === 'number') enumValues.push(enumValue)\n else enumValues.push(enumValue.content)\n }\n // 2. hash its value\n const hashContent =\n enumValues.length === 0 //\n ? `[[empty]]`\n : enumValues.sort().join('|')\n const hash = sha1HexOfString(hashContent).slice(0, 8)\n\n // 3. retrieve or create an EnumInfo\n let unionInfo: Maybe<ComfyUnionInfo> = this.knownUnionByHash.get(hash)\n if (unionInfo == null) {\n const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent)\n unionInfo = { hash, unionName, values: enumValues, enumNames: [] }\n this.knownUnionByHash.set(hash, unionInfo)\n this.knownUnionByName.set(unionName, unionInfo)\n }\n unionInfo.enumNames.push(p.slotName)\n\n // 4. store enum by name\n this.knownUnionBySlotName.set(p.slotName, unionInfo)\n return unionInfo\n }\n\n private log(...args: unknown[]): void {\n logInfo(`[👅]: ${args.join(' ')}`)\n }\n\n toTSType(t: string): string {\n // '*' is ComfyUI's wildcard: any output or primitive fits\n if (t === '*') return `string | number | boolean | ComfyNodeOutput<string, number>`\n return ComfyPrimitiveMapping[t]\n ? `${ComfyPrimitiveMapping[t]} | ComfyNodeOutput<'${t}'>`\n : `ComfyNodeOutput<'${t}'>`\n }\n\n toAcceptsType(t: string): string {\n return `ComfyNodeOutput<'${t}'>`\n }\n\n // #region discovery helpers\n /**\n * every possible value for a given slot, straight from the live schema.\n * e.g. schema.values('LoraLoader.lora_name') -> all loras on this host\n */\n values(slotName: string): ComfyUnionValue[] {\n return this.knownUnionBySlotName.get(asComfyNodeSlotName(slotName))?.values ?? []\n }\n\n /** string values only (most enums are), for quick discovery */\n stringValues(slotName: string): string[] {\n return this.values(slotName).filter((v): v is string => typeof v === 'string')\n }\n\n /**\n * for now, simply ensure that the number of parsed nodes matches the number\n * of nodes present in the object_info.json\n */\n RUN_BASIC_CHECKS = (): void => {\n const numNodesInSource = Object.keys(this.data.spec).length\n // +1: the injected UnknownNodeXX default schema\n const numNodesInSchema = this.nodes.length - 1\n if (numNodesInSource !== numNodesInSchema) {\n console.log(`🔴 parsed ${numNodesInSchema} nodes but object_info has ${numNodesInSource}`)\n }\n }\n\n hasEmbedding(embedding: string): embedding is EmbeddingName {\n return this.data.embeddings.includes(embedding)\n }\n\n hasLora(loraName: string): boolean {\n return this.getLoras().includes(loraName)\n }\n\n /** all loras on the host, optionally narrowed by a regex */\n getLoras = (filter?: RegExp): string[] => {\n const all = this.stringValues('LoraLoader.lora_name')\n const stateless = filter == null ? null : statelessRegex(filter)\n return stateless == null ? all : all.filter((n) => stateless.test(n))\n }\n\n hasImage(imgName: string): imgName is ComfyImageName {\n return this.getImages().includes(imgName)\n }\n\n getImages = (): string[] => {\n return this.stringValues('LoadImage.image')\n }\n\n /**\n * only use this function after an upload success,\n * when you say this asset is now part of ComfyUI\n **/\n unsafely_addImageInSchemaWithoutReloading = (imgName: ComfyImageName): void => {\n const enumInfo = this.knownUnionBySlotName.get(asComfyNodeSlotName('LoadImage.image'))\n if (enumInfo == null) throw new Error(`LoadImage.image not found`)\n enumInfo.values.push(imgName)\n }\n\n hasCheckpoint(ckptName: string): boolean {\n return this.getCheckpoints().includes(ckptName)\n }\n\n getCheckpoints = (): string[] => {\n return this.stringValues('CheckpointLoaderSimple.ckpt_name')\n }\n}\n","import { scope, type } from 'arktype'\n\nexport const ComfyUIObjectInfoScope = scope({\n ComfySchemaJSON: { '[string]': 'ComfyNodeSchemaJSON' },\n ComfyNodeSchemaJSON: {\n input: {\n 'required?': { '[string]': 'ComfyInputSpec' },\n 'optional?': { '[string]': 'ComfyInputSpec' },\n 'hidden?': { '[string]': 'ComfyInputHiddenEntry' },\n },\n 'input_order?': {\n 'required?': 'string[]',\n 'optional?': 'string[]',\n 'hidden?': 'string[]',\n },\n output: 'ComfyInputType[]',\n output_is_list: 'boolean[]',\n output_name: 'string[]',\n name: 'string',\n display_name: 'string',\n description: 'string',\n /** */\n python_module: 'string',\n category: 'string',\n output_node: 'boolean',\n 'output_tooltips?': 'string[]',\n // Stability Flags\n 'deprecated?': 'boolean',\n 'experimental?': 'boolean',\n },\n ComfyInputSpecAlt1: ['ComfyInputType', 'ComfyInputOpts'],\n ComfyInputSpecAlt2: ['ComfyInputType'],\n // means it's broken: some nodes declare an input whose spec is literally\n // [null] — accepted here so ONE bad node cannot fail a whole schema parse\n ComfyInputSpecAlt3: type([type.null]),\n ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,\n\n ComfyInputType: `string | ComfyEnumDef`,\n\n ComfyInputHiddenEntry_broken1: '\"CHOOSE\"[][]', // BROKEN STUFF (e.g. found in several 'rgthree' nodes)\n ComfyInputHiddenEntry_broken2: type.Record('string', type.unknown), // BROKEN STUFF (e.g. found in \"ttN xyPlot\")\n ComfyInputHiddenEntry: 'string | ComfyInputHiddenEntry_broken1 | ComfyInputHiddenEntry_broken2 ',\n\n ComfyInputOpts_simple: 'string',\n ComfyInputOpts_advanced: {\n // 💬 2025-06-11 rvion: \"ComfyInputOpts_advanced\" added because of Segment.input.optional.background : Segment.input.optional.background[1].tooltip must be a string or null (was an object) or Segment.input.optional.background must be exactly length 1 (was 2)\n 'tooltip?': 'string | null | ComfyInputOpts_advanced',\n 'multiline?': 'boolean | null',\n\n // 💬 2025-06-11 rvion: \"number[]\" added because of CreateShapeImageOnPath.input.optional.size_multiplier : CreateShapeImageOnPath.input.optional.size_multiplier[1].default must be a number, a string, boolean or null (was an object) or CreateShapeImageOnPath.input.optional.size_multiplier must be exactly length 1 (was 2)\n 'default?': 'boolean | number | string | null | number[]',\n\n 'forceInput?': 'boolean | null',\n 'min?': 'number | null',\n 'round?': 'boolean | number | null',\n 'max?': 'number | null',\n 'step?': 'number | null',\n /** Observed on 2024-11-01; 171 occurrences */\n 'dynamicPrompts?': 'boolean',\n\n /** text widgets (e.g. LoraManager autocomplete fields) */\n 'placeholder?': 'string | null',\n\n /** COMBO-typed inputs (ComfyUI ≥ 0.3.x) carry their choices here */\n 'options?': 'unknown[] | null',\n 'multiselect?': 'boolean | null',\n\n // 💬 2025-06-11 rvion: \"0\" added because of CustomControlNetWeightsFluxFromList.input.optional.autosize : CustomControlNetWeightsFluxFromList.input.optional.autosize[1].padding must be boolean (was 0) or CustomControlNetWeightsFluxFromList.input.optional.autosize must be exactly length 1 (was 2)\n 'padding?': 'boolean | 0',\n },\n ComfyInputOpts: 'ComfyInputOpts_simple | ComfyInputOpts_advanced',\n\n ComfyEnumIllustratedItem: {\n content: 'string',\n 'image?': 'string | null',\n },\n ComfyEnumItem: 'string | number | boolean | ComfyEnumIllustratedItem',\n ComfyEnumDef: `ComfyEnumItem[]`,\n})\n\nconst types = ComfyUIObjectInfoScope.export()\n\nexport type ComfySchemaJSON = typeof types.ComfySchemaJSON.infer\nexport type ComfyNodeSchemaJSON = typeof types.ComfyNodeSchemaJSON.infer\nexport type ComfyInputSpec = typeof types.ComfyInputSpec.infer\nexport type ComfyInputType = typeof types.ComfyInputType.infer\nexport type ComfyEnumDef = typeof types.ComfyEnumDef.infer\nexport type ComfyInputOpts = typeof types.ComfyInputOpts.infer\n\nexport const ComfySchemaJSON_ark = types.ComfySchemaJSON\nexport const ComfyNodeSchemaJSON_ark = types.ComfyNodeSchemaJSON\nexport const ComfyInputSpec_ark = types.ComfyInputSpec\nexport const ComfyInputType_ark = types.ComfyInputType\nexport const ComfyEnumDef_ark = types.ComfyEnumDef\nexport const ComfyInputOpts_ark = types.ComfyInputOpts\n","const tab = ' '\n\nexport function readableStringify(obj: unknown, maxLevel = 3, level = 0): string {\n if (level > maxLevel) return JSON.stringify(obj)\n if (typeof obj !== 'object' || obj === null) return JSON.stringify(obj)\n const indent = ' '.repeat(level + 1)\n let result = '{\\n'\n const keys = Object.keys(obj)\n for (let i = 0; i < keys.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: don't care\n const key = keys[i]!\n // biome-ignore lint/suspicious/noExplicitAny: don't care\n const value = (obj as any)[key]\n if (value === undefined) continue\n const valueType = typeof value\n\n if (i > 0) result += ','\n const thisIndent = i > 0 ? indent.slice(1) : indent\n if (Array.isArray(value)) {\n result += `${thisIndent}${JSON.stringify(key)}: ${JSON.stringify(value)}`\n } else if (valueType === 'object' && value !== null) {\n result += `${thisIndent}${JSON.stringify(key)}: ${readableStringify(value, maxLevel, level + 1)}`\n } else {\n const formattedValue = valueType === 'string' ? JSON.stringify(value) : value\n result += `${thisIndent}${JSON.stringify(key)}: ${formattedValue}`\n }\n result += '\\n'\n }\n result += `${tab.repeat(Math.max(0, level))}}`\n\n return result\n}\n","import { type } from 'arktype'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\n\nexport type ComfyManagerAPIModelList = typeof ComfyManagerAPIModelList_ark.infer\nexport const ComfyManagerAPIModelList_ark = type({\n models: type({\n name: type.string.as<KnownModel_Name>(),\n installed: `'False' | 'True' | 'Update'`,\n }).array(),\n})\n","import { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\n\nexport type ComfyManagerAPIPluginList = typeof ComfyManagerAPIPluginList_ark.infer\nexport const ComfyManagerAPIPluginList_ark = type({\n custom_nodes: type({\n title: type.string.as<KnownComfyPluginTitle>(),\n installed: `'False' | 'True' | 'Update'`,\n }).array(),\n chanel: 'string',\n})\n","/** 🔶 NAMING DISCLAIMER: I call a \"custom node package\" => \"PLUGIN\" */\n\nimport type { Type } from 'arktype'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport type { ComfyManagerAPIFetchPolicy } from 'src/manager/types/ComfyManagerAPIFetchPolicy.ts'\nimport {\n type ComfyManagerAPIModelList,\n ComfyManagerAPIModelList_ark,\n} from 'src/manager/types/ComfyManagerAPIModelList.ts'\nimport {\n type ComfyManagerAPIPluginList,\n ComfyManagerAPIPluginList_ark,\n} from 'src/manager/types/ComfyManagerAPIPluginList.ts'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { logError as toastError, logSuccess as toastSuccess } from 'src/utils/log.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport type { PluginInstallStatus } from 'src/host/Requirements.ts'\n\nexport class ComfyManager {\n constructor(\n public host: {\n getServerHostHTTP: () => string\n fetch: (route: string, init?: RequestInit, p?: { apiPrefix?: boolean }) => Promise<Response>\n },\n ) {\n // void this.updateHostPluginsAndModels()\n }\n\n get registry(): ComfyRegistry {\n return comfyts.registry\n }\n\n fetchPluginsAndModels = async (): Promise<void> => {\n const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()])\n this.pluginList = _pluginList\n this.modelList = _modelList\n }\n\n // -----------\n configureLogging = (mi: boolean): Promise<unknown> => {\n // return this.repository.getModelInfoFinalFilePath(mi)\n return this.fetchGetText(`/manager/terminal?mode=${mi}`)\n }\n\n // utils ------------------------------------------------------------------------------\n getModelInfoFinalFilePath = (mi: ComfyManagerModelInfo): string => {\n return comfyts.registry.getModelInfoFinalFilePath(mi)\n }\n\n waitForHostToBeBackOnline(maxAttempt: 10): Promise<true> {\n return new Promise<true>((yes, no) => {\n let attempt = 0\n let abortCtrl: AbortController\n const interval = setInterval(async () => {\n attempt++\n if (attempt > maxAttempt) {\n console.log(` - failure`)\n clearInterval(interval)\n no()\n }\n if (abortCtrl) abortCtrl.abort()\n abortCtrl = new AbortController()\n try {\n console.log(` - trying...`)\n await this.host.fetch('/', { signal: abortCtrl.signal }, { apiPrefix: false })\n clearInterval(interval)\n yes(true)\n } catch {\n /* empty */\n }\n }, 1000)\n })\n }\n\n // actions ---------------------------------------------------------------------------\n rebootComfyUIAndUpdateHostPluginsAndModelsAfter10Seconds(): Promise<void> {\n // 🔴 bad code\n setTimeout(() => void this.fetchPluginsAndModels(), 10_000)\n return this.restartComfyUI()\n }\n\n /**\n * reboot the ComfyUI process (ComfyUI-Manager).\n *\n * The server dies mid-request, so a DROPPED CONNECTION is the success shape and the only\n * one most callers ever see. A 404 is not: the route is POST from Manager V3 on (verified\n * against V3.41), and a GET there answers 404 while the process keeps running — a caller\n * that treats every failure as \"expected mid-reboot disconnect\" then reports a reboot that\n * never happened. Both verbs are tried so an old and a new Manager both work, and anything\n * that is neither a disconnect nor a 404 throws with what the host actually said.\n */\n restartComfyUI = async (): Promise<void> => {\n const refusals: string[] = []\n for (const method of ['POST', 'GET'] as const) {\n let response: Response\n try {\n response = await this.host.fetch('/manager/reboot', { method })\n } catch {\n return // connection gone: the process is going down, which is what we asked for\n }\n if (response.ok) return\n refusals.push(`${method} → ${response.status}`)\n // only a missing route is worth retrying with the other verb\n if (response.status !== 404) break\n }\n throw new Error(\n `🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(', ')}) — ` +\n `ComfyUI-Manager is not installed there, or its reboot route moved again`,\n )\n }\n\n modelList: Maybe<ComfyManagerAPIModelList> = null\n\n fetchModels = (): Promise<ComfyManagerAPIModelList> => {\n return this.fetchGetJSON('/externalmodel/getlist?mode=cache', ComfyManagerAPIModelList_ark)\n }\n\n fetchLogs = (): Promise<any> => {\n return this.fetchGetJSON<unknown>('/internal/logs')\n }\n\n isModelInstalled = (name: KnownModel_Name): boolean => {\n return this.modelList?.models.some((x) => x.name === name && x.installed === 'True') ?? false\n }\n\n modelsBeeingInstalled = new Set<KnownModel_Name>()\n\n installModel = async (model: ComfyManagerModelInfo): Promise<boolean> => {\n try {\n this.modelsBeeingInstalled.add(model.name)\n await this.fetchPost('/model/install', model)\n this.modelsBeeingInstalled.delete(model.name)\n toastSuccess('Model installed')\n return true\n } catch (exception) {\n console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)\n toastError('Model Installation Failed')\n this.modelsBeeingInstalled.delete(model.name)\n return false\n }\n }\n\n getModelStatus = (modelName: KnownModel_Name): PluginInstallStatus => {\n if (this.modelList == null) return 'unknown'\n const entry = this.modelList?.models.find((x) => x.name === modelName)\n const status = ((): PluginInstallStatus => {\n if (!entry) return 'unknown'\n if (entry?.installed === 'False') return 'not-installed'\n if (entry?.installed === 'True') return 'installed'\n if (entry?.installed === 'Update') return 'update-available'\n return 'error'\n })()\n return status\n }\n\n // PLUGINS (A.K.A. Custom nodes) ----------------------------------------------------------------------------\n /**\n * you need to call `fetchPluginList()` to populate this field\n */\n pluginList: Maybe<ComfyManagerAPIPluginList> = null // hasModel = async (model: ModelInfo) => {\n\n get titlesOfAllInstalledPlugins(): KnownComfyPluginTitle[] {\n return (\n this.pluginList?.custom_nodes //\n .filter((x) => x.installed === 'True')\n .map((x) => x.title) ?? []\n )\n }\n\n isPluginInstalled = (title: KnownComfyPluginTitle): boolean => {\n if (!this.pluginList || !this.pluginList.custom_nodes) return false\n return this.pluginList.custom_nodes.some((x) => x.title === title && x.installed === 'True') ?? false\n }\n\n getPluginStatus = (title: KnownComfyPluginTitle): PluginInstallStatus => {\n if (this.pluginList == null) return 'unknown'\n const entry = this.pluginList?.custom_nodes.find((x) => x.title === title)\n const status = ((): PluginInstallStatus => {\n if (!entry) return 'unknown'\n if (entry?.installed === 'False') return 'not-installed'\n if (entry?.installed === 'True') return 'installed'\n if (entry?.installed === 'Update') return 'update-available'\n return 'error'\n })()\n return status\n }\n\n // --------------------------------------------------------------\n // https://github.com/ltdrdata/ComfyUI-Manager/blob/4649d216b1842aa48b95d3f064c679a1b698e506/js/custom-nodes-downloader.js#L14C25-L14C88\n fetchPlugins = async (\n /** @default: 'cache' */\n mode: ComfyManagerAPIFetchPolicy = 'cache',\n /** @default: true */\n skipUpdate: boolean = true,\n ): Promise<ComfyManagerAPIPluginList> => {\n try {\n const skip_update = skipUpdate ? '&skip_update=true' : ''\n return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark)\n } catch (exception) {\n console.error(`node list retrieval failed: ${exception}`)\n toastError('node list retrieveal failed')\n throw exception\n }\n }\n\n installPlugin = async (model: ComfyManagerPluginInfo): Promise<boolean> => {\n try {\n await this.fetchPost('/customnode/install', model)\n console.log('✅ Custom Node installed')\n toastSuccess('Custom Node installed')\n return true\n } catch (exception) {\n console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)\n toastError('Custom Node Installation Failed')\n return false\n }\n }\n\n // --------------------------------------------------------------\n private fetchPost = async <IN, OUT = unknown>(endpoint: string, body: IN, validator?: Type<OUT>): Promise<OUT> => {\n const response = await this.host.fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`)\n const status = await response.json()\n if (validator) return softValidate(validator, status)\n // wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json\n return status as OUT\n }\n\n private fetchGetJSON = async <OUT = unknown>(endpoint: string, validator?: Type<OUT>): Promise<OUT> => {\n const response = await this.host.fetch(endpoint)\n if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`)\n const jsonResult = await response.json()\n if (validator) return softValidate(validator, jsonResult)\n // wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json\n return jsonResult as OUT\n }\n\n private fetchGetText = async (endopint: string): Promise<string> => {\n const response = await this.host.fetch(endopint)\n const status = await response.text()\n return status\n }\n}\n","import { type } from 'arktype'\nimport type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'\nimport type { MediaImage } from 'src/runner/MediaImage.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\n\nexport type ComfyUploadImageResult = {\n name: ComfyImageName\n subfolder: string\n type: string\n}\n\nexport const ComfyUploadImageResult_ark = type({\n name: type.string.as<ComfyImageName>(),\n subfolder: 'string',\n type: 'string',\n})\n\n/** all those functions are kinda legacy */\nexport class ComfyUploader {\n constructor(public host: ComfyHost) {}\n\n /** upload a blob */\n uploadImage = async (\n //\n img: MediaImage,\n p: {\n type?: Maybe<'input' | 'temp' | 'output'>\n override?: Maybe<boolean>\n subfolder?: string\n },\n ): Promise<ComfyImageName> => {\n const uniqFileName = img.enumName as ComfyImageName\n // console.warn(`[🌁] UPLOAD: ${img.relPath} required as \"${uniqFileName}\"...`)\n\n const expectedFinalName = p.subfolder //\n ? `${p.subfolder}/${uniqFileName}`\n : uniqFileName\n // 2. if image already exists, return it\n if (this.host.schema.hasImage(expectedFinalName)) {\n console.log(`[🌁] UPLOAD: 🩶 \"${img.absPath}\" already exists on current ComfyUI instance`)\n return expectedFinalName as ComfyImageName\n }\n\n // 3. upload\n const form = new FormData()\n form.set('image', img.getAsBlob(), uniqFileName)\n if (p.type) form.set('type', p.type)\n if (p.override ?? true) form.set('override', 'true')\n // const subfolder = p.subfolder ?? 'comfyts-upload'\n if (p.subfolder) form.set('subfolder', p.subfolder)\n const resp = await this.host.fetch('/upload/image', { method: 'POST', body: form })\n const result: ComfyUploadImageResult = softValidate(ComfyUploadImageResult_ark, await resp.json())\n\n // 4. check upload is successfull\n console.log('[🌁] UPLOAD: ✅ got', result)\n if (result.name == null) throw new Error('upload failed')\n\n const finalName = result.subfolder //\n ? (`${result.subfolder}/${result.name}` as ComfyImageName)\n : result.name\n\n if (finalName !== expectedFinalName) {\n console.warn(`[🌁] UPLOAD: ⚠️ expected \"${expectedFinalName}\" but got \"${finalName}\"`)\n } else {\n console.log(`[🌁] UPLOAD: ✅ finalName is \"${finalName}\"`)\n }\n\n // 5. patch the local ComfyUI schema locally\n this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName)\n\n // 6. return the image\n return finalName\n }\n\n /** upload an image present on disk to ComfyUI */\n // ⏸️ upload_FileAtAbsolutePath = async (filePath: AbsolutePath): Promise<ComfyUploadImageResult> => {\n // ⏸️ const mime = asSTRING_orCrash(lookup(filePath))\n // ⏸️ const file = new Blob([readFileSync(filePath)], { type: mime })\n // ⏸️ return await this.upload_Blob(file)\n // ⏸️ }\n\n // ⏸️ /** upload an image from dataURL */\n // ⏸️ upload_dataURL = async (dataURL: string): Promise<ComfyUploadImageResult> => {\n // ⏸️ const mime = dataURL.split(';')[0].split(':')[1]\n // ⏸️ console.log('[⬆️] upload_dataURL', mime)\n // ⏸️ const file = new Blob([Buffer.from(dataURL.split(',')[1], 'base64')], { type: mime })\n // ⏸️ return await this.upload_Blob(file)\n // ⏸️ }\n\n // ⏸️ /** upload an image present on disk to ComfyUI */\n // ⏸️ upload_NativeFile = async (file: File): Promise<ComfyUploadImageResult> => {\n // ⏸️ const blob = new Blob([await file.arrayBuffer()], { type: file.type })\n // ⏸️ return await this.upload_Blob(blob)\n // ⏸️ }\n\n // ⏸️ /** upload an image that can be downloaded form a given URL to ComfyUI */\n // ⏸️ upload_ImageAtURL = async (url: string): Promise<ComfyUploadImageResult> => {\n // ⏸️ const blob: Blob = await this.st.getUrlAsBlob(url)\n // ⏸️ return this.upload_Blob(blob)\n // ⏸️ }\n\n // ⏸️ /** upload a deck asset to ComfyUI */\n // ⏸️ upload_Asset = async (assetName: RelativePath): Promise<ComfyUploadImageResult> => {\n // ⏸️ const absPath = asAbsolutePath(path.join(this.st.rootPath, assetName))\n // ⏸️ return this.st.uploader.upload_FileAtAbsolutePath(absPath)\n // ⏸️ }\n}\n","/** pure url layer for ComfyHost: parse once, render everywhere. No comfyts global. */\n\nexport type ParsedHostBase = {\n scheme: 'http' | 'https'\n host: string\n /** always concrete (defaults 80/443 from the scheme when the url omits it) */\n port: number\n /** '' or '/segment…' with no trailing slash */\n basePath: string\n}\n\n/** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */\nexport function parseHostBase(p: {\n id: string\n url?: string\n host?: string\n port?: number\n https?: boolean\n}): ParsedHostBase {\n const hasLegacy = p.host != null || p.port != null || p.https != null\n if (p.url != null && hasLegacy)\n throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`)\n if (p.url == null) {\n if (p.host == null || p.port == null)\n throw new Error(`host '${p.id}': needs either url, or host AND port (got host=${p.host}, port=${p.port})`)\n return { scheme: p.https ? 'https' : 'http', host: p.host, port: p.port, basePath: '' }\n }\n\n let parsed: URL\n try {\n parsed = new URL(p.url)\n } catch {\n throw new Error(`host '${p.id}': unparseable url '${p.url}'`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')\n throw new Error(`host '${p.id}': url scheme must be http or https, got '${parsed.protocol}' in '${p.url}'`)\n if (parsed.search !== '' || parsed.hash !== '')\n throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`)\n const scheme = parsed.protocol === 'https:' ? 'https' : 'http'\n const port = parsed.port !== '' ? Number(parsed.port) : scheme === 'https' ? 443 : 80\n const basePath = parsed.pathname.replace(/\\/+$/, '')\n return { scheme, host: parsed.hostname, port, basePath }\n}\n\n/** http(s) base, port omitted when it is the scheme default */\nexport function renderHttpBase(p: ParsedHostBase): string {\n return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`\n}\n\n/** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless\n * transports (browser), where the ws client remaps X-API-Key to ?token= */\nexport function renderWsUrl(p: ParsedHostBase): string {\n const scheme = p.scheme === 'https' ? 'wss' : 'ws'\n return `${scheme}://${p.host}${renderPort(p)}${p.basePath}/ws`\n}\n\nfunction renderPort(p: ParsedHostBase): string {\n const schemeDefault = p.scheme === 'https' ? 443 : 80\n return p.port === schemeDefault ? '' : `:${p.port}`\n}\n","// transport-agnostic since 2026-07-31 (architecture item 13): node uses the\n// `ws` package (custom upgrade headers work), browsers the native WebSocket.\n// The `ws` import specifier is a VARIABLE so browser bundlers never chase it.\nimport type { Maybe } from 'src/types/index.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\nimport { logInfo } from 'src/utils/log.ts'\n\ntype Message = string | Uint8Array\n\n/** structural face of both transports (ws package AND browser WebSocket) */\nexport type WsLike = {\n binaryType: string\n onmessage: ((event: WsMessageEvent) => void) | null\n onopen: ((event: unknown) => void) | null\n onclose: ((event: WsCloseEvent) => void) | null\n onerror: ((event: unknown) => void) | null\n send(data: Message): void\n close(): void\n}\n\n/** what both transports deliver with binaryType 'arraybuffer': string or ArrayBuffer in `data` */\nexport type WsMessageEvent = { data: unknown }\nexport type WsCloseEvent = { code: number; reason: string }\n\ntype WsCtor = new (url: string, opts?: { headers?: Record<string, string> }) => WsLike\n\ntype WsTransport = { ctor: WsCtor; supportsHeaders: boolean }\n\nlet transportPromise: Promise<WsTransport> | null = null\n\n/** node: the ws package (headers on the upgrade). browser: native WebSocket. */\nfunction resolveWsTransport(): Promise<WsTransport> {\n transportPromise ??= (async (): Promise<WsTransport> => {\n const specifier = 'ws'\n try {\n // cast: the ws package ctor fits WsCtor structurally; a variable\n // specifier types the import as any, so the shape is stated here\n const mod = (await import(specifier)) as { default: WsCtor }\n return { ctor: mod.default, supportsHeaders: true }\n } catch {\n const native = (globalThis as { WebSocket?: WsCtor }).WebSocket\n if (native != null) return { ctor: native, supportsHeaders: false }\n throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`)\n }\n })()\n return transportPromise\n}\n\ntype WsDebugMessage = {\n type: 'info' | 'error'\n timestamp: number\n message: string\n}\n\nexport class ResilientWebSocketClient {\n private url: string\n private currentWS?: Maybe<WsLike>\n private messageBuffer: Message[] = []\n\n isOpen: boolean = false\n debugMessages: WsDebugMessage[] = []\n\n private addInfo(msg: string): void {\n this.debugMessages.push({ type: 'info', timestamp: Date.now(), message: msg })\n logInfo(`[🧦] WS: ${msg}`)\n }\n\n private addError(err: string): void {\n this.debugMessages.push({ type: 'error', timestamp: Date.now(), message: err })\n console.error('[🧦] WS:', err)\n }\n\n constructor(\n public options: {\n url: () => string\n /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect.\n * On a headerless transport (browser) X-API-Key rides `?token=` instead\n * (the probed Comfy Cloud contract); other headers throw loud. */\n headers?: () => Record<string, string>\n onMessage: (event: WsMessageEvent) => void\n onConnectOrReconnect: () => void\n onClose: () => void\n /** transport unrecoverable (no ws package AND no global WebSocket, or ctor threw):\n * reported here ONCE, the client goes permanently closed — never a retry storm */\n onTransportDead?: (error: unknown) => void\n /**\n * the socket closed WITHOUT ever opening: nothing is listening there.\n * That is a definitive answer, not a blip, so it is reported instead of\n * retried and the caller decides. The 2s retry loop exists to heal an\n * ESTABLISHED session; spending it on a refused connect only makes every\n * waiter sit for the full connect deadline. No callback = retry as before.\n */\n onFirstConnectFailed?: (error: unknown) => void\n },\n ) {\n this.url = options.url()\n void this.connect()\n }\n\n /** an established session heals by retrying; a first connect that never opened does not */\n private hasEverOpened: boolean = false\n\n private reconnectTimeout?: Maybe<ReturnType<typeof setTimeout>>\n private permanentlyClosed: boolean = false\n\n /** close and stop reconnecting (lets a script exit cleanly) */\n disconnectPermanently(): void {\n this.permanentlyClosed = true\n if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout)\n this.currentWS?.close()\n this.currentWS = null\n this.isOpen = false\n }\n\n /** headerless transports carry the api key as ?token= — everything else is refused loud */\n private headerlessUrl(headers: Record<string, string>): string {\n const rest = { ...headers }\n const apiKey = rest['X-API-Key']\n delete rest['X-API-Key']\n const extra = Object.keys(rest)\n if (extra.length > 0)\n throw new Error(\n `custom ws headers (${extra.join(', ')}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`,\n )\n if (apiKey == null) return this.url\n return this.url + (this.url.includes('?') ? '&' : '?') + 'token=' + encodeURIComponent(apiKey)\n }\n\n private async connect(): Promise<void> {\n this.isOpen = false\n const prevWS = this.currentWS\n\n // cleanup a possible re-connection timeout for an other url\n if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout)\n\n this.currentWS = null\n if (prevWS) {\n this.addInfo('Previous WebSocket discarded')\n prevWS.close()\n }\n\n let ws: WsLike\n try {\n const transport = await resolveWsTransport()\n if (this.permanentlyClosed) return // closed while the transport resolved\n const headers = this.options.headers?.() ?? {}\n ws = transport.supportsHeaders\n ? new transport.ctor(this.url, { headers })\n : new transport.ctor(this.headerlessUrl(headers))\n } catch (e) {\n // connect() runs void'd (ctor + reconnect timer): a rethrow here would be\n // an unhandled rejection, so the failure reports through onTransportDead\n this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`)\n this.permanentlyClosed = true\n this.options.onTransportDead?.(e)\n return\n }\n ws.binaryType = 'arraybuffer'\n\n this.currentWS = ws\n\n ws.onmessage = (event: WsMessageEvent): void => {\n this.options.onMessage(event)\n }\n\n ws.onopen = (): void => {\n if (ws !== this.currentWS) return\n this.addInfo('✅ WebSocket connected to ' + this.url)\n this.hasEverOpened = true\n this.isOpen = true\n this.options.onConnectOrReconnect()\n this.flushMessageBuffer()\n }\n\n ws.onclose = (event: WsCloseEvent): void => {\n if (ws !== this.currentWS) return\n this.isOpen = false\n this.options.onClose()\n if (this.permanentlyClosed) return\n this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`)\n // never opened = nothing is listening: report, do not retry (see the option)\n if (!this.hasEverOpened && this.options.onFirstConnectFailed != null) {\n this.permanentlyClosed = true\n this.options.onFirstConnectFailed(\n new Error(`connection refused (code=${event.code}${event.reason === '' ? '' : `, ${event.reason}`})`),\n )\n return\n }\n this.addInfo('⏱️ reconnecting in 2 seconds...')\n this.reconnectTimeout = setTimeout(() => void this.connect(), 2000)\n }\n\n ws.onerror = (event: unknown): void => {\n if (ws !== this.currentWS) return\n this.addError(`WebSocket ERROR` + JSON.stringify(event))\n console.error({ event })\n }\n }\n\n public send(message: Message): void {\n if (this.isOpen) {\n this.currentWS?.send(message)\n } else {\n this.messageBuffer.push(message)\n }\n }\n\n private flushMessageBuffer(): void {\n while (this.messageBuffer.length > 0) {\n const message = bang(this.messageBuffer.shift())\n this.currentWS?.send(message)\n }\n }\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('&nbsp;', ' ')\n .replaceAll('&amp;', '&')\n .replaceAll('&lt;', '<')\n .replaceAll('&gt;', '>')\n .replaceAll('&quot;', '\"')\n .replaceAll('&#39;', \"'\")\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","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\nimport type { ComfyExecution } from 'src/runner/ComfyExecution.ts'\nimport type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport { parseWorkflowJson } from 'src/litegraph/normalizeWorkflow.ts'\nimport { parseBinaryWsFrame } from 'src/runner/wsBinaryFrame.ts'\nimport { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'\nimport { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport {\n type ComfyStatusData,\n type LogEntry,\n type PromptID,\n type PendingWsItem,\n type PromptRelated_WsMsg,\n type WsMsg,\n WsMsg_ark,\n WsMsgLogsData_ark,\n} from 'src/runner/ComfyWsApi.ts'\nimport { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport { type ComfySchemaJSON, ComfySchemaJSON_ark } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport type { EmbeddingName } from 'src/sdk-generator/comfyui-types.ts'\nimport { type AbsolutePath, type Maybe, type number_Timestamp, type Tagged } from 'src/types/index.ts'\nimport { exhaust } from 'src/utils/exhaust.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\nimport { readableStringify } from 'src/utils/stringifyReadable.ts'\nimport { logError as toastError, logInfo } from 'src/utils/log.ts'\nimport type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'\nimport { ComfyManager } from 'src/host/ComfyManager.ts'\nimport { ComfyUploader } from 'src/host/ComfyUploader.ts'\nimport { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'\nimport type { Requirements } from 'src/host/Requirements.ts'\nimport { ResilientWebSocketClient, type WsMessageEvent } from 'src/host/ResilientWebsocket.ts'\nimport { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'\nimport type { VarsSpec } from 'src/vars/ComfyVars.ts'\n\nexport type ComfyHostID = Tagged<string, { HostID: true }>\nexport type ComfyHostData = {\n id: string\n\n /** full base url as pasted from a provider (https://cloud.comfy.org,\n * https://xxx.modal.run, http://192.168.1.5:8188/comfy).\n * Exactly ONE of url OR the legacy host+port (+https?) spelling. */\n url?: string\n host?: string\n port?: number\n https?: boolean\n\n /** sent as X-API-Key on every request AND the ws upgrade.\n * NEVER persist the value: read it from an env var (e.g. COMFY_CLOUD_API_KEY) */\n apiKey?: string\n /** default true. false = never write sdk.d.ts to .comfy-ts/hosts/<id>/ —\n * schema updates stay in-memory. The comfy-cloud example sets false: its sdk\n * home is the COMMITTED examples/comfy-cloud/sdk.d.ts (gen:sdk:cloud), and a\n * second copy under .comfy-ts/hosts/ would double-declare the globals. */\n sdkAutoWrite?: boolean\n /** extra headers merged into every request + the ws upgrade (Modal-style auth pairs) */\n headers?: Record<string, string>\n\n // for extra features using path manipulation\n installType?: ComfyInstallType\n\n // misc\n onWsMessageAny?: (e: WsMessageEvent) => void\n onWsMessageArrayBuffer?: (e: ArrayBuffer) => void\n onWsMessageJSON?: (e: WsMsg) => void\n}\n\nexport type ConnectOptions = {\n /** 'auto' (default): reuse cache when fresh · 'refresh': always fetch · 'cache': never fetch */\n schema?: 'auto' | 'refresh' | 'cache'\n /** max cache age for 'auto' (default 24h) */\n maxAgeMs?: number\n /**\n * deadline for the FIRST connect, default 30s. 0 or Infinity waits forever.\n * A refused TCP connection is a ws CLOSE, not a dead transport, so without a\n * deadline `connect()` sat in the 2s reconnect loop and never settled: scripts\n * hung with no error and `comfy-ts serve` wedged the module behind its mutex.\n * Reconnects AFTER a successful connect are untouched and still retry forever.\n */\n timeoutMs?: number\n}\n\n/** the host never came up within ConnectOptions.timeoutMs */\nexport class ComfyHostUnreachableError extends Error {\n /** name, not instanceof: the cli bundle and dist/index.js each define this class */\n override readonly name = 'ComfyHostUnreachableError'\n}\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 30_000\n\n// biome-ignore format: misc\ntype SchemaUpdateResult = Maybe<{ type: 'success' } | { type: 'error'; error: unknown }>\n\ntype ServerLog = {\n at: string\n content: string\n id: number\n}\n\n/** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):\n * 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive\n * (or plain rate limiting on non-cloud hosts). The key value never appears here. */\nexport class ComfyHostAuthError extends Error {\n constructor(\n public code: 401 | 402 | 429,\n public hostId: string,\n message: string,\n ) {\n super(message)\n this.name = 'ComfyHostAuthError'\n }\n}\n\nexport class ComfyHost<ID extends string = string> {\n // ----- misc paths where we'll store host-related files -----\n cacheFolder: AbsolutePath\n\n comfyJSONPath: AbsolutePath\n embeddingsPath: AbsolutePath\n sdkDTSPath: AbsolutePath\n\n /** the schema instance with all methods to interract with the host schema */\n schema: ComfySchema\n uploader = new ComfyUploader(this)\n\n /** parsed ONCE from data (url-first or legacy host/port/https) — the url ground truth */\n readonly base: ParsedHostBase\n\n constructor(public data: ComfyHostData & { id: ID }) {\n this.base = parseHostBase(this.data)\n\n /** folder where file related to the host config will be cached */\n this.cacheFolder = comfyts.resolveFromHosts(this.data.id)\n\n // create the folder if it does not exist\n const storage = getComfyStorage()\n if (!storage.exists(this.cacheFolder)) {\n console.log('🟢 creating folder', this.cacheFolder)\n storage.mkdirp(this.cacheFolder)\n }\n\n this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`)\n this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`)\n this.sdkDTSPath = comfyts.resolve(this.cacheFolder, `sdk.d.ts`)\n\n /** create a new schema */\n this.schema = new ComfySchema({ embeddings: [], spec: {} })\n }\n\n /** helper to check if your host have whatever it needs to run your workflow */\n matchRequirements = (requirements: Requirements[]): boolean => {\n const repo = comfyts.registry\n for (const req of requirements) {\n if (req.optional) continue\n if (req.type === 'customNodesByNodeKey') {\n const plugins: ComfyManagerPluginInfo[] = repo.plugins_byNodeKey.get(req.nodeName) ?? []\n if (!plugins.find((i) => this.manager.isPluginInstalled(i.title))) {\n // console.log(`[❌ A] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'customNodesByTitle') {\n const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byTitle.get(req.title)\n if (plugin == null) continue\n if (!this.manager.isPluginInstalled(plugin.title)) {\n // console.log(`[❌ B] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'customNodesByURI') {\n const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byFile.get(req.uri)\n if (plugin == null) continue\n if (!this.manager.isPluginInstalled(plugin.title)) {\n // console.log(`[❌ C] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'modelInManager') {\n if (!this.manager.isModelInstalled(req.modelName)) {\n // console.log(`[❌ D] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else {\n // exhaust(req.type)\n }\n }\n return true\n }\n\n // ----- Rotating srever logs -----\n\n /** server sent by the comfy-manager plugin */\n readonly serverLogs: ServerLog[] = []\n\n /** if true, request ComfyUI to forward logs */\n private wantLog: boolean = true\n\n /** maximum amount of logs to keep in memory */\n readonly maxLogs: number = 200\n\n /** last log id received */\n private logId: number = 0\n\n /** toggle server log forwarding so comfy-ts can */\n toggleServerLogs = (): Promise<unknown> => {\n this.wantLog = !this.wantLog\n return this.manager.configureLogging(this.wantLog)\n }\n\n addLog = (content: string): void => {\n if (this.serverLogs.length > this.maxLogs) this.serverLogs.shift()\n const d = new Date().toISOString().slice(11, 19)\n this.serverLogs.push({ content, id: this.logId++, at: d })\n }\n\n // ----- Misc helpers if you work with a local Comfy -----\n\n /** root install of ComfyUI on the host filesystem */\n get absolutePathToComfyUI(): Maybe<string> {\n return this.data.installType?.absolutePathToComfyRoot\n }\n\n // ----- Misc helpers if you work with a local Comfy -----\n\n get manager(): ComfyManager {\n const value = new ComfyManager(this)\n Object.defineProperty(this, 'manager', { value })\n return value\n }\n\n // INIT -----------------------------------------------------------------------------\n installCustomNodeByFile = async (customNodeFile: KnownComfyPluginURL): Promise<boolean> => {\n const manager = comfyts.registry\n const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byFile.get(customNodeFile)\n if (plugin == null) throw new Error(`Unknown custom node for file: \"${customNodeFile}\"`)\n return this.manager.installPlugin(plugin)\n }\n\n installCustomNodeByTitle = async (customNodeTitle: KnownComfyPluginTitle): Promise<boolean> => {\n const manager = comfyts.registry\n const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byTitle.get(customNodeTitle)\n if (plugin == null) throw new Error(`Unknown custom node for title: \"${customNodeTitle}\"`)\n return this.manager.installPlugin(plugin)\n }\n\n installCustomNode = async (customNode: ComfyManagerPluginInfo): Promise<boolean> => {\n return this.manager.installPlugin(customNode)\n }\n\n // URLS -----------------------------------------------------------------------------\n getServerHostHTTP(): string {\n return renderHttpBase(this.base)\n }\n\n getWSUrl = (): string => {\n return renderWsUrl(this.base)\n }\n\n // HTTP -----------------------------------------------------------------------------\n /** extra headers + X-API-Key, for every http request AND the ws upgrade */\n private authHeaders(): Record<string, string> {\n const out: Record<string, string> = {}\n if (this.data.headers != null) Object.assign(out, this.data.headers)\n if (this.data.apiKey != null) out['X-API-Key'] = this.data.apiKey\n return out\n }\n\n /** remembered /api-prefix verdict for this host; null until first probed */\n private _apiPrefix: boolean | null = null\n\n /**\n * the ONE http path to this host: joins basePath, injects X-API-Key + extra\n * headers, prefers `/api<route>` (required by Comfy Cloud, canonical since\n * custom nodes hijack bare routes) with a bare-route fallback on 404/405 for\n * old local servers (winner memoized; the other spelling is still retried\n * when the memo misses — mixed servers exist, e.g. /internal is bare-only).\n * Auth failures throw a typed ComfyHostAuthError instead of generic noise.\n * `p.apiPrefix: false` opts a route out of the prefix game entirely.\n */\n fetch = async (route: string, init: RequestInit = {}, p: { apiPrefix?: boolean } = {}): Promise<Response> => {\n const base = this.getServerHostHTTP()\n const headers = new Headers(init.headers)\n for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v)\n const send = (prefixed: boolean): Promise<Response> =>\n fetch(`${base}${prefixed ? '/api' : ''}${route}`, { ...init, headers })\n const missed = (res: Response): boolean => res.status === 404 || res.status === 405\n\n let res: Response\n if (p.apiPrefix === false) {\n res = await send(false)\n } else if (this._apiPrefix != null) {\n res = await send(this._apiPrefix)\n if (missed(res)) {\n const alt = await send(!this._apiPrefix)\n if (!missed(alt)) res = alt\n }\n } else {\n res = await send(true)\n if (missed(res)) {\n const bare = await send(false)\n if (!missed(bare)) {\n this._apiPrefix = false\n res = bare\n }\n } else {\n this._apiPrefix = true\n }\n }\n this.throwOnAuthError(res, route)\n return res\n }\n\n /**\n * binary download path: Comfy Cloud answers `/api/view` with a 302 to a\n * temporary signed URL. fetch only auto-strips Authorization/cookies on\n * cross-origin redirects — a custom X-API-Key WOULD be forwarded to the\n * storage host — so we follow the Location manually with a CLEAN fetch.\n */\n fetchFile = async (route: string): Promise<Response> => {\n const res = await this.fetch(route, { redirect: 'manual' })\n if (res.status >= 300 && res.status < 400) {\n const location = res.headers.get('location')\n if (location == null)\n throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`)\n void res.body?.cancel()\n return fetch(new URL(location, this.getServerHostHTTP()))\n }\n return res\n }\n\n private throwOnAuthError(res: Response, route: string): void {\n if (res.status === 401)\n throw new ComfyHostAuthError(\n 401,\n this.data.id,\n this.data.apiKey != null\n ? `host '${this.data.id}': 401 on ${route} — API key invalid or expired`\n : `host '${this.data.id}': 401 on ${route} — host requires authentication, no apiKey configured`,\n )\n if (res.status === 402)\n throw new ComfyHostAuthError(\n 402,\n this.data.id,\n `host '${this.data.id}': 402 on ${route} — insufficient credits`,\n )\n if (res.status === 429)\n throw new ComfyHostAuthError(\n 429,\n this.data.id,\n `host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`,\n )\n }\n\n // LOGS -----------------------------------------------------------------------------\n schemaRetrievalLogs: string[] = []\n\n resetLog = (): void => {\n this.schemaRetrievalLogs.splice(0, this.schemaRetrievalLogs.length)\n }\n\n // STARTING -----------------------------------------------------------------------------\n get isConnected(): boolean {\n return this.ws?.isOpen ?? false\n }\n\n workflow = (p: { id?: string } = {}): ComfyWorkflow<ID> => {\n return new ComfyWorkflow(this, {\n metadata: {},\n id: p.id ? asComfyWorkflowID(p.id) : undefined,\n })\n }\n\n /**\n * define a re-runnable workflow: `build` re-executes with the current var\n * values on every run(). The standard contract for tweak & re-run drivers\n * (scripts, the TUI).\n */\n defineWorkflow = <V extends VarsSpec>(spec: DefineWorkflowSpec<ID, V>): DefinedWorkflow<ID, V> => {\n return new DefinedWorkflow(this, spec)\n }\n\n /**\n * import a workflow.json (litegraph format) as a live, editable workflow.\n * Accepts unknown: the JSON is ark-validated + normalized (parseWorkflowJson)\n * before conversion — invalid documents throw WorkflowNormalizeError.\n */\n importWorkflowJson = (json: unknown, p: { id?: string } = {}): ComfyWorkflow<ID> => {\n const canonical = parseWorkflowJson(json)\n const apiJson = convertLiteGraphToPrompt(this.schema, canonical)\n return this.importApiJson(apiJson, p)\n }\n\n /** import an api.json (ComfyUI prompt format) as a live, editable workflow */\n importApiJson = (json: ComfyApiJson, p: { id?: string } = {}): ComfyWorkflow<ID> => {\n const wf = new ComfyWorkflow(this, {\n apiJson: json,\n metadata: {},\n id: p.id ? asComfyWorkflowID(p.id) : undefined,\n })\n wf.onUpdate(null, wf.data) // hydrate ComfyNode instances from the json\n return wf\n }\n\n private _ready: Promise<void> | null = null\n private _readyResolve: (() => void) | null = null\n private _readyReject: ((e: unknown) => void) | null = null\n private _schemaStrategy: NonNullable<ConnectOptions['schema']> = 'auto'\n private _schemaMaxAgeMs: number = 24 * 3600_000\n\n /**\n * open the websocket; resolves once connected AND the schema is loaded.\n * Schema strategy:\n * - 'auto' (default): reuse .comfy-ts/ cache when younger than maxAgeMs — fast starts\n * - 'refresh': always fetch object_info + regen the sdk\n * - 'cache': never fetch (throws when no cache exists)\n */\n connect = (p: ConnectOptions = {}): Promise<void> => {\n if (this._ready == null) {\n this._schemaStrategy = p.schema ?? 'auto'\n this._schemaMaxAgeMs = p.maxAgeMs ?? 24 * 3600_000\n this._ready = new Promise<void>((res, rej) => {\n this._readyResolve = res\n this._readyReject = rej\n })\n const timeoutMs = p.timeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS\n if (timeoutMs > 0 && Number.isFinite(timeoutMs)) {\n this._connectTimer = setTimeout(() => {\n this.markFailed(\n new ComfyHostUnreachableError(\n `host '${this.data.id}' did not come up within ${timeoutMs}ms at ${this.getWSUrl()} — is ComfyUI running there ?`,\n ),\n )\n }, timeoutMs)\n this._connectTimer.unref?.()\n }\n this.initWebsocket()\n }\n return this._ready\n }\n\n private _connectTimer: Maybe<ReturnType<typeof setTimeout>> = null\n private clearConnectTimer(): void {\n if (this._connectTimer != null) clearTimeout(this._connectTimer)\n this._connectTimer = null\n }\n\n /** close the websocket (e.g. to let a script exit) */\n disconnect = (): void => {\n this.clearConnectTimer()\n this.ws?.disconnectPermanently()\n this.ws = null\n this._ready = null\n this._readyResolve = null\n this._readyReject = null\n }\n\n private markReady(): void {\n this.clearConnectTimer()\n this._readyResolve?.()\n this._readyResolve = null\n this._readyReject = null\n }\n\n private markFailed(error: unknown): void {\n this.clearConnectTimer()\n const reject = this._readyReject\n // no pending connect = this is a RECONNECT failing on an already-live host.\n // Its retry loop is the resilience; never tear that down.\n if (reject == null) return\n this._readyResolve = null\n this._readyReject = null\n // a failed connect stays RETRYABLE: keeping the rejected promise on the\n // instance made every later connect() replay the same stale error, so a host\n // that came back was unreachable for the life of the process\n this._ready = null\n // nobody is waiting anymore: stop the 2s retry loop instead of leaking it\n this.ws?.disconnectPermanently()\n this.ws = null\n reject(error)\n }\n\n private async writeSDKToDisk(): Promise<void> {\n if (this.data.sdkAutoWrite === false) return\n const storage = getComfyStorage()\n const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })\n // skip the 4MB write when nothing changed (fast re-connects)\n if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return\n storage.writeText(this.sdkDTSPath, comfySchemaTs)\n }\n\n private shouldUseSchemaCache(): boolean {\n if (this._schemaStrategy === 'refresh') return false\n const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath)\n if (this._schemaStrategy === 'cache') {\n if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)\n return true\n }\n if (mtimeMs == null) return false\n return Date.now() - mtimeMs < this._schemaMaxAgeMs\n }\n\n // WEBSCKET -----------------------------------------------------------------------------\n /**\n * will be created only after we've loaded cnfig file\n * so we don't attempt to connect to some default server\n * */\n ws: Maybe<ResilientWebSocketClient> = null\n\n /** resolves once the server assigned us a session id (first ws 'status' message) */\n private _sessionResolve: (() => void) | null = null\n private waitForSession(timeoutMs: number = 5000): Promise<void> {\n if (this.comfySessionId !== 'temp') return Promise.resolve()\n return new Promise<void>((res) => {\n this._sessionResolve = res\n // some setups never send a sid — proceed after the timeout, loudly\n setTimeout(() => {\n if (this._sessionResolve != null) {\n console.error(\n `🔴 no session id from ${this.data.id} after ${timeoutMs}ms — executions may not route back`,\n )\n this._sessionResolve = null\n res()\n }\n }, timeoutMs).unref?.()\n })\n }\n\n private initWebsocket(): ResilientWebSocketClient {\n logInfo(`[👢] WEBSOCKET: starting client to ComfyUI host ${this.data.id}`)\n this.ws = new ResilientWebSocketClient({\n onConnectOrReconnect: async (): Promise<void> => {\n logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`)\n if (this.shouldUseSchemaCache()) {\n try {\n await this.loadSchemaFromCache()\n // the server routes execution events by client_id: without the\n // session id from the first 'status' message, prompts we POST\n // would report to nobody. The slow fetch path masked this race.\n await this.waitForSession()\n this.markReady()\n return\n } catch (error) {\n console.error(`🔴 schema cache load failed, falling back to fetch`, extractErrorMessage(error))\n }\n }\n await this.fetchAndUpdateSchema()\n await this.waitForSession()\n this.markReady()\n },\n onMessage: (e: WsMessageEvent): void => this.onMessage(e),\n url: () => this.getWSUrl(),\n // auth rides the upgrade headers; headerless transports (browser)\n // remap X-API-Key to ?token= inside the ws client\n headers: () => this.authHeaders(),\n onTransportDead: (e): void => this.markFailed(e),\n // nothing listening: answer NOW instead of making every caller wait out\n // the deadline. markFailed resets _ready, so the next connect() retries\n // and a host that comes back is reachable again\n onFirstConnectFailed: (e): void =>\n this.markFailed(\n new ComfyHostUnreachableError(\n `host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`,\n ),\n ),\n onClose: (): void => {\n logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)\n },\n })\n return this.ws\n }\n\n _isUpdatingSchema: boolean = false\n get isUpdatingSchema(): boolean {\n return this._isUpdatingSchema\n }\n set isUpdatingSchema(v: boolean) {\n this._isUpdatingSchema = v\n }\n\n schemaUpdateResult: SchemaUpdateResult = null\n\n private _schemaFromCache: Promise<void> | null = null\n\n /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).\n * idempotent like connect(): N co-imported modules parse the ~4MB cache once.\n * A MISSING cache degrades LOUDLY to the base types instead of failing the\n * module import (a fresh consumer project has no cache yet — the bundled\n * examples must still open in the TUI; run() fetches the real schema through\n * connect() anyway). Not memoized in that case, so a later gen/connect retries. */\n loadSchemaFromCache(): Promise<void> {\n if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {\n toastError(\n `no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \\`comfy-ts gen --id ${this.data.id} --host <url>\\` or connect() once to create it`,\n )\n return Promise.resolve()\n }\n this._schemaFromCache ??= (async (): Promise<void> => {\n const object_info_json = comfyts.readJSON_<ComfySchemaJSON>(this.comfyJSONPath)\n const embeddings_json = comfyts.readJSON_<string[]>(this.embeddingsPath, [])\n\n // update schema\n this.schema.update({ spec: object_info_json, embeddings: embeddings_json })\n this.schema.RUN_BASIC_CHECKS()\n\n // the on-disk sdk was generated from this same cache — only write when missing\n if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk()\n })().catch((e: unknown) => {\n this._schemaFromCache = null // a missing cache must stay retryable (e.g. after gen:sdk)\n throw e\n })\n return this._schemaFromCache\n }\n\n /** POST a JSON route through host.fetch (/api preferred, bare fallback) */\n private postJSON_ = async (route: string, body: unknown): Promise<void> => {\n const res = await this.fetch(route, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`)\n }\n\n /** drop every PENDING prompt from the server queue (the running one keeps going) */\n clearQueue = (): Promise<void> => {\n return this.postJSON_('/queue', { clear: true })\n }\n\n /** interrupt the CURRENTLY RUNNING prompt */\n interrupt = (): Promise<void> => {\n return this.postJSON_('/interrupt', {})\n }\n\n // HISTORY SCRUB (architecture.md item 14) -------------------------------------------\n // deletes the server-side history ENTRY (workflow JSON, prompts, output\n // filenames) — never files: the ephemeral tier creates none to begin with\n\n /** delete ONE prompt's server history entry */\n deleteHistory = (promptId: string): Promise<void> => {\n return this.postJSON_('/history', { delete: [promptId] })\n }\n\n /** wipe the server's WHOLE prompt history (every user of that server) */\n clearHistory = (): Promise<void> => {\n return this.postJSON_('/history', { clear: true })\n }\n\n // SERVER LOGS ----------------------------------------------------------------------\n // /internal routes are served bare (no /api prefix, no custom-node hijacks)\n\n /** the server's recent console buffer (entries are write CHUNKS, not lines) */\n fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {\n const res = await this.fetch('/internal/logs/raw', {}, { apiPrefix: false })\n if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`)\n const json: unknown = await res.json()\n // wire tolerance (agent/coding.md cast #4): soft-validate, log, still cast\n const checked = WsMsgLogsData_ark(json)\n if (checked instanceof type.errors) {\n console.log(`[🔴] /!\\\\ /internal/logs/raw payload does not match schema.`)\n printArkResultInConsole(checked)\n }\n return json as { entries: LogEntry[] }\n }\n\n /** (un)subscribe THIS session to ws 'logs' messages — per-sid server state,\n * must be re-sent after every reconnect (see onSession) */\n subscribeLogs = async (p: { enabled: boolean; clientId: string }): Promise<void> => {\n const res = await this.fetch(\n '/internal/logs/subscribe',\n {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ enabled: p.enabled, clientId: p.clientId }),\n },\n { apiPrefix: false },\n )\n if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`)\n }\n\n /** GET a JSON route through host.fetch (/api preferred, bare fallback) */\n private fetchJSON_ = async <T>(route: string): Promise<T> => {\n const base = this.getServerHostHTTP()\n const res = await this.fetch(route)\n if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`)\n const contentType = res.headers.get('content-type') ?? ''\n if (!contentType.includes('json'))\n throw new Error(`GET ${route} on ${base} answered '${contentType || 'no content-type'}' instead of json`)\n return (await res.json()) as T\n }\n\n /** retrieve the comfy spec from the schema*/\n fetchAndUpdateSchema = async (): Promise<void> => {\n try {\n this.isUpdatingSchema = true\n // 1 ------------------------------------\n // download object_info (prefer /api/*: custom nodes hijack bare routes,\n // e.g. lora-manager serves HTML at /embeddings)\n const object_info_json = await this.fetchJSON_<{ [key: string]: ComfySchemaJSON[string] }>('/object_info')\n const object_info_str = readableStringify(object_info_json, 4)\n getComfyStorage().writeText(this.comfyJSONPath, object_info_str)\n // use ark to check if payload match the type, and display errors if not\n const res = ComfySchemaJSON_ark(object_info_json)\n if (res instanceof type.errors) {\n printArkResultInConsole(res)\n }\n\n // 2 ------------------------------------\n // download embeddings\n const embeddings_json = await this.fetchJSON_<EmbeddingName[]>('/embeddings').catch(\n () => [] as EmbeddingName[],\n )\n getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json))\n\n // 3 ------------------------------------\n // update schema\n this.schema.update({ spec: object_info_json, embeddings: embeddings_json })\n this.schema.RUN_BASIC_CHECKS()\n\n // 3 ------------------------------------\n // regen sdk\n await this.writeSDKToDisk()\n this.isUpdatingSchema = false\n this.schemaUpdateResult = { type: 'success' }\n } catch (error) {\n this.isUpdatingSchema = false\n this.schemaUpdateResult = { type: 'error', error: error }\n\n console.error(error)\n console.error('🔴 FAILURE TO GENERATE the typed sdk', extractErrorMessage(error))\n\n const schemaExists = getComfyStorage().exists(this.sdkDTSPath)\n if (!schemaExists) await this.writeSDKToDisk()\n this.markFailed(error)\n } finally {\n this.isUpdatingSchema = false\n }\n }\n\n /** executions we started */\n executions: Map<PromptID, ComfyExecution> = new Map()\n\n /** buffer in case we receive packets out of order */\n _pendingMsgs = new Map<PromptID, PendingWsItem[]>()\n\n /** the active prompt currently running on this host */\n private activePromptID: PromptID | null = null\n\n /** method to either execute or buffer the incoming message */\n routeOrBuffer(prompt_id: PromptID, msg: PromptRelated_WsMsg): void {\n this.activePromptID = prompt_id\n const prompt = this.executions.get(prompt_id)\n\n // case 1. no prompt yet => just store the messages\n if (prompt == null) {\n const msgs = this._pendingMsgs.get(prompt_id)\n if (msgs) msgs.push(msg)\n else this._pendingMsgs.set(prompt_id, [msg])\n return\n }\n // case 2. prompt exists => send the messages\n prompt.onPromptRelatedMessage(msg)\n }\n\n /** the latent image beeing generated, in case you want to display it */\n latentPreview: Maybe<{\n promptID: Maybe<PromptID>\n receivedAt: number_Timestamp\n blob: Blob\n url: string\n }> = null\n\n /** byte-level latent-preview hook (e.g. TUI live preview panel) */\n onLatentPreview: Maybe<(p: { bytes: Uint8Array; mime: string; promptID: Maybe<PromptID> }) => void> = null\n\n /** a node's live display text, as it produces it (`PromptServer.send_progress_text`) */\n onProgressText: Maybe<(p: { nodeId: string; text: string; promptID: Maybe<PromptID> }) => void> = null\n\n /** fires on every ws 'status' message (queue length lives there) */\n onStatus: Maybe<(p: { queueRemaining: number }) => void> = null\n\n /** fires when the server assigns a NEW session id (first connect AND every\n * reconnect — per-sid server state like log subscriptions must be redone) */\n onSession: Maybe<(sid: string) => void> = null\n\n /** fires on ws 'logs' messages (server console stream, see subscribeLogs) */\n onLogs: Maybe<(p: { entries: LogEntry[] }) => void> = null\n\n /** the session assigned to us by the server */\n comfySessionId: string = 'temp' /** send by ComfyUI server */\n\n /** binary frame types we already complained about (one log per type, no spam) */\n private _unknownBinaryFrameTypes = new Set<number>()\n\n /** handy to keep around */\n status: ComfyStatusData['status'] | null = null\n\n /** last time ANY ws message arrived — proof-of-life for the TUI probe: a\n * busy single-threaded ComfyUI stalls NEW connects while established\n * sockets keep streaming (a half-open socket receives nothing, so this\n * never revives one) */\n lastWsMessageAt: number | null = null\n\n onMessage(e: WsMessageEvent): void {\n this.lastWsMessageAt = Date.now()\n if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)\n if (e.data instanceof ArrayBuffer) {\n const frame = parseBinaryWsFrame(e.data)\n if (frame.kind === 'preview') {\n // OUTPUT, not preview: while a SaveImageWebsocket node executes,\n // each preview-kind frame IS one output image (frames follow their\n // 'executing' message on the same socket — architecture.md item 14)\n const activeExec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null\n if (activeExec?.wsOutputNodeExecuting) {\n activeExec.onWsImageOutput({ bytes: frame.bytes, mime: frame.mime })\n return\n }\n // pre-registration window: ws messages\n // can beat the POST /prompt response, and an ephemeral output frame\n // in that window would be the ONLY copy of the image — buffer it IN\n // ORDER with the json messages; ComfyExecution.onCreate replays the\n // queue and decides output-vs-latent from the state at replay time\n if (this.activePromptID != null) {\n const pending = this._pendingMsgs.get(this.activePromptID)\n if (pending != null) pending.push({ type: 'binary_preview_frame', bytes: frame.bytes, mime: frame.mime })\n }\n // type 1 AND the cloud's type 4 (preview + metadata) feed the same hook.\n // The object url REGISTRY holds a strong ref to its blob until it is\n // revoked (node and browsers alike), and a sampler emits one frame per\n // step: revoke the outgoing one or a long session retains every latent\n if (this.latentPreview != null) URL.revokeObjectURL(this.latentPreview.url)\n const imageBlob = new Blob([frame.bytes], { type: frame.mime })\n this.latentPreview = {\n blob: imageBlob,\n url: URL.createObjectURL(imageBlob),\n receivedAt: Date.now() as number_Timestamp,\n promptID: this.activePromptID,\n }\n this.onLatentPreview?.({ bytes: frame.bytes, mime: frame.mime, promptID: this.activePromptID })\n } else if (frame.kind === 'unknown' && !this._unknownBinaryFrameTypes.has(frame.eventType)) {\n // wire tolerance: log once per type, never throw (a throw per sampling\n // step is what the first live cloud run did on type 4)\n this._unknownBinaryFrameTypes.add(frame.eventType)\n console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`)\n }\n if (frame.kind === 'text') {\n // a node's live display text (`PromptServer.send_progress_text`), REPLACEMENT\n // semantics per node: each frame is that node's current text, not a delta. This is\n // the only channel on which text arrives DURING a node, so a streaming generator\n // reaches us here and nowhere else. An early frame lost to the pre-registration\n // window needs no buffering (unlike an output image): the next frame replaces it\n const exec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null\n exec?.onProgressText({ nodeId: frame.nodeId, text: frame.text })\n this.onProgressText?.({ nodeId: frame.nodeId, text: frame.text, promptID: this.activePromptID })\n }\n return\n }\n\n const msg_: unknown = JSON.parse(String(e.data))\n\n // ----- crystools silent fix -----\n if (typeof msg_ === 'object' && msg_ != null && 'type' in msg_) {\n if (msg_.type === 'crystools.monitor') return\n }\n\n // ----- soft-validate against the schema -----\n const res = WsMsg_ark(msg_)\n if (res instanceof type.errors) {\n console.log(`[🔴] /!\\\\ Websocket payload does not match schema.`)\n printArkResultInConsole(res)\n }\n // wire tolerance (agent/coding.md): ComfyUI drifts faster than our schema;\n // failures are logged above, then we still route best-effort\n const msg = msg_ as WsMsg\n\n if (msg.type === 'status') {\n if (msg.data.sid) {\n const sidChanged = msg.data.sid !== this.comfySessionId\n this.comfySessionId = msg.data.sid\n this._sessionResolve?.()\n this._sessionResolve = null\n if (sidChanged) this.onSession?.(msg.data.sid)\n }\n this.status = msg.data.status\n this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 })\n return\n }\n\n // defer accumulation to ScriptStep_prompt\n if (msg.type === 'progress') {\n const activePromptID = this.activePromptID\n if (activePromptID == null) {\n console.log(`❌ received a 'progress' msg, but activePromptID is not set`)\n return\n }\n this.routeOrBuffer(activePromptID, msg)\n return\n }\n if (\n msg.type === 'execution_start' ||\n msg.type === 'execution_cached' ||\n msg.type === 'execution_error' ||\n msg.type === 'execution_success' ||\n msg.type === 'executing' ||\n msg.type === 'executed' ||\n msg.type === 'progress_state'\n ) {\n this.routeOrBuffer(msg.data.prompt_id, msg)\n return\n }\n\n if (msg.type === 'manager-terminal-feedback') {\n this.addLog(msg.data.data)\n return\n }\n\n if (msg.type === 'logs') {\n this.onLogs?.(msg.data)\n return\n }\n exhaust(msg)\n console.log('❌', 'Unknown message:', msg)\n\n toastError('Unknown message type: ' + JSON.stringify(msg.type))\n // throw new Error('Unknown message type: ' + JSON.stringify(msg))\n }\n}\n","// fetch-based (node:https replaced 2026-07-31, architecture item 13): the\n// manager registry chain is in the web graph via ComfyRegistry, so this file\n// must stay portable — fetch follows redirects itself, storage owns the write\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport type { AbsolutePath } from 'src/types/index.ts'\n\nexport async function downloadFile(\n //\n url: string,\n outputPath: AbsolutePath | string,\n logPrefix = ' - ',\n): Promise<true> {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`)\n const bytes = new Uint8Array(await res.arrayBuffer())\n getComfyStorage().writeBytes(outputPath, bytes)\n console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`)\n return true\n}\n","import { ansi as chalk } from 'src/utils/ansi.ts'\nimport { downloadFile } from 'src/utils/downloadFile.ts'\n\n// canonical repo since the ltdrdata → Comfy-Org move; the old ltdrdata raw\n// urls still redirect here but that is goodwill, not contract (2026-07-30)\nconst MANAGER_RAW_BASE = 'https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main'\n\nconst MANAGER_MIRROR_FILES = [\n 'custom-node-list.json',\n 'model-list.json',\n 'extension-node-map.json',\n 'alter-list.json',\n 'github-stats.json',\n] as const\n\nexport async function DownloadComfyManagerJSONs(): Promise<void> {\n for (const file of MANAGER_MIRROR_FILES) {\n const dest = `src/manager/json/${file}`\n await downloadFile(`${MANAGER_RAW_BASE}/${file}`, dest, `- downloading ${file}...`)\n console.log(` saved at ${chalk.blue(dest)}`)\n }\n}\n","export const githubRegexpV1 = /https:\\/\\/github.com\\/(.+?)\\/(.+?)\\/?/\nexport const githubRegexpV2 = /https:\\/\\/github.com\\/(.+?)\\/([a-zA-Z0-9-_]+)?/\n","import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport const ComfyPluginExtra: ComfyManagerPluginInfo[] = [\n {\n id: 'TEMP_ComfyUI-BRIA_AI-RMBG',\n author: 'ZHO-ZHO-ZHO',\n title: 'TEMP_ComfyUI-BRIA_AI-RMBG',\n reference: 'https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG',\n files: ['https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG'],\n install_type: 'git-clone',\n description: 'better rembg ?',\n },\n]\n","import { ansi as chalk } from 'src/utils/ansi.ts'\n\n/** root shape of a manager mirror file is broken: nothing to salvage, fail loud */\nexport class ManagerParseError extends Error {\n constructor(\n public file: string,\n public detail: string,\n ) {\n super(`🔴 [manager] ${file} root shape invalid: ${detail}`)\n this.name = 'ManagerParseError'\n }\n}\n\nexport class FileParseCounter {\n total = 0\n accepted = 0\n skipped = new Map<string, { count: number; firstError: string }>()\n\n constructor(public file: string) {}\n\n ok(): void {\n this.total++\n this.accepted++\n }\n\n skip(reason: string, firstError: string): void {\n this.total++\n const prev = this.skipped.get(reason)\n if (prev == null) this.skipped.set(reason, { count: 1, firstError })\n else prev.count++\n }\n}\n\n/** per-file row accounting for the manager mirror parse; printed on every registry build so upstream drift stays visible */\nexport class ManagerParseReport {\n counters: FileParseCounter[] = []\n\n file(name: string): FileParseCounter {\n const counter = new FileParseCounter(name)\n this.counters.push(counter)\n return counter\n }\n\n print(): void {\n console.log(chalk.bold(`[📘 registry] parse report:`))\n for (const c of this.counters) {\n const skippedTotal = [...c.skipped.values()].reduce((acc, cur) => acc + cur.count, 0)\n const headline = ` ${c.file}: ${c.total} rows, ${c.accepted} accepted, ${skippedTotal} skipped`\n console.log(skippedTotal === 0 ? headline : chalk.red(headline))\n for (const [reason, info] of c.skipped) {\n console.log(chalk.red(` - ${reason} x${info.count}, first: ${info.firstError}`))\n }\n }\n }\n}\n","import { type } from 'arktype'\n\n/** root shape only: rows are validated ONE BY ONE against ComfyManagerRawPluginInfo_ark */\nexport type ComfyManagerFilePluginListRoot = typeof ComfyManagerFilePluginListRoot_ark.infer\nexport const ComfyManagerFilePluginListRoot_ark = type({ custom_nodes: 'unknown[]' })\n","import { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { ComfyManagerPluginID } from 'src/manager/types/ComfyManagerPluginEnums.ts'\n\n/**\n * loose INPUT schema: what Comfy-Org/ComfyUI-Manager custom-node-list.json\n * actually ships (surveyed 2026-07-30, 5882 rows)\n */\nexport type ComfyManagerRawPluginInfo = typeof ComfyManagerRawPluginInfo_ark.infer\nexport const ComfyManagerRawPluginInfo_ark = type({\n // always present upstream\n author: 'string',\n title: type.string.as<KnownComfyPluginTitle>(),\n reference: 'string',\n files: type.string.as<KnownComfyPluginURL>().array(),\n install_type: 'string', // 'git-clone' | 'copy' | 'unzip' | stray casings\n description: 'string',\n\n // absent on 4471/5882 rows (2026-07-30): recovered at normalization\n 'id?': type.string.as<ComfyManagerPluginID>(),\n\n // sparse optional tail\n 'preemptions?': 'string[]',\n 'pip?': 'string[]',\n 'nodename_pattern?': 'string',\n 'apt_dependency?': 'string[]',\n 'js_path?': 'string',\n 'version?': 'string',\n 'tags?': 'string[]',\n\n // 2025/2026 additions, unconsumed but declared so drift stays visible\n 'reference2?': 'string',\n 'category?': 'string',\n 'name?': 'string',\n 'license?': 'string',\n 'nickname?': 'string',\n 'stars?': 'number',\n 'last_update?': 'string',\n 'badges?': 'string[]',\n 'dependencies?': 'string[]',\n})\n\n/**\n * canonical plugin row: `id` ALWAYS present (normalization recovers it).\n * The optional tail stays optional ON PURPOSE: this object is also the\n * Manager v2 install POST body, where absent and null differ python-side.\n */\nexport type ComfyManagerPluginInfo = {\n id: ComfyManagerPluginID\n author: string\n title: KnownComfyPluginTitle\n reference: string\n files: KnownComfyPluginURL[]\n install_type: string\n description: string\n preemptions?: string[]\n pip?: string[]\n nodename_pattern?: string\n apt_dependency?: string[]\n js_path?: string\n version?: string\n tags?: string[]\n}\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { githubRegexpV1 } from 'src/utils/githubRegexes.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { ComfyPluginExtra } from 'src/manager/json/custom-node-list.extra.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport { ComfyManagerFilePluginListRoot_ark } from 'src/manager/types/ComfyManagerFilePluginList.ts'\nimport {\n type ComfyManagerRawPluginInfo,\n ComfyManagerRawPluginInfo_ark,\n type ComfyManagerPluginInfo,\n} from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport const _getKnownPlugins = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('custom-node-list.json')\n let totalFileSeen = 0\n\n // parse rows: loose raw schema per row, skip+report failures, normalize survivors\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/custom-node-list.json'))\n const root = ComfyManagerFilePluginListRoot_ark(raw)\n if (root instanceof type.errors) throw new ManagerParseError('custom-node-list.json', root.summary)\n\n const canonical: ComfyManagerPluginInfo[] = []\n for (const row of root.custom_nodes) {\n const res = ComfyManagerRawPluginInfo_ark(row)\n if (res instanceof type.errors) {\n counter.skip('schema', res.summary)\n continue\n }\n const plugin = normalizePluginInfo(res)\n if (plugin == null) {\n counter.skip('id-unrecoverable', res.reference)\n continue\n }\n canonical.push(plugin)\n counter.ok()\n }\n\n // hand-maintained extras are compile-checked canonical rows, not upstream data: no counting\n const knownPluginList: ComfyManagerPluginInfo[] = canonical.concat(ComfyPluginExtra)\n\n for (const plugin of knownPluginList) {\n if (DB.opts.check && DB.plugins_byTitle.has(plugin.title))\n console.log(` ❌ plugin.title: \"${plugin.title}\" is duplicated`)\n DB.plugins_byTitle.set(plugin.title, plugin)\n for (const pluginURI of plugin.files) {\n totalFileSeen++\n if (DB.opts.check && DB.plugins_byFile.has(pluginURI))\n console.log(` ❌ plugin.file: \"${pluginURI}\" is duplicated`)\n DB.plugins_byFile.set(pluginURI, plugin)\n }\n }\n\n // CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n let out1 = ''\n // TitleType\n const allPlugins = [...DB.plugins_byTitle.values()]\n const allPluginsSortedByTitles = allPlugins.sort((a, b) =>\n a.title.toLowerCase().localeCompare(b.title.toLowerCase()),\n )\n out1 += '// prettier-ignore\\n'\n out1 += 'export type KnownComfyPluginTitle =\\n'\n for (const plugin of allPluginsSortedByTitles) {\n out1 += ` /** ${plugin.id} - ${plugin.reference} */\\n`\n out1 += ` | ${JSON.stringify(plugin.title)}\\n`\n }\n out1 += '\\n'\n const out1Path = 'src/manager/generated/KnownComfyPluginTitle.ts'\n getComfyStorage().writeText(out1Path, out1 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out1Path)}`)\n\n // FileType\n let out2 = ''\n const allFileNames = [...DB.plugins_byFile.keys()]\n const sortedFileNames = allFileNames.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))\n out2 += '// prettier-ignore\\n'\n out2 += 'export type KnownComfyPluginURL =\\n'\n for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\\n`\n const out2Path = 'src/manager/generated/KnownComfyPluginURL.ts'\n getComfyStorage().writeText(out2Path, out2)\n console.log(` > generated: ${chalk.blue.underline(out2Path)}`)\n }\n\n // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n console.log(` - ${knownPluginList.length} CustomNodes in file`)\n console.log(` - ${DB.plugins_byTitle.size} CustomNodes registered in map`)\n console.log(` - ${totalFileSeen} CustomNodes-File Seen`)\n console.log(` - ${DB.plugins_byFile.size} CustomNodes-File registered in map`)\n }\n}\n\n/**\n * raw → canonical: recover the missing `id` (absent on ~76% of upstream rows)\n * from the title, else the github repo name. null = unrecoverable, caller\n * reports and skips the row.\n */\nfunction normalizePluginInfo(p: ComfyManagerRawPluginInfo): ComfyManagerPluginInfo | null {\n const id = p.id ?? p.title ?? p.reference.match(githubRegexpV1)?.[2]\n if (id == null) return null\n return { ...p, id }\n}\n","import { type } from 'arktype'\n\nexport type ComfyManagerPluginContentMetadata = typeof ComfyManagerPluginContentMetadata_ark.infer\nexport const ComfyManagerPluginContentMetadata_ark = type({\n // absent on 10/5573 upstream rows (2026-07-30), null on others\n 'title_aux?': type.string.or(type.null), // \"Jovimetrix Composition Nodes\",\n\n // optional\n 'author?': 'string', // \"amorano\",\n 'nickname?': 'string', // \"Comfy Deploy\",\n 'description?': 'string', // \"Webcams, GLSL shader, Media Streaming, Tick animation, Image manipulation,\",\n 'nodename_pattern?': 'string', // \" \\\\(jov\\\\)$\",\n 'title?': 'string', // \"Jovimetrix\",\n 'preemptions?': 'string[]', // ❓\n})\n","import { type } from 'arktype'\nimport type { Tagged } from 'src/types/index.ts'\n\nexport type ComfyManagerPluginContentNodeName = Tagged<string, 'ComfyManagerPluginContentNodeName'>\nexport const ComfyManagerPluginContentNodeName_ark = type.string.as<ComfyManagerPluginContentNodeName>()\n\nexport type ComfyManagerPluginID = string\nexport const ComfyManagerPluginID_ark = type('string')\n","import { type } from 'arktype'\nimport { ComfyManagerPluginContentMetadata_ark } from 'src/manager/types/ComfyManagerPluginContentMetadata.ts'\nimport { ComfyManagerPluginContentNodeName_ark } from 'src/manager/types/ComfyManagerPluginEnums.ts'\n\n/** ONE extension-node-map entry value: [nodeNames, meta]; the file root is a Record of these, validated row by row */\nexport type ComfyManagerExtensionNodeMapEntry = typeof ComfyManagerExtensionNodeMapEntry_ark.infer\nexport const ComfyManagerExtensionNodeMapEntry_ark = type([\n ComfyManagerPluginContentNodeName_ark.array(),\n ComfyManagerPluginContentMetadata_ark,\n])\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'\nimport { githubRegexpV2 } from 'src/utils/githubRegexes.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport type { KnownComfyCustomNodeName } from 'src/manager/generated/KnownComfyCustomNodeName.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport { ComfyManagerExtensionNodeMapEntry_ark } from 'src/manager/types/ComfyManagerFilePluginContent.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport const _getCustomNodeRegistry = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('extension-node-map.json')\n let totalCustomNodeSeen: number = 0\n\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/extension-node-map.json'))\n const root = type('Record<string, unknown>')(raw)\n if (root instanceof type.errors) throw new ManagerParseError('extension-node-map.json', root.summary)\n\n for (const [url, value] of Object.entries(root)) {\n // row shape: [nodeNames, meta]\n const res = ComfyManagerExtensionNodeMapEntry_ark(value)\n if (res instanceof type.errors) {\n counter.skip('schema', `${url}: ${res.summary}`)\n continue\n }\n // cross-reference: the url must be a file of a known plugin (upstream ships a few orphans)\n const plugin = DB.plugins_byFile.get(url as KnownComfyPluginURL)\n if (plugin == null) {\n counter.skip('unknown-plugin-url', url)\n continue\n }\n counter.ok()\n\n // meta (res[1]) is validated so drift stays visible, but consumed by nothing today\n const comfyNodeNames = res[0]\n totalCustomNodeSeen += comfyNodeNames.length\n const pythonModule = reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin)\n\n // ensure we have a list of nodes for this plugin\n const nodesInPlugin: KnownComfyCustomNodeName[] = DB.customNodes_byPluginName.get(plugin.title) ?? []\n DB.customNodes_byPluginName.set(plugin.title, nodesInPlugin)\n\n for (const nodeNameInComfy of comfyNodeNames) {\n const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy)\n const prevEntry = DB.plugins_byNodeKey.get(nodeKey)\n if (prevEntry == null) DB.plugins_byNodeKey.set(nodeKey, [plugin])\n else prevEntry.push(plugin)\n nodesInPlugin.push(nodeKey as KnownComfyCustomNodeName)\n }\n }\n\n // CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n let out = ''\n const allNodeKeys = [...DB.plugins_byNodeKey.keys()]\n const sortedNodeKeys = allNodeKeys.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))\n out += '// prettier-ignore\\n'\n out += 'export type KnownComfyCustomNodeName =\\n'\n for (const nodeName of sortedNodeKeys) {\n out += ` | ${JSON.stringify(nodeName)}\\n`\n }\n out += '\\n'\n\n const outPath = 'src/manager/generated/KnownComfyCustomNodeName.ts'\n getComfyStorage().writeText(outPath, out + '\\n')\n console.log(` > generated: ${chalk.blue.underline(outPath)}`)\n }\n\n // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n console.log(` - ${totalCustomNodeSeen} CustomNodes names processed`)\n console.log(` - ${DB.plugins_byNodeKey.size} unique node keys registered in map`)\n }\n}\n\nfunction reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin: ComfyManagerPluginInfo): string {\n if (plugin.id === 'nodes' && plugin.reference === 'https://github.com/comfyanonymous/ComfyUI') return 'nodes'\n const repoName = plugin.reference.match(githubRegexpV2)?.[2]\n if (repoName) return `custom_nodes.${repoName}`\n return `custom_nodes.${plugin.id}`\n}\n","import type { ComfyManagerFileModelInfo } from 'src/manager/types/ComfyManagerFileModelInfo.ts'\n\nexport const extraModels: ComfyManagerFileModelInfo = {\n models: [\n {\n name: 'TEMP_briaai_RMBG-1.4',\n type: 'controlnet',\n base: 'SDXL',\n save_path: 'custom_nodes/ComfyUI-BRIA_AI-RMBG/RMBG-1.4',\n description: '<3 stuff',\n reference: 'https://huggingface.co/briaai/RMBG-1.4',\n filename: 'model.pth',\n url: 'https://huggingface.co/briaai/RMBG-1.4/resolve/main/model.pth?download=true',\n },\n {\n name: '4x_NMKD-Siax_200k',\n type: 'upscale',\n base: 'upscale',\n save_path: 'default',\n description: '4xRealWebPhoto_v4_dat2',\n reference: 'https://openmodeldb.info/models/4x-RealWebPhoto-v4-dat2',\n filename: '4xRealWebPhoto_v4_dat2.pth',\n url: 'https://huggingface.co/gemasai/4x_NMKD-Siax_200k/resolve/main/4xRealWebPhoto_v4_dat2.pth',\n },\n ],\n}\n","import { type } from 'arktype'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\n\n/** root shape only: rows are validated ONE BY ONE against ComfyManagerModelInfo_ark */\nexport type ComfyManagerFileModelInfoRoot = typeof ComfyManagerFileModelInfoRoot_ark.infer\nexport const ComfyManagerFileModelInfoRoot_ark = type({ models: 'unknown[]' })\n\n/** hand-maintained extras (model-list.extra.ts) still declare the full canonical shape */\nexport type ComfyManagerFileModelInfo = { models: ComfyManagerModelInfo[] }\n","import { type } from 'arktype'\nimport type { KnownModel_Base } from 'src/manager/generated/KnownModel_Base.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport type { KnownModel_SavePath } from 'src/manager/generated/KnownModel_SavePath.ts'\nimport type { KnownModel_Type } from 'src/manager/generated/KnownModel_Type.ts'\n\nexport type ComfyManagerModelInfo = typeof ComfyManagerModelInfo_ark.infer\nexport const ComfyManagerModelInfo_ark = type({\n name: type.string.as<KnownModel_Name>(), // e.g. \"ip-adapter_sd15_light.safetensors\",\n type: type.string.as<KnownModel_Type>(), // e.g. \"IP-Adapter\",\n base: type.string.as<KnownModel_Base>(), // e.g. \"SD1.5\",\n save_path: type.string.as<KnownModel_SavePath>(), // e.g. \"ipadapter\",\n description: 'string', // e.g. \"You can use this model in the [a/ComfyUI IPAdapter plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus) extension.\",\n reference: 'string', // e.g. \"https://huggingface.co/h94/IP-Adapter\",\n filename: 'string', // e.g. \"ip-adapter_sd15_light.safetensors\",\n url: 'string', // e.g. \"https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter_sd15_light.safetensors\"\n 'size?': 'string', // e.g. \"698.4MB\"\n})\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { extraModels } from 'src/manager/json/model-list.extra.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport { ComfyManagerFileModelInfoRoot_ark } from 'src/manager/types/ComfyManagerFileModelInfo.ts'\nimport { type ComfyManagerModelInfo, ComfyManagerModelInfo_ark } from 'src/manager/types/ComfyManagerModelInfo.ts'\n\nexport const _getKnownModels = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('model-list.json')\n\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/model-list.json'))\n const root = ComfyManagerFileModelInfoRoot_ark(raw)\n if (root instanceof type.errors) throw new ManagerParseError('model-list.json', root.summary)\n\n const canonical: ComfyManagerModelInfo[] = []\n for (const row of root.models) {\n const res = ComfyManagerModelInfo_ark(row)\n if (res instanceof type.errors) {\n counter.skip('schema', res.summary)\n continue\n }\n canonical.push(res)\n counter.ok()\n }\n\n // hand-maintained extras are compile-checked canonical rows, not upstream data: no counting\n const knownModelList = canonical.concat(extraModels.models)\n\n for (const modelInfo of knownModelList) {\n DB.knownModels.set(modelInfo.name, modelInfo)\n }\n\n // CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n // #region type\n let out1 = ''\n const uniqCategories: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.type] != null) acc[cur.type]! += 1\n else acc[cur.type] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out1 += `// prettier-ignore\\n`\n out1 += 'export type KnownModel_Type =\\n'\n for (const [cat, count] of Object.entries(uniqCategories))\n out1 += ` | ${JSON.stringify(cat).padEnd(20)} // x ${count.toString().padStart(3)}\\n`\n out1 += '\\n'\n out1 += 'export const knownModel_Type: KnownModel_Type[] = [\\n'\n for (const [cat, count] of Object.entries(uniqCategories))\n out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\\n`\n out1 += ']\\n'\n const out1Path = 'src/manager/generated/KnownModel_Type.ts'\n getComfyStorage().writeText(out1Path, out1 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out1Path)}`)\n\n // #region savepath\n let out4 = ''\n const uniqSavePath: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.save_path] != null) acc[cur.save_path]! += 1\n else acc[cur.save_path] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out4 += `// prettier-ignore\\n`\n out4 += 'export type KnownModel_SavePath =\\n'\n for (const [cat, count] of Object.entries(uniqSavePath))\n out4 += ` | ${JSON.stringify(cat).padEnd(50)} // x ${count.toString().padStart(3)}\\n`\n out4 += '\\n'\n out4 += 'export const knownModel_SavePath: KnownModel_SavePath[] = [\\n'\n for (const [cat, count] of Object.entries(uniqSavePath))\n out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\\n`\n out4 += ']\\n'\n const out4Path = 'src/manager/generated/KnownModel_SavePath.ts'\n getComfyStorage().writeText(out4Path, out4 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out4Path)}`)\n\n // #region base\n let out2 = ''\n const uniqBases: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.base] != null) acc[cur.base]! += 1\n else acc[cur.base] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out2 += `// prettier-ignore\\n`\n out2 += 'export type KnownModel_Base =\\n'\n for (const [cat, count] of Object.entries(uniqBases))\n out2 += ` | ${JSON.stringify(cat).padEnd(20)} // x ${count.toString().padStart(3)}\\n`\n out2 += '\\n'\n out2 += '// prettier-ignore\\n'\n out2 += 'export const knownModel_Base: KnownModel_Base[] = [\\n'\n for (const [cat, count] of Object.entries(uniqBases))\n out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\\n`\n out2 += ']\\n'\n const out2Path = 'src/manager/generated/KnownModel_Base.ts'\n getComfyStorage().writeText(out2Path, out2 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out2Path)}`)\n\n // #region KnownModel_Name\n let out3 = ''\n const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()))\n out3 += `// prettier-ignore\\n`\n out3 += 'export type KnownModel_Name =\\n'\n for (const mi of sortedModels) {\n out3 += ` /** ${mi.description}\\n`\n out3 += ` * ${mi.size} - ${mi.url}\\n`\n out3 += ` * see ${mi.reference}\\n`\n out3 += ` */\\n`\n out3 += ` | ${JSON.stringify(mi.name)}\\n`\n }\n out3 += '\\n'\n const out3Path = 'src/manager/generated/KnownModel_Name.ts'\n getComfyStorage().writeText(out3Path, out3 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out3Path)}`)\n\n // #region KnownModel_FileName\n let out99 = ''\n out99 += `// prettier-ignore\\n`\n out99 += 'export type KnownModel_FileName =\\n'\n for (const mi of sortedModels) {\n out99 += ` /** ${mi.description}\\n`\n out99 += ` * ${mi.size} - ${mi.url}\\n`\n out99 += ` * see ${mi.reference}\\n`\n out99 += ` */\\n`\n out99 += ` | ${JSON.stringify(mi.filename)}\\n`\n }\n out99 += '\\n'\n const out99Path = 'src/manager/generated/KnownModel_FileName.ts'\n getComfyStorage().writeText(out99Path, out99 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out99Path)}`)\n }\n\n // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n console.log(`${knownModelList.length} models found`)\n console.log(`${DB.knownModels.size} models registered map`)\n if (knownModelList.length !== DB.knownModels.size)\n console.log(`❌ some models are either duplicated or have overlapping indexing keys`)\n }\n}\n","import { type } from 'arktype'\n\n/** ONE alter-list.json row (a1111 extension → comfy alternative); `tags` is a comma-separated STRING upstream */\nexport type ComfyManagerAlterInfo = typeof ComfyManagerAlterInfo_ark.infer\nexport const ComfyManagerAlterInfo_ark = type({\n id: 'string', // \"https://github.com/comfyanonymous/ComfyUI\"\n tags: 'string', // \"SD1.x,SD2.x,SDXL\"\n description: 'string',\n})\n\n/** root shape only: rows are validated ONE BY ONE */\nexport type ComfyManagerFileAlterListRoot = typeof ComfyManagerFileAlterListRoot_ark.infer\nexport const ComfyManagerFileAlterListRoot_ark = type({ items: 'unknown[]' })\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport {\n type ComfyManagerAlterInfo,\n ComfyManagerAlterInfo_ark,\n ComfyManagerFileAlterListRoot_ark,\n} from 'src/manager/types/ComfyManagerAlterInfo.ts'\n\nexport const _getAlterList = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('alter-list.json')\n\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/alter-list.json'))\n const root = ComfyManagerFileAlterListRoot_ark(raw)\n if (root instanceof type.errors) throw new ManagerParseError('alter-list.json', root.summary)\n\n const canonical: ComfyManagerAlterInfo[] = []\n for (const row of root.items) {\n const res = ComfyManagerAlterInfo_ark(row)\n if (res instanceof type.errors) {\n counter.skip('schema', res.summary)\n continue\n }\n canonical.push(res)\n counter.ok()\n }\n DB.alterations = canonical\n}\n","import { type } from 'arktype'\n\n/** ONE github-stats.json entry, keyed by repo url in the file root (a Record, validated row by row) */\nexport type ComfyManagerGithubStatEntry = typeof ComfyManagerGithubStatEntry_ark.infer\nexport const ComfyManagerGithubStatEntry_ark = type({\n stars: 'number',\n last_update: 'string', // \"2026-07-28 03:14:59\"\n author_account_age_days: 'number',\n})\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport { ComfyManagerGithubStatEntry_ark } from 'src/manager/types/ComfyManagerGithubStats.ts'\n\nexport const _getGithubStats = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('github-stats.json')\n\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/github-stats.json'))\n const root = type('Record<string, unknown>')(raw)\n if (root instanceof type.errors) throw new ManagerParseError('github-stats.json', root.summary)\n\n for (const [url, value] of Object.entries(root)) {\n const res = ComfyManagerGithubStatEntry_ark(value)\n if (res instanceof type.errors) {\n counter.skip('schema', `${url}: ${res.summary}`)\n continue\n }\n DB.githubStats.set(url, res)\n counter.ok()\n }\n}\n","import { ansi as chalk } from 'src/utils/ansi.ts'\nimport type { NodeNameInComfy, QualifiedNodeKey } from 'src/sdk-generator/comfyui-types.ts'\nimport type { KnownComfyCustomNodeName } from 'src/manager/generated/KnownComfyCustomNodeName.ts'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport { DownloadComfyManagerJSONs } from 'src/manager/loaders/step1_downloadComfyManagerJSONs.ts'\nimport { _getKnownPlugins } from 'src/manager/loaders/step2_custom-node-list-loader.ts'\nimport { _getCustomNodeRegistry } from 'src/manager/loaders/step3_extension-node-map-loader.ts'\nimport { _getKnownModels } from 'src/manager/loaders/step4_model-list-loader.ts'\nimport { _getAlterList } from 'src/manager/loaders/step5_alter-list-loader.ts'\nimport { _getGithubStats } from 'src/manager/loaders/step6_github-stats-loader.ts'\nimport { ManagerParseReport } from 'src/manager/loaders/parseReport.ts'\nimport type { ComfyManagerAlterInfo } from 'src/manager/types/ComfyManagerAlterInfo.ts'\nimport type { ComfyManagerGithubStatEntry } from 'src/manager/types/ComfyManagerGithubStats.ts'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nconst log = (...args: unknown[]) => console.log(`[📘 registry]`, ...args)\n\n// core ComfyUI as a pseudo-plugin: extension-node-map keys the builtin nodes under this url\nconst BUILTIN_URL: KnownComfyPluginURL = 'https://github.com/comfyanonymous/ComfyUI'\nconst BUILTIN_PLUGIN: ComfyManagerPluginInfo = {\n id: 'nodes',\n author: 'comfyanonymous',\n description: 'built-in',\n title: 'built-in',\n files: [BUILTIN_URL],\n reference: 'https://github.com/comfyanonymous/ComfyUI',\n install_type: '',\n}\n\nexport class ComfyRegistry {\n // plugins, indexed\n plugins_byTitle = new Map<KnownComfyPluginTitle, ComfyManagerPluginInfo>()\n plugins_byFile = new Map<KnownComfyPluginURL, ComfyManagerPluginInfo>()\n plugins_byNodeNameInComfy = new Map<NodeNameInComfy, ComfyManagerPluginInfo[]>()\n plugins_byNodeKey = new Map<QualifiedNodeKey, ComfyManagerPluginInfo[]>()\n\n // custom nodes\n customNodes_byPluginName = new Map<KnownComfyPluginTitle, KnownComfyCustomNodeName[]>()\n\n // Models\n knownModels = new Map<KnownModel_Name, ComfyManagerModelInfo>()\n\n // a1111 → comfy alternatives (alter-list.json)\n alterations: ComfyManagerAlterInfo[] = []\n\n // repo url → stars / last_update (github-stats.json)\n githubStats = new Map<string, ComfyManagerGithubStatEntry>()\n\n // per-file row accounting of the last load, printed on every build\n report = new ManagerParseReport()\n\n static async DownloadAndUpdate(download: boolean): Promise<ComfyRegistry> {\n if (download) {\n log(chalk.bold(`1. Downloading comfy-manager JSONs...`))\n await DownloadComfyManagerJSONs()\n } else {\n log(`1. Downloading comfy-manager JSONs... ${chalk.bold('[SKIPPED]')}`)\n }\n // should take care of the code generation\n return new ComfyRegistry({\n check: true,\n genTypes: true,\n })\n }\n\n constructor(\n public opts: {\n check?: boolean\n genTypes?: boolean\n } = {},\n ) {\n // seeded BEFORE codegen so 'built-in' and the core repo url are legitimate union members\n this.plugins_byTitle.set(BUILTIN_PLUGIN.title, BUILTIN_PLUGIN)\n this.plugins_byFile.set(BUILTIN_URL, BUILTIN_PLUGIN)\n\n log(`loading src/manager/json/${chalk.yellow('custom-node-list.json')}...`)\n _getKnownPlugins(this)\n\n log(`loading src/manager/json/${chalk.yellow('extension-node-map.json')}...`)\n _getCustomNodeRegistry(this)\n\n log(`loading src/manager/json/${chalk.yellow('model-list.json')}...`)\n _getKnownModels(this)\n\n log(`loading src/manager/json/${chalk.yellow('alter-list.json')}...`)\n _getAlterList(this)\n\n log(`loading src/manager/json/${chalk.yellow('github-stats.json')}...`)\n _getGithubStats(this)\n\n this.report.print()\n }\n\n getKnownCheckpoints = (): ComfyManagerModelInfo[] => {\n const allKnownModels = [...this.knownModels.values()]\n const allKnownCheckpoints = allKnownModels.filter((i) => i.type === 'checkpoint')\n // console.log(`[🤠] allKnownCheckpoints`, allKnownCheckpoints)\n // for (const mi of knownModels.values()) {\n // console.log(`[🧐] `, mi.type === 'checkpoint' ? '✅' : '❌', mi.name)\n // }\n return allKnownCheckpoints\n }\n\n /**\n * try to replicate the logic of ComfyUIManager to extract the final\n * file path of a downloaded managed model\n */\n getModelInfoFinalFilePath = (mi: ComfyManagerModelInfo): string => {\n /**\n * the wide data-lt once told:\n *\n * | if save_path is 'default'\n * | models/type'/filename\n *\n * | if type is \"checkpoint\"\n * | models/checkpoints/filename\n *\n * | if save_path not starting with custom node\n * | base path is models\n * | e.g. save_path is \"checkpoints/SD1.5\"\n * | models/checkpoints/SD1.5/filename\n * | save_path is \"custom_nodes/AAA/models\"\n * | custom_nodes/AAA/models/filename\n *\n */\n if (mi.save_path === 'default') return `models/${mi.type}/${mi.filename}`\n if (mi.type === 'checkpoint') return `models/checkpoints/${mi.filename}`\n if (mi.save_path.startsWith('custom_nodes')) return `${mi.save_path}/${mi.filename}`\n else return `models/${mi.save_path}/${mi.filename}`\n }\n\n getModelInfoEnumName = (mi: ComfyManagerModelInfo, prefix: string = ''): { win: string; nix: string } => {\n const relPath = this.getModelInfoFinalFilePath(mi)\n\n const winPath = relPath.replace(/\\//g, '\\\\')\n const winPrefix = prefix?.replace(/\\//g, '\\\\')\n const isUnderPrefixWin = winPath.startsWith(winPrefix)\n\n const nixPath = relPath.replace(/\\\\/g, '/')\n const nixPrefix = prefix?.replace(/\\//g, '\\\\')\n const isUnderPrefixNix = nixPath.startsWith(nixPrefix)\n\n const isUnderPrefix = isUnderPrefixNix || isUnderPrefixWin\n return {\n win: isUnderPrefix ? winPath.slice(winPrefix.length) : mi.filename /* winRel */,\n nix: isUnderPrefix ? nixPath.slice(nixPrefix.length) : mi.filename /* nixRel */,\n }\n }\n}\n","import { join } from 'pathe'\nimport pkgJson from '../package.json' with { type: 'json' }\nimport { ComfyHost, type ComfyHostData } from 'src/host/ComfyHost.ts'\nimport { parseHostBase, renderHttpBase } from 'src/host/hostUrl.ts'\nimport { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { type ComfyStorage, resolveComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type AbsolutePath, asAbsolutePath, type RelativePath } from 'src/types/index.ts'\n\n/** the ONE settings-file location rule — run-tui reads it BEFORE any module\n * import creates the comfyts global, so the path logic cannot live on the instance only */\nexport function settingsPathFor(root: string): AbsolutePath {\n return asAbsolutePath(join(root, '.comfy-ts', 'settings.json'))\n}\n\n/** singleton */\nexport class ComfyTS {\n version = pkgJson.version\n\n /** the storage seam (architecture item 13): node fs by default, in-memory on web */\n storage: ComfyStorage\n\n constructor(p: { rootPath?: string; storage?: ComfyStorage } = {}) {\n // global registration: the rest of the lib resolves paths through `comfyts`\n const globalHack = globalThis as { comfyts?: ComfyTS }\n if (globalHack.comfyts != null) throw new Error('ComfyTS instance already created')\n globalHack.comfyts = this\n // storage FIRST: the default rootPath comes from it (browser has no process.cwd)\n this.storage = resolveComfyStorage(p.storage)\n this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd())\n this.baseFolder = asAbsolutePath(join(this.rootPath, '.comfy-ts'))\n this.hostsFolder = asAbsolutePath(join(this.baseFolder, 'hosts'))\n this.outputPath = asAbsolutePath(join(this.baseFolder, 'outputs'))\n }\n\n /**\n * multi-module entrypoint: returns the existing global instance or creates\n * it. Workflow modules MUST use this (the TUI imports many of them into one\n * process); `new ComfyTS()` still throws on a second instance.\n */\n static create(p: { rootPath?: string; storage?: ComfyStorage } = {}): ComfyTS {\n const globalHack = globalThis as { comfyts?: ComfyTS }\n const existing = globalHack.comfyts\n if (existing == null) return new ComfyTS(p)\n if (p.rootPath != null && asAbsolutePath(p.rootPath) !== existing.rootPath)\n throw new Error(\n `ComfyTS.create({rootPath: '${p.rootPath}'}) conflicts with the existing instance rooted at '${existing.rootPath}'`,\n )\n return existing\n }\n\n /** every host created through host(), keyed by id — one instance (and one ws) per id */\n hosts: Map<string, ComfyHost> = new Map()\n\n host<const ID extends string>(data: ComfyHostData & { id: ID }): ComfyHost<ID> {\n const existing = this.hosts.get(data.id)\n if (existing != null) {\n // identity = the parsed base quad + apiKey PRESENCE (equivalent url and\n // host/port spellings unify; the key VALUE never appears in the error)\n const incoming = parseHostBase(data)\n const cur = existing.base\n const sameBase =\n cur.scheme === incoming.scheme &&\n cur.host === incoming.host &&\n cur.port === incoming.port &&\n cur.basePath === incoming.basePath\n const sameAuth = (existing.data.apiKey == null) === (data.apiKey == null)\n if (!sameBase || !sameAuth)\n throw new Error(\n `host id '${data.id}' already registered at ${renderHttpBase(cur)}${existing.data.apiKey != null ? ' (authed)' : ''} — refusing ${renderHttpBase(incoming)}${data.apiKey != null ? ' (authed)' : ''}`,\n )\n // cast: whitelist item 7 (agent/coding.md) — id equality checked just above\n return existing as ComfyHost<ID>\n }\n const created = new ComfyHost(data)\n this.hosts.set(data.id, created)\n return created\n }\n\n /**\n * A ComfyRegistry instance that provides access to all\n * known Comfy nodes, models, plugins, ...\n * lazy: constructing it parses ~3MB of ComfyUI-Manager JSON, only pay when used\n */\n private _registry: ComfyRegistry | null = null\n get registry(): ComfyRegistry {\n if (this._registry == null) this._registry = new ComfyRegistry({ check: false, genTypes: false })\n return this._registry\n }\n\n /** root path used to resolve things (set in the constructor, storage.cwd() default) */\n rootPath: AbsolutePath\n\n /**\n * every repo using comfy-ts gets ONE `.comfy-ts/` folder:\n * .comfy-ts/hosts/<id>/{object_info.json, embeddings.json, sdk.d.ts}\n * .comfy-ts/outputs/... generated images & workflows\n * .comfy-ts/drafts/<workflow-id>/<draft>.json TUI var snapshots (local, gitignored)\n * .comfy-ts/prompt-enhancers/<name>.md serve web ui master prompts (local, gitignored)\n */\n baseFolder: AbsolutePath\n hostsFolder: AbsolutePath\n outputPath: AbsolutePath\n\n resolveFromDrafts(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'drafts', relativePath))\n }\n\n /** master prompts of the serve web ui's prompt enhancer — hand-editable markdown */\n resolveFromPromptEnhancers(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'prompt-enhancers', relativePath))\n }\n\n resolveFromCache(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'cache', relativePath))\n }\n\n /** local TUI settings (preview mode, last draft per workflow) — gitignored */\n get settingsPath(): AbsolutePath {\n return settingsPathFor(this.rootPath)\n }\n\n resolveFromHosts(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.hostsFolder, relativePath))\n }\n\n /**\n * Resolves a relative path against an absolute path.\n * @param from - The absolute path to resolve from.\n * @param relativePath - The relative path to resolve.\n * @returns The resolved absolute path.\n */\n resolve(from: AbsolutePath, relativePath: RelativePath): AbsolutePath {\n return asAbsolutePath(join(from, relativePath))\n }\n resolveFromOutput(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.outputPath, relativePath))\n }\n\n readJSON_ = <T>(absPath: AbsolutePath, def?: T): T => {\n const str = this.storage.readTextIfExists(absPath)\n if (str == null) {\n if (def != null) return def\n throw new Error(`file does not exist ${absPath}`)\n }\n const json = JSON.parse(str)\n return json\n }\n\n // for automatic formating of produced ComfyUI workflow\n autolayoutOpts: {\n node_hsep: number\n node_vsep: number\n forceLeft: boolean\n } = {\n node_hsep: 50,\n node_vsep: 50,\n forceLeft: false,\n }\n}\n\ndeclare global {\n var comfyts: ComfyTS\n}\n","/**\n * build a LoraManager-style lora tag: `<lora:name:strength>` or\n * `<lora:name:strength:clipStrength>`. Pin the name to a host union for\n * autocomplete + validation:\n *\n * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)\n */\nexport function loraTag<N extends string = string>(name: N, strength: number = 1, clipStrength?: number): string {\n return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`\n}\n","/**\n * comfy-ts/web — the BROWSER entry (architecture item 13): same library,\n * in-memory storage, native WebSocket, no sharp. Types still come from a\n * generated sdk.d.ts included in the consumer's tsconfig.\n * Importing both entries in one process: the LAST import wins the default\n * backend — pass ComfyTS.create({ storage }) to be explicit (SSR setups).\n * @packageDocumentation\n */\nimport { createMemoryStorage, setDefaultComfyStorage } from 'src/storage/ComfyStorage.ts'\n\nsetDefaultComfyStorage(createMemoryStorage())\n\nexport * from 'src/coreExports.ts'\n\n// the serve web panel's postMessage host protocol, TYPES ONLY: a page embedding the panel in an\n// <iframe> types what it sends and receives, and no runtime enters the browser graph\nexport type {\n HostToPanel,\n PanelError,\n PanelHostAction,\n PanelRequest,\n PanelResultAction,\n PanelState,\n PanelToHost,\n} from 'src/cli/serve/hostProtocol.ts'\n"],"mappings":";;;;;;AAmCA,SAAS,UAAU,MAAsB;CACtC,MAAM,KAAK,KAAK,YAAY,GAAG;CAC/B,OAAO,MAAM,IAAI,MAAM,KAAK,MAAM,GAAG,EAAE;AAC1C;;;AAIA,SAAgB,sBAAsB,IAAgB,IAA8B;CACjF,OAAO;EACJ,MAAM;EACN,WAAW,MAAM,GAAG,aAAa,GAAG,MAAM;EAC1C,mBAAmB,MAAO,GAAG,WAAW,CAAC,IAAK,GAAG,aAAa,GAAG,MAAM,IAAe;EACtF,YAAY,MAAM,IAAI,WAAW,GAAG,aAAa,CAAC,CAAe;EACjE,YAAY,GAAG,SAAS;GACrB,GAAG,UAAU,UAAU,CAAC,GAAG,EAAE,WAAW,KAAK,CAAC;GAC9C,GAAG,cAAc,GAAG,IAAI;EAC3B;EACA,aAAa,GAAG,UAAU;GACvB,GAAG,UAAU,UAAU,CAAC,GAAG,EAAE,WAAW,KAAK,CAAC;GAC9C,GAAG,cAAc,GAAG,KAAK;EAC5B;EACA,SAAS,MAAM,GAAG,WAAW,CAAC;EAC9B,SAAS,MAAM,KAAK,GAAG,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;EACvD,UAAU,MAAO,GAAG,WAAW,CAAC,IAAI,GAAG,SAAS,CAAC,CAAC,CAAC,UAAU;EAC7D,eAAe,GAAG,QAAQ;EAC1B,WAAW,QAAQ,IAAI;CAC1B;AACH;;;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AC;CAC5D;AAsBH;;;;;;;;;;ACvJA,SAAgB,QAAmC,MAAS,WAAmB,GAAG,cAA+B;CAC9G,OAAO,gBAAgB,OAAO,SAAS,KAAK,GAAG,SAAS,KAAK,SAAS,KAAK,GAAG,SAAS,GAAG,aAAa;AAC1G;;;;;;;;;;;ACCA,uBAAuB,oBAAoB,CAAC"}
1
+ {"version":3,"file":"web.js","names":["g","isRecord","isRecord","types","chalk","isRecord","chalk","chalk","chalk","chalk","chalk","chalk","pkgJson.version","globalHack"],"sources":["../src/storage/ComfyStorage.ts","../package.json","../src/litegraph/LiteGraphLinkID.ts","../src/utils/bang.ts","../src/litegraph/expandSubgraphs.ts","../src/litegraph/LiteGraphGroup.ts","../src/litegraph/LiteGraphLink.ts","../src/litegraph/LiteGraphNodeInput.ts","../src/litegraph/LiteGraphSlotIndex.ts","../src/litegraph/LiteGraphNodeOutput.ts","../src/litegraph/LiteGraphNode.ts","../src/litegraph/LiteGraphSubgraphDef.ts","../src/litegraph/LiteGraphJSON.ts","../src/litegraph/normalizeWorkflow.ts","../src/runner/wsBinaryFrame.ts","../src/sdk-generator/Primitives.ts","../src/sdk-generator/inputWidgetKind.ts","../src/sdk-generator/litegraphToApiRequestPayload.ts","../src/utils/isRecord.ts","../src/runner/describePromptRejection.ts","../src/errors/InvalidPromptError.ts","../src/utils/ComfyColors.ts","../src/graph/autoValue.ts","../src/graph/ComfyNodeOutput.ts","../src/graph/ComfyNode.ts","../src/host/ComfyWorkflowBuilder.ts","../src/litegraph/convertFlowToLiteGraphJSON.ts","../src/runner/outputPath.ts","../src/utils/extractErrorMessage.ts","../src/utils/lazySharp.ts","../src/types/index.ts","../src/image-utils/_getPngMetadata.ts","../src/utils/exhaust.ts","../src/utils/sha1.ts","../src/utils/hashArrayBuffer.ts","../src/graph/ComfyNodeID.ts","../src/runner/ComfyWsApi.ts","../src/runner/MediaImage.ts","../src/runner/ComfyExecution.ts","../src/runner/ephemeral.ts","../src/utils/deepCopyNaive.ts","../src/utils/ansi.ts","../src/utils/log.ts","../src/utils/printArkResultInConsole.ts","../src/utils/softValidate.ts","../src/utils/toposort.ts","../src/runner/ComfyWorkflowLayout.ts","../src/runner/ComfyWorkflow.ts","../src/utils/matchesRegex.ts","../src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts","../src/sdk-generator/_pythonModuleToNamespace.ts","../src/sdk-generator/_toQualifiedNodeKey.ts","../src/utils/CodeBuffer.ts","../src/utils/escapeJSKey.ts","../src/sdk-generator/ComfyNodeSchema.ts","../src/sdk-generator/comfyui-sdk-codegen.ts","../src/sdk-generator/comfyui-types.ts","../src/sdk-generator/ComfySchema.ts","../src/sdk-generator/ComfyUIObjectInfoTypes.ts","../src/utils/stringifyReadable.ts","../src/manager/types/ComfyManagerAPIModelList.ts","../src/manager/types/ComfyManagerAPIPluginList.ts","../src/host/ComfyManager.ts","../src/host/ComfyUploader.ts","../src/host/hostUrl.ts","../src/host/ResilientWebsocket.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","../src/host/schemaDrift.ts","../src/host/ComfyHost.ts","../src/utils/downloadFile.ts","../src/manager/loaders/step1_downloadComfyManagerJSONs.ts","../src/utils/githubRegexes.ts","../src/manager/json/custom-node-list.extra.ts","../src/manager/loaders/parseReport.ts","../src/manager/types/ComfyManagerFilePluginList.ts","../src/manager/types/ComfyManagerPluginInfo.ts","../src/manager/loaders/step2_custom-node-list-loader.ts","../src/manager/types/ComfyManagerPluginContentMetadata.ts","../src/manager/types/ComfyManagerPluginEnums.ts","../src/manager/types/ComfyManagerFilePluginContent.ts","../src/manager/loaders/step3_extension-node-map-loader.ts","../src/manager/json/model-list.extra.ts","../src/manager/types/ComfyManagerFileModelInfo.ts","../src/manager/types/ComfyManagerModelInfo.ts","../src/manager/loaders/step4_model-list-loader.ts","../src/manager/types/ComfyManagerAlterInfo.ts","../src/manager/loaders/step5_alter-list-loader.ts","../src/manager/types/ComfyManagerGithubStats.ts","../src/manager/loaders/step6_github-stats-loader.ts","../src/manager/ComfyRegistry.ts","../src/state.ts","../src/utils/loraTag.ts","../src/web.ts"],"sourcesContent":["// 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 } from 'arktype'\nimport type { Branded } from 'src/types/index.ts'\n\nexport const asLiteGraphLinkID = (id: number): LiteGraphLinkID => id as LiteGraphLinkID\nexport const LiteGraphLinkID_ = type.number.atLeast(0).as<Branded<number, { LiteGraphLinkID: true }>>()\nexport type LiteGraphLinkID = typeof LiteGraphLinkID_.infer\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","import type { CanonicalLink, CanonicalNode, CanonicalWorkflow } from 'src/litegraph/CanonicalWorkflow.ts'\nimport { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'\nimport { WorkflowNormalizeError } from 'src/litegraph/normalizeWorkflow.ts'\nimport { bang } from 'src/utils/bang.ts'\n\n/** one exposed slot of a normalized subgraph definition */\nexport type CanonicalSubgraphIO = {\n name: string\n type: string\n}\n\n/** a subgraph definition normalized by the SAME per-node/per-link normalizers as the root */\nexport type CanonicalSubgraphDef = {\n id: string // uuid, referenced by instance nodes' `type`\n name: string\n inputs: CanonicalSubgraphIO[]\n outputs: CanonicalSubgraphIO[]\n nodes: CanonicalNode[]\n links: CanonicalLink[]\n}\n\n/** boundary sentinel ids inside definition link tables */\nconst SUBGRAPH_INPUT_NODE_ID = -10\nconst SUBGRAPH_OUTPUT_NODE_ID = -20\n\n/** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */\nconst MAX_EXPANSION_PASSES = 32\n\n/**\n * widget-kind fallback when a def input slot has no boundary target carrying a\n * widget marker: these litegraph slot types carry widget values. LOCAL copy on\n * purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here\n * (the io-widget era serializes exactly one value per exposed widget slot).\n */\nconst PRIMITIVE_WIDGET_TYPES: ReadonlySet<string> = new Set(['INT', 'FLOAT', 'STRING', 'BOOLEAN', 'COMBO'])\n\n/**\n * inline every subgraph instance (node whose `type` is a definition uuid) into\n * the root graph: fresh numeric ids, boundary links rewired, instance widget\n * values promoted into the inner nodes' `named` overrides. Iterative so nested\n * definitions expand on the next pass. Muted instances are dropped (their\n * consumers resolve unconnected); bypassed instances stay for the converter's\n * passthrough walk, which needs no interior.\n */\nexport const expandSubgraphs = (wf: CanonicalWorkflow, defs: Map<string, CanonicalSubgraphDef>): CanonicalWorkflow => {\n let passes = 0\n while (true) {\n const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== 'bypassed')\n if (expandable.length === 0) return wf\n if (++passes > MAX_EXPANSION_PASSES)\n throw new WorkflowNormalizeError(\n 'subgraph-cycle',\n `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`,\n )\n for (const instance of expandable) {\n if (instance.mode === 'muted') dropMutedInstance(wf, instance)\n else expandOneInstance(wf, instance, bang(defs.get(instance.type)))\n }\n }\n}\n\n/** converter mute semantics applied early: after expansion there is no single node left to skip */\nconst dropMutedInstance = (wf: CanonicalWorkflow, instance: CanonicalNode): void => {\n const dead = new Set<LiteGraphLinkID>()\n for (const link of wf.links) {\n if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id)\n }\n wf.links = wf.links.filter((l) => !dead.has(l.id))\n wf.nodes = wf.nodes.filter((n) => n.id !== instance.id)\n pruneDeadLinkRefs(wf, dead)\n}\n\nconst pruneDeadLinkRefs = (wf: CanonicalWorkflow, dead: ReadonlySet<LiteGraphLinkID>): void => {\n if (dead.size === 0) return\n for (const node of wf.nodes) {\n for (const input of node.inputs) {\n if (input.link != null && dead.has(input.link)) input.link = null\n }\n for (const output of node.outputs) {\n output.links = output.links.filter((id) => !dead.has(id))\n }\n }\n}\n\nconst expandOneInstance = (wf: CanonicalWorkflow, instance: CanonicalNode, def: CanonicalSubgraphDef): void => {\n // 1. fresh numeric ids, deterministic (def node order / def link order)\n let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id))\n let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id))\n const newNodeIds = new Map<number, number>()\n for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId)\n // null = the def link references a node the def does not contain: upstream\n // editors leave STALE links behind after node deletion (corpus-verified,\n // e.g. utility_video_upscale) and the frontend prunes them on load. We drop\n // the link; the consumer resolves unconnected, loud at conversion when required.\n const remapNodeId = (id: number): number | null => newNodeIds.get(id) ?? null\n\n // 2. instance input slot → def input slot, BY NAME (instances may serialize\n // a subset of the def's inputs). A name matching NO def input is LOUD:\n // silently falling back to the positional index would wire the outer feed\n // into the wrong inner slot (corpus-absent today, so a throw is safe)\n const defSlotOfInstanceSlot = new Map<number, number>()\n for (const [k, input] of instance.inputs.entries()) {\n const defSlot = def.inputs.findIndex((d) => d.name === input.name)\n if (defSlot < 0)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): input \"${input.name}\" (slot ${k}) matches no definition input (defined: ${def.inputs.map((d) => d.name).join(', ')})`,\n )\n defSlotOfInstanceSlot.set(k, defSlot)\n }\n\n // 3. outer links INTO the instance, keyed by def input slot\n const outerLinkIntoDefSlot = new Map<number, CanonicalLink>()\n for (const link of wf.links) {\n if (link.targetId !== instance.id) continue\n const defSlot = defSlotOfInstanceSlot.get(link.targetSlot)\n if (defSlot == null)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`,\n )\n outerLinkIntoDefSlot.set(defSlot, link)\n }\n\n // 4. classify definition links: plain interior links clone with fresh ids;\n // input-boundary links (-10 origin) become real links from the outer origin\n // when one exists (else they drop and the inner target falls back to its own\n // widget values); output-boundary links (-20 target) just name the inner\n // producer each def output slot maps to.\n const newLinkIds = new Map<LiteGraphLinkID, LiteGraphLinkID>()\n const splicedLinks: CanonicalLink[] = []\n const producerByOutSlot = new Map<number, { nodeId: number; slot: number }>()\n const passthroughOutSlot = new Map<number, number>() // def out slot → def in slot (-10 → -20 direct)\n const boundaryTargetsByInSlot = new Map<number, { nodeId: number; slot: number }[]>() // remapped inner targets\n for (const link of def.links) {\n const fromInputBoundary = link.originId === SUBGRAPH_INPUT_NODE_ID\n const toOutputBoundary = link.targetId === SUBGRAPH_OUTPUT_NODE_ID\n if (fromInputBoundary && toOutputBoundary) {\n passthroughOutSlot.set(link.targetSlot, link.originSlot)\n continue\n }\n if (toOutputBoundary) {\n const producerId = remapNodeId(link.originId)\n if (producerId != null && !producerByOutSlot.has(link.targetSlot))\n producerByOutSlot.set(link.targetSlot, { nodeId: producerId, slot: link.originSlot })\n continue\n }\n if (fromInputBoundary) {\n const targetId = remapNodeId(link.targetId)\n if (targetId == null) continue\n const target = { nodeId: targetId, slot: link.targetSlot }\n const targets = boundaryTargetsByInSlot.get(link.originSlot) ?? []\n targets.push(target)\n boundaryTargetsByInSlot.set(link.originSlot, targets)\n const outer = outerLinkIntoDefSlot.get(link.originSlot)\n if (outer == null) continue // no outer feed: inner target's input.link nulls at clone time\n const fresh = asLiteGraphLinkID(++nextLinkId)\n newLinkIds.set(link.id, fresh)\n splicedLinks.push({\n id: fresh,\n originId: outer.originId,\n originSlot: outer.originSlot,\n targetId: target.nodeId,\n targetSlot: target.slot,\n type: link.type,\n })\n const originNode = wf.nodes.find((n) => n.id === outer.originId)\n originNode?.outputs[outer.originSlot]?.links.push(fresh)\n continue\n }\n const interiorOrigin = remapNodeId(link.originId)\n const interiorTarget = remapNodeId(link.targetId)\n if (interiorOrigin == null || interiorTarget == null) continue\n const fresh = asLiteGraphLinkID(++nextLinkId)\n newLinkIds.set(link.id, fresh)\n splicedLinks.push({\n id: fresh,\n originId: interiorOrigin,\n originSlot: link.originSlot,\n targetId: interiorTarget,\n targetSlot: link.targetSlot,\n type: link.type,\n })\n }\n\n // 5. clone inner nodes with remapped ids; link refs not in newLinkIds were\n // dropped boundary links → null (the node falls back to its widget values)\n const splicedNodes: CanonicalNode[] = def.nodes.map((inner) => ({\n id: bang(newNodeIds.get(inner.id)),\n type: inner.type,\n title: inner.title,\n mode: inner.mode,\n isVirtualNode: inner.isVirtualNode,\n inputs: inner.inputs.map((i) => ({\n name: i.name,\n type: i.type,\n link: i.link != null ? (newLinkIds.get(i.link) ?? null) : null,\n widgetName: i.widgetName,\n })),\n outputs: inner.outputs.map((o) => ({\n name: o.name,\n type: o.type,\n links: o.links.map((id) => newLinkIds.get(id)).filter((id): id is LiteGraphLinkID => id != null),\n })),\n widgets: { positional: [...inner.widgets.positional], named: { ...inner.widgets.named } },\n pos: [inner.pos[0], inner.pos[1]],\n size: [inner.size[0], inner.size[1]],\n properties: { ...inner.properties },\n }))\n\n // 6. rewire root links FROM the instance's outputs onto the inner producers;\n // outer links INTO the instance were consumed by step 4\n const dead = new Set<LiteGraphLinkID>()\n for (const link of wf.links) {\n if (link.targetId === instance.id) {\n dead.add(link.id)\n continue\n }\n if (link.originId !== instance.id) continue\n const producer = producerByOutSlot.get(link.originSlot)\n if (producer != null) {\n link.originId = producer.nodeId\n link.originSlot = producer.slot\n const producerNode = splicedNodes.find((n) => n.id === producer.nodeId)\n producerNode?.outputs[producer.slot]?.links.push(link.id)\n continue\n }\n const passthroughInSlot = passthroughOutSlot.get(link.originSlot)\n const outer = passthroughInSlot != null ? outerLinkIntoDefSlot.get(passthroughInSlot) : null\n if (outer != null) {\n link.originId = outer.originId\n link.originSlot = outer.originSlot\n continue\n }\n dead.add(link.id) // def output has no producer: consumers resolve unconnected\n }\n wf.links = wf.links.filter((l) => !dead.has(l.id))\n pruneDeadLinkRefs(wf, dead)\n\n // 7. widget promotion (both serialization eras), then splice\n promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot)\n wf.nodes = wf.nodes.filter((n) => n.id !== instance.id)\n wf.nodes.push(...splicedNodes)\n wf.links.push(...splicedLinks)\n}\n\n/**\n * instance widget values land in inner nodes' `named` overrides. TWO eras for\n * the POSITIONAL values:\n * - proxyWidgets era: `properties.proxyWidgets` pairs [innerNodeId, widgetName]\n * zip against the instance's positional values (incl. `control_after_generate`\n * phantom pairs — written to `named` and simply never read, no schema input\n * has that name).\n * - io-widget era (no proxyWidgets): positional values zip against the def's\n * widget-kind input slots in def order, one value per slot (no phantom —\n * corpus-verified). An outer link into the same slot wins in the converter;\n * the named override is still written, matching ComfyUI.\n * PLUS, in both eras, NAMED overrides on the instance keyed by def-input name:\n * that is how a NESTED instance receives its outer values (the previous pass\n * wrote them to `named`), so they must forward through THIS expansion too —\n * named wins over positional, same precedence as the converter.\n */\nconst promoteInstanceWidgets = (\n instance: CanonicalNode,\n def: CanonicalSubgraphDef,\n splicedNodes: CanonicalNode[],\n newNodeIds: Map<number, number>,\n boundaryTargetsByInSlot: Map<number, { nodeId: number; slot: number }[]>,\n): void => {\n const promoteToSlotTargets = (slot: number, value: unknown): void => {\n for (const t of boundaryTargetsByInSlot.get(slot) ?? []) {\n const target = splicedNodes.find((n) => n.id === t.nodeId)\n const input = innerInputAt(splicedNodes, t)\n if (target == null || input == null) continue\n target.widgets.named[input.name] = value\n }\n }\n\n promotePositionalWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets)\n\n for (const [slot, io] of def.inputs.entries()) {\n if (!Object.hasOwn(instance.widgets.named, io.name)) continue\n promoteToSlotTargets(slot, instance.widgets.named[io.name])\n }\n}\n\nconst promotePositionalWidgets = (\n instance: CanonicalNode,\n def: CanonicalSubgraphDef,\n splicedNodes: CanonicalNode[],\n newNodeIds: Map<number, number>,\n boundaryTargetsByInSlot: Map<number, { nodeId: number; slot: number }[]>,\n promoteToSlotTargets: (slot: number, value: unknown) => void,\n): void => {\n const values = instance.widgets.positional\n if (values.length === 0) return // inner nodes keep their serialized defaults\n\n const proxy = instance.properties['proxyWidgets']\n if (Array.isArray(proxy) && proxy.length > 0) {\n const count = Math.min(values.length, proxy.length)\n for (let k = 0; k < count; k++) {\n const pair: unknown = proxy[k]\n if (!Array.isArray(pair) || pair.length !== 2)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): malformed proxyWidgets entry ${JSON.stringify(pair)}`,\n )\n const innerId = Number(pair[0])\n const widgetName = String(pair[1])\n if (innerId < 0) {\n // id -1 names a widget on the subgraph node ITSELF (a promoted io\n // widget): route the value through the matching def input slot\n const slot = def.inputs.findIndex((d) => d.name === widgetName)\n if (slot < 0)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names io widget \"${widgetName}\" but no definition input matches`,\n )\n promoteToSlotTargets(slot, values[k])\n continue\n }\n const target = splicedNodes.find((n) => n.id === newNodeIds.get(innerId))\n if (target == null)\n throw new WorkflowNormalizeError(\n 'subgraph-io-mismatch',\n `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names unknown inner node ${String(pair[0])}`,\n )\n target.widgets.named[widgetName] = values[k]\n }\n return\n }\n\n let valueIndex = 0\n for (const [slot, io] of def.inputs.entries()) {\n const targets = boundaryTargetsByInSlot.get(slot) ?? []\n const isWidgetSlot =\n targets.length > 0\n ? targets.some((t) => innerInputAt(splicedNodes, t)?.widgetName != null)\n : PRIMITIVE_WIDGET_TYPES.has(io.type)\n if (!isWidgetSlot) continue\n if (valueIndex >= values.length) break\n promoteToSlotTargets(slot, values[valueIndex++])\n }\n}\n\nconst innerInputAt = (\n splicedNodes: CanonicalNode[],\n t: { nodeId: number; slot: number },\n): { name: string; widgetName: string | null } | null => {\n const node = splicedNodes.find((n) => n.id === t.nodeId)\n return node?.inputs[t.slot] ?? null\n}\n","import { type } from 'arktype'\nimport type { EmptyRecord, IsEqual } from 'src/types/index.ts'\n\n// prettier-ignore\nexport type LiteGraphGroup = {\n id?: number // 1 (newer serializers only)\n title: string // 'Create Mask'\n bounding: [number, number, number, number] // [1078, -579, 1589, 614]\n color?: string // '#3f789e' (omitted = litegraph default)\n font_size?: number // 24 (omitted = litegraph default)\n flags?: EmptyRecord // {}\n}\n\nexport const LiteGraphGroup_ark = type({\n 'id?': 'number',\n title: 'string',\n bounding: type(['number', 'number', 'number', 'number']),\n 'color?': 'string',\n 'font_size?': 'number',\n // EmptyRecord: an object we don't read any key from\n 'flags?': type.Record('string', 'unknown').as<EmptyRecord>(),\n})\n\ntrue satisfies IsEqual<LiteGraphGroup, typeof LiteGraphGroup_ark.infer>\n","import { type } from 'arktype'\nimport type { IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'\n\n/** v0.4 serialization: links are 6-tuples (our EXPORT path emits this form) */\nexport type LiteGraphLinkTuple = [\n linkId: LiteGraphLinkID, // 9, - linkId\n fromNodeId: number, // 8, - fromNodeId\n fromNodeOutputIx: number, // 0, - fromNodeOutputIx\n toNodeId: number, // 9, - toNodeId\n toNodeInputIx: number, // 0, - toNodeInputIx\n linkType: string, // \"IMAGE\" - type\n]\n\nexport const LiteGraphLinkTuple_ark = type([\n LiteGraphLinkID_, // 9, - linkId\n 'number', // 8, - fromNodeId\n 'number', // 0, - fromNodeOutputIx\n 'number', // 9, - toNodeId\n 'number', // 0, - toNodeInputIx\n 'string', // \"IMAGE\" - linkType\n])\n\ntrue satisfies IsEqual<typeof LiteGraphLinkTuple_ark.infer, LiteGraphLinkTuple>\n\n/** v1 serialization: links are objects (subgraph definition interiors use this) */\nexport type LiteGraphLinkObject = {\n id: LiteGraphLinkID\n origin_id: number // -10 = the subgraph's inputNode boundary\n origin_slot: number\n target_id: number // -20 = the subgraph's outputNode boundary\n target_slot: number\n type: string\n parentId?: number // reroute chain parent (cosmetic)\n}\n\nexport const LiteGraphLinkObject_ark = type({\n id: LiteGraphLinkID_,\n origin_id: 'number',\n origin_slot: 'number',\n target_id: 'number',\n target_slot: 'number',\n type: 'string',\n 'parentId?': 'number',\n})\n\ntrue satisfies IsEqual<typeof LiteGraphLinkObject_ark.infer, LiteGraphLinkObject>\n\nexport type LiteGraphLink = LiteGraphLinkTuple | LiteGraphLinkObject\n\nexport const LiteGraphLink_ark = LiteGraphLinkTuple_ark.or(LiteGraphLinkObject_ark)\n\ntrue satisfies IsEqual<typeof LiteGraphLink_ark.infer, LiteGraphLink>\n","import { type } from 'arktype'\nimport type { IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'\n\nexport type LiteGraphNodeInput = {\n name: string // | 'clip'\n type: string // | 'CLIP'\n link?: LiteGraphLinkID | null // | 5 (widget-backed inputs omit the key)\n shape?: number // | 7\n label?: string // | 'select'\n widget?: {\n name: string // | 'select'\n config?: unknown // | 2022-era serializer only, gone since\n }\n}\n\nexport const LiteGraphNodeInput_ark = type({\n name: 'string',\n type: 'string',\n 'link?': LiteGraphLinkID_.or(type.null),\n 'shape?': 'number',\n 'label?': 'string',\n 'widget?': type({\n name: 'string',\n 'config?': 'unknown',\n }),\n})\n\ntrue satisfies IsEqual<LiteGraphNodeInput, typeof LiteGraphNodeInput_ark.infer>\n","import { type } from 'arktype'\nimport type { Branded } from 'src/types/index.ts'\n\nexport const asLiteGraphSlotIndex = (id: number): LiteGraphSlotIndex => id as LiteGraphSlotIndex\nexport const LiteGraphSlotIndex_ = type.number.atLeast(0).as<Branded<number, { LiteGraphSlotIndex: true }>>()\nexport type LiteGraphSlotIndex = typeof LiteGraphSlotIndex_.infer\n","import { type } from 'arktype'\nimport type { IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'\nimport { type LiteGraphSlotIndex, LiteGraphSlotIndex_ } from 'src/litegraph/LiteGraphSlotIndex.ts'\n\nexport type LiteGraphNodeOutput = {\n name: string\n type: string // 'CONDITIONING'\n links?: LiteGraphLinkID[] | null // unconnected outputs may omit the key\n shape?: number // '2D'\n slot_index?: LiteGraphSlotIndex\n}\n\nexport const LiteGraphNodeOutput_ark = type({\n name: 'string',\n type: 'string',\n 'links?': LiteGraphLinkID_.array().or(type.null),\n 'shape?': 'number',\n 'slot_index?': LiteGraphSlotIndex_,\n})\n\ntrue satisfies IsEqual<LiteGraphNodeOutput, typeof LiteGraphNodeOutput_ark.infer>\n","import { type } from 'arktype'\nimport type { IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphNodeInput, LiteGraphNodeInput_ark } from 'src/litegraph/LiteGraphNodeInput.ts'\nimport { type LiteGraphNodeOutput, LiteGraphNodeOutput_ark } from 'src/litegraph/LiteGraphNodeOutput.ts'\n\n// prettier-ignore\nexport type LiteGraphNode = {\n id: number // 5\n type: string // 'CLIPTextEncode', or a definitions.subgraphs uuid (instance)\n\n // cosmetics\n title?: string // \"Inpaint (Positive)\",\n color?: string // \"#222\", or \"#3f789e\"\n bgcolor?: string // \"#3f789e\" (lowercase, like upstream)\n pos: { '0': number; '1': number } // serialized as [number, number] OR {0,1}\n size: { '0': number; '1': number }\n flags?: Record<string, unknown> // collapsed?, pinned?, … — never read\n order?: number\n /**\n * 0 = always (normal), 1 = on-event, 2 = muted (never),\n * 3 = on-trigger, 4 = bypassed\n */\n mode?: number\n inputs?: LiteGraphNodeInput[]\n outputs?: LiteGraphNodeOutput[]\n\n isVirtualNode?: boolean // frontend only\n /** open record: proxyWidgets (subgraph widget promotion), cnr_id/ver (pack provenance), … */\n properties?: Record<string, unknown>\n /** array form (positional) OR object form (named, e.g. VHS_VideoCombine) */\n widgets_values?: unknown[] | Record<string, unknown>\n}\n\nexport const LiteGraphNode_ark = type({\n id: 'number',\n type: 'string',\n\n // cosmetics\n 'title?': 'string',\n 'color?': 'string',\n 'bgcolor?': 'string',\n pos: { '0': 'number', '1': 'number' },\n size: { '0': 'number', '1': 'number' },\n 'flags?': type.Record('string', 'unknown'),\n 'order?': 'number',\n 'mode?': 'number',\n 'inputs?': LiteGraphNodeInput_ark.array(),\n 'outputs?': LiteGraphNodeOutput_ark.array(),\n 'isVirtualNode?': 'boolean',\n 'properties?': type.Record('string', 'unknown'),\n 'widgets_values?': type('unknown[]').or(type.Record('string', 'unknown')),\n})\n\ntrue satisfies IsEqual<LiteGraphNode, typeof LiteGraphNode_ark.infer>\n","import { type } from 'arktype'\nimport type { EmptyRecord, IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphGroup, LiteGraphGroup_ark } from 'src/litegraph/LiteGraphGroup.ts'\nimport { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'\nimport { type LiteGraphLinkObject, LiteGraphLinkObject_ark } from 'src/litegraph/LiteGraphLink.ts'\nimport { type LiteGraphNode, LiteGraphNode_ark } from 'src/litegraph/LiteGraphNode.ts'\n\n/** one exposed input/output slot of a subgraph definition */\nexport type LiteGraphSubgraphIO = {\n id: string // uuid\n name: string // 'image'\n type: string // 'IMAGE'\n linkIds?: LiteGraphLinkID[]\n label?: string\n localized_name?: string\n pos?: { '0': number; '1': number }\n shape?: number\n}\n\nexport const LiteGraphSubgraphIO_ark = type({\n id: 'string',\n name: 'string',\n type: 'string',\n 'linkIds?': LiteGraphLinkID_.array(),\n 'label?': 'string',\n 'localized_name?': 'string',\n 'pos?': { '0': 'number', '1': 'number' },\n 'shape?': 'number',\n})\n\ntrue satisfies IsEqual<LiteGraphSubgraphIO, typeof LiteGraphSubgraphIO_ark.infer>\n\n/**\n * a subgraph definition body (definitions.subgraphs[] entry). Corpus fact:\n * every one is a v1-shaped interior (object links, `state`) even when the\n * root document is v0.4 — instances reference it via node.type = this uuid.\n */\nexport type LiteGraphSubgraphDef = {\n id: string // uuid, referenced by instance nodes' `type`\n name: string\n version: number // 1 in the whole corpus\n state?: Record<string, unknown> // {lastNodeId, lastLinkId, …} — recomputable\n revision?: number\n config?: EmptyRecord\n extra?: unknown\n nodes: LiteGraphNode[]\n links: LiteGraphLinkObject[]\n groups?: LiteGraphGroup[]\n inputNode: { id: number; bounding: number[] } // id is -10 in boundary links\n outputNode: { id: number; bounding: number[] } // id is -20 in boundary links\n inputs: LiteGraphSubgraphIO[]\n outputs: LiteGraphSubgraphIO[]\n widgets: unknown[] // empty in the whole corpus\n}\n\nexport const LiteGraphSubgraphDef_ark = type({\n id: 'string',\n name: 'string',\n version: 'number',\n 'state?': type.Record('string', 'unknown'),\n 'revision?': 'number',\n 'config?': type.Record('string', 'unknown').as<EmptyRecord>(),\n 'extra?': 'unknown',\n nodes: LiteGraphNode_ark.array(),\n links: LiteGraphLinkObject_ark.array(),\n 'groups?': LiteGraphGroup_ark.array(),\n inputNode: { id: 'number', bounding: 'number[]' },\n outputNode: { id: 'number', bounding: 'number[]' },\n inputs: LiteGraphSubgraphIO_ark.array(),\n outputs: LiteGraphSubgraphIO_ark.array(),\n widgets: 'unknown[]',\n})\n\ntrue satisfies IsEqual<LiteGraphSubgraphDef, typeof LiteGraphSubgraphDef_ark.infer>\n","import { type } from 'arktype'\nimport type { EmptyRecord, IsEqual } from 'src/types/index.ts'\nimport { type LiteGraphGroup, LiteGraphGroup_ark } from 'src/litegraph/LiteGraphGroup.ts'\nimport { type LiteGraphLink, LiteGraphLink_ark } from 'src/litegraph/LiteGraphLink.ts'\nimport { type LiteGraphNode, LiteGraphNode_ark } from 'src/litegraph/LiteGraphNode.ts'\nimport { type LiteGraphSubgraphDef, LiteGraphSubgraphDef_ark } from 'src/litegraph/LiteGraphSubgraphDef.ts'\n\n/** comfy workflows are simply LiteGraphs workflows */\nexport type ComfyWorkflowJSON = LiteGraphJSON\n\n/**\n * litegraph workflow root, TOLERANT: models what upstream actually serializes\n * across eras — v0.4 (tuple links, last_*_id) and v1 (object links, `state`),\n * including hybrid files (v0.4 root + v1-shaped subgraph definitions).\n * Downstream code never reads this shape: `normalizeWorkflow` turns it into\n * the strict `CanonicalWorkflow`.\n */\nexport type LiteGraphJSON = {\n id?: string // uuid (newer serializers)\n revision?: number\n last_node_id?: number // v0.4 (recomputable, absent in v1)\n last_link_id?: number // v0.4\n state?: Record<string, unknown> // v1: {lastNodeId, lastLinkId, …}\n nodes: LiteGraphNode[]\n links: LiteGraphLink[]\n groups?: LiteGraphGroup[]\n config?: EmptyRecord\n extra?: {\n ds?: {\n scale: number\n offset: { 0: number; 1: number }\n }\n }\n models?: unknown[] // model download manifest — never read\n definitions?: { subgraphs: LiteGraphSubgraphDef[] }\n reroutes?: unknown[] // v1 cosmetic link routing — dropped at normalization\n floatingLinks?: unknown[] // v1 cosmetic — dropped at normalization\n version: 0.4 | 1\n}\n\nexport const LiteGraphJSON_ark = type({\n 'id?': 'string',\n 'revision?': 'number',\n 'last_node_id?': 'number',\n 'last_link_id?': 'number',\n 'state?': type.Record('string', 'unknown'),\n nodes: LiteGraphNode_ark.array(),\n links: LiteGraphLink_ark.array(),\n 'groups?': LiteGraphGroup_ark.array(),\n 'config?': type.Record('never', 'never'),\n 'extra?': {\n 'ds?': {\n scale: 'number',\n offset: {\n '0': 'number',\n '1': 'number',\n },\n },\n },\n 'models?': 'unknown[]',\n 'definitions?': { subgraphs: LiteGraphSubgraphDef_ark.array() },\n 'reroutes?': 'unknown[]',\n 'floatingLinks?': 'unknown[]',\n version: '0.4 | 1',\n})\n\ntrue satisfies IsEqual<LiteGraphJSON, typeof LiteGraphJSON_ark.infer>\n","import { type } from 'arktype'\nimport type {\n CanonicalGroup,\n CanonicalInput,\n CanonicalLink,\n CanonicalNode,\n CanonicalOutput,\n CanonicalWidgetValues,\n CanonicalWorkflow,\n NodeMode,\n} from 'src/litegraph/CanonicalWorkflow.ts'\nimport { type CanonicalSubgraphDef, expandSubgraphs } from 'src/litegraph/expandSubgraphs.ts'\nimport type { LiteGraphGroup } from 'src/litegraph/LiteGraphGroup.ts'\nimport { type LiteGraphJSON, LiteGraphJSON_ark } from 'src/litegraph/LiteGraphJSON.ts'\nimport type { LiteGraphLink } from 'src/litegraph/LiteGraphLink.ts'\nimport type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'\nimport type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'\nimport type { LiteGraphNodeOutput } from 'src/litegraph/LiteGraphNodeOutput.ts'\nimport type { LiteGraphSubgraphDef } from 'src/litegraph/LiteGraphSubgraphDef.ts'\n\nexport type WorkflowNormalizeErrorCode = 'schema-reject' | 'subgraph-cycle' | 'subgraph-io-mismatch' | 'bad-document'\n\n/** a workflow JSON we cannot turn into a CanonicalWorkflow — loud, typed, never a cast */\nexport class WorkflowNormalizeError extends Error {\n constructor(\n public code: WorkflowNormalizeErrorCode,\n message: string,\n public detail?: unknown,\n ) {\n super(`[workflow ${code}] ${message}`)\n this.name = 'WorkflowNormalizeError'\n }\n}\n\n/**\n * THE one entry for foreign workflow JSON (files, clipboard, imports):\n * tolerant ark validation, then normalization to the strict canonical shape.\n */\nexport const parseWorkflowJson = (json: unknown): CanonicalWorkflow => {\n const out = LiteGraphJSON_ark(json)\n if (out instanceof type.errors) throw new WorkflowNormalizeError('schema-reject', out.summary, out)\n return normalizeWorkflow(out)\n}\n\n/**\n * loose wire document → strict canonical document. Defaults filled, both link\n * eras unified, cosmetic fields dropped, subgraph definitions expanded away\n * (see expandSubgraphs.ts — def interiors go through the SAME per-shape\n * normalizers, they are v1 bodies).\n */\nexport const normalizeWorkflow = (raw: LiteGraphJSON): CanonicalWorkflow => {\n const wf: CanonicalWorkflow = {\n nodes: raw.nodes.map(normalizeNode),\n links: raw.links.map(normalizeLink),\n groups: (raw.groups ?? []).map(normalizeGroup),\n }\n const rawDefs = raw.definitions?.subgraphs ?? []\n if (rawDefs.length === 0) return wf\n const defs = new Map<string, CanonicalSubgraphDef>()\n for (const d of rawDefs) defs.set(d.id, normalizeSubgraphDef(d))\n return expandSubgraphs(wf, defs)\n}\n\nconst normalizeSubgraphDef = (d: LiteGraphSubgraphDef): CanonicalSubgraphDef => {\n return {\n id: d.id,\n name: d.name,\n inputs: d.inputs.map((io) => ({ name: io.name, type: io.type })),\n outputs: d.outputs.map((io) => ({ name: io.name, type: io.type })),\n nodes: d.nodes.map(normalizeNode),\n links: d.links.map(normalizeLink),\n }\n}\n\nconst normalizeMode = (mode: number | undefined): NodeMode => {\n if (mode === 2) return 'muted'\n if (mode === 4) return 'bypassed'\n return 'normal' // 0 (always) / 1 (on-event) / 3 (on-trigger) all execute\n}\n\nconst normalizeNode = (n: LiteGraphNode): CanonicalNode => {\n return {\n id: n.id,\n type: n.type,\n title: n.title ?? null,\n mode: normalizeMode(n.mode),\n isVirtualNode: n.isVirtualNode ?? false,\n inputs: (n.inputs ?? []).map(normalizeInput),\n outputs: (n.outputs ?? []).map(normalizeOutput),\n widgets: normalizeWidgetValues(n.widgets_values),\n pos: [n.pos[0], n.pos[1]],\n size: [n.size[0], n.size[1]],\n properties: { ...n.properties },\n }\n}\n\nconst normalizeInput = (i: LiteGraphNodeInput): CanonicalInput => {\n return {\n name: i.name,\n type: i.type,\n link: i.link ?? null,\n widgetName: i.widget?.name ?? null,\n }\n}\n\nconst normalizeOutput = (o: LiteGraphNodeOutput): CanonicalOutput => {\n return {\n name: o.name,\n type: o.type,\n links: [...(o.links ?? [])],\n }\n}\n\nconst normalizeWidgetValues = (wv: unknown[] | Record<string, unknown> | undefined): CanonicalWidgetValues => {\n if (wv == null) return { positional: [], named: {} }\n if (Array.isArray(wv)) return { positional: [...wv], named: {} }\n return { positional: [], named: { ...wv } }\n}\n\nconst normalizeLink = (l: LiteGraphLink): CanonicalLink => {\n if (Array.isArray(l)) {\n return { id: l[0], originId: l[1], originSlot: l[2], targetId: l[3], targetSlot: l[4], type: l[5] }\n }\n return {\n id: l.id,\n originId: l.origin_id,\n originSlot: l.origin_slot,\n targetId: l.target_id,\n targetSlot: l.target_slot,\n type: l.type,\n }\n}\n\nconst normalizeGroup = (g: LiteGraphGroup): CanonicalGroup => {\n return {\n title: g.title,\n bounding: [g.bounding[0], g.bounding[1], g.bounding[2], g.bounding[3]],\n color: g.color ?? '#3f789e',\n fontSize: g.font_size ?? 24,\n }\n}\n","// pure parser for BINARY ws frames (formats per\n// agent/external-docs/comfy-cloud/api-reference.md, all integers big-endian):\n// 1 PREVIEW_IMAGE 4B type · 4B image_type (1 jpeg, 2 png) · image bytes\n// 3 TEXT 4B type · 4B node_id_len · node_id · progress text\n// 4 PREVIEW_IMAGE_WITH_METADATA 4B type · 4B metadata_len · metadata JSON · image bytes\n// Unknown types come back as 'unknown' — the CALLER logs, never throws: the\n// wire drifts faster than we do (type 4 appeared on the first live cloud run).\n\nexport type ParsedBinaryWsFrame =\n | { kind: 'preview'; bytes: Uint8Array<ArrayBuffer>; mime: string; metadata: unknown }\n | { kind: 'text'; nodeId: string; text: string }\n | { kind: 'unknown'; eventType: number }\n\nexport function parseBinaryWsFrame(data: ArrayBuffer): ParsedBinaryWsFrame {\n const view = new DataView(data)\n const eventType = view.getUint32(0)\n\n if (eventType === 1) {\n const imageType = view.getUint32(4)\n const bytes = new Uint8Array(data.slice(8))\n const mime = imageType === 2 ? 'image/png' : 'image/jpeg'\n return { kind: 'preview', bytes, mime, metadata: null }\n }\n\n if (eventType === 3) {\n const nodeIdLen = view.getUint32(4)\n const decoder = new TextDecoder()\n const nodeId = decoder.decode(data.slice(8, 8 + nodeIdLen))\n const text = decoder.decode(data.slice(8 + nodeIdLen))\n return { kind: 'text', nodeId, text }\n }\n\n if (eventType === 4) {\n const metadataLen = view.getUint32(4)\n let metadata: unknown = null\n try {\n metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)))\n } catch {\n // tolerate broken metadata: the image bytes are the payload that matters\n }\n const bytes = new Uint8Array(data.slice(8 + metadataLen))\n // the docs say \"raw JPEG/PNG bytes\" with no format field — sniff the magic\n const mime = bytes[0] === 0x89 && bytes[1] === 0x50 ? 'image/png' : 'image/jpeg'\n return { kind: 'preview', bytes, mime, metadata }\n }\n\n return { kind: 'unknown', eventType }\n}\n","import type { ComfyNodeSchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\n\nexport const ComfyPrimitiveMapping: { [key: string]: string } = {\n // BACK\n BOOLEAN: 'boolean',\n FLOAT: 'number',\n INT: 'number',\n STRING: 'string',\n\n // ????\n // ⏸️ Boolean: 'boolean',\n // ⏸️ Float: 'number',\n // ⏸️ Integer: 'number',\n // ⏸️ SchedulerName: 'string',\n // ⏸️ SamplerName: 'string',\n // ⏸️ IMAGE_PATH: 'string',\n}\n\nexport const ComfyPrimitives: string[] = Object.keys(ComfyPrimitiveMapping)\n\n// schema-driven widget counting moved to src/sdk-generator/inputWidgetKind.ts\n// (config-driven classification); what stays below is the LEGACY serialized-\n// type path, used only when an old file carries a widget-marked input whose\n// schema now says slot.\n\n/**\n * when a litegraph node has an input entry with a widget marker, the\n * serialized TYPE string decides how many widgets_values it consumed in that era\n */\nexport const howManyWidgetValuesForThisInputType = (type: string, nameInComfy: string): number => {\n if (type === 'INT') {\n if (nameInComfy === 'seed' || nameInComfy === 'noise_seed') return 2\n return 1\n }\n if (type === 'BOOLEAN') return 1\n if (type === 'FLOAT') return 1\n if (type === 'STRING') return 1\n if (type === 'COMBO') return 1\n if (type === 'INT:seed') return 2\n if (type === 'INT:noise_seed') return 2\n\n // not a primitive, no Field_values\n return 0\n}\nexport const ComfyDefaultNodeWhenUnknown_Name: string = 'UnknownNodeXX'\n\nexport const ComfyDefaultNodeWhenUnknown_Schema: ComfyNodeSchemaJSON = {\n category: 'test',\n input: {},\n output: [],\n description: 'This is a test node',\n output_name: [],\n display_name: 'UnknownNodeXX',\n name: 'UnknownNodeXX',\n output_is_list: [],\n output_node: false,\n python_module: 'nodes',\n}\n","import type { NodeInputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { ComfyPrimitiveMapping } from 'src/sdk-generator/Primitives.ts'\n\n/**\n * Widget-ness of a schema input, decided from its CONFIG — never from a\n * type-name whitelist (2026 object_info spells widget inputs as arbitrary\n * strings backed by a frontend widget registry we cannot mirror; every\n * registry spelling carries a config signal instead). Signal precedence and\n * their upstream anchors: agent/architecture.md \"Widget-ness is decided from\n * the input CONFIG\".\n */\nexport type InputWidgetKind =\n | { kind: 'slot' }\n | {\n kind: 'widget'\n /** total widgets_values entries this input's run occupies: prefix buttons + value + control phantom */\n consumes: number\n strictValues: boolean\n /**\n * serialized values the frontend addWidget()s BEFORE the real value\n * (button widgets, creation order). Import reads the value at\n * `offset + prefixValues.length`; export writes these literals first\n * so a round-trip through the ComfyUI editor keeps positional\n * alignment. Empty for every config-signalled widget.\n */\n prefixValues: readonly unknown[]\n }\n | { kind: 'dynamic-combo'; options: DynamicComboOption[]; defaultKey: string }\n | { kind: 'dynamic-container'; instanceNames: string[]; requiredCount: number }\n\n/** one raw `[type, opts]` input entry as spelled in object_info (dynamic-combo branches arrive in this raw form) */\nexport type RawInputSpecEntry = {\n name: string\n type: string | readonly unknown[]\n opts: unknown\n required: boolean\n}\n\nexport type DynamicComboOption = { key: string; inputs: RawInputSpecEntry[] }\n\nexport const isRecord = (x: unknown): x is Record<string, unknown> =>\n typeof x === 'object' && x != null && !Array.isArray(x)\n\n/**\n * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.\n * The frontend creates the control widget on truthiness, and real 2026 hosts\n * spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,\n * SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed\n * heuristic applies.\n */\nconst controlConsumes = (o: Record<string, unknown> | null, typeName: string, name: string): 1 | 2 => {\n if (o != null && 'control_after_generate' in o) return o['control_after_generate'] ? 2 : 1\n if (typeName === 'INT' && (name === 'seed' || name === 'noise_seed')) return 2\n return 1\n}\n\nconst flattenInputSections = (inputs: Record<string, unknown>): RawInputSpecEntry[] => {\n const out: RawInputSpecEntry[] = []\n for (const section of ['required', 'optional'] as const) {\n const sec = inputs[section]\n if (!isRecord(sec)) continue\n for (const [name, spec] of Object.entries(sec)) {\n if (!Array.isArray(spec) || spec.length === 0) continue\n const t: unknown = spec[0]\n if (typeof t !== 'string' && !Array.isArray(t)) continue\n out.push({ name, type: t, opts: spec[1], required: section === 'required' })\n }\n }\n return out\n}\n\n/** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */\nconst parseDynamicOptions = (options: unknown[]): DynamicComboOption[] | null => {\n if (options.length === 0) return null\n const out: DynamicComboOption[] = []\n for (const entry of options) {\n if (!isRecord(entry)) return null\n const key = entry['key']\n const inputs = entry['inputs']\n if (typeof key !== 'string' || !isRecord(inputs)) return null\n out.push({ key, inputs: flattenInputSections(inputs) })\n }\n return out\n}\n\n/**\n * autogrow (`template` WITH a nested `input` section): instances are always\n * link slots named `decl.<name_i>` (the backend force-inputs widget\n * templates), the first `min` of them required WHEN the template input\n * section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.\n */\nconst parseContainer = (template: Record<string, unknown>): InputWidgetKind => {\n const input = template['input']\n const min = typeof template['min'] === 'number' ? template['min'] : 1\n const prefix = typeof template['prefix'] === 'string' ? template['prefix'] : ''\n const max = typeof template['max'] === 'number' ? template['max'] : 100\n const rawNames = template['names']\n const names = Array.isArray(rawNames)\n ? rawNames.filter((n): n is string => typeof n === 'string')\n : Array.from({ length: max }, (_, i) => `${prefix}${i}`)\n const templateRequired = isRecord(input) && isRecord(input['required']) && Object.keys(input['required']).length > 0\n return {\n kind: 'dynamic-container',\n instanceNames: names,\n requiredCount: templateRequired ? Math.min(min, names.length) : 0,\n }\n}\n\n/**\n * the single template sub-input's slot type of an autogrow container\n * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an\n * autogrow template or the template has several sub-inputs (corpus-absent\n * 2026-07-30, 27/27 single on the cloud catalog) — then codegen emits no\n * typed instance keys and the container stays builderBase territory.\n */\nexport const containerInstanceSlotType = (opts: unknown): string | null => {\n const o = isRecord(opts) ? opts : null\n const template = o?.['template']\n if (!isRecord(template) || !isRecord(template['input'])) return null\n const subs = flattenInputSections(template['input'])\n const first = subs[0]\n if (subs.length !== 1 || first == null || typeof first.type !== 'string') return null\n return first.type\n}\n\n/**\n * frontend-registered widgets whose object_info opts carry NO config signal —\n * the one exception to config-only classification (architecture.md rule 8).\n * Every entry must quote the frontend widget-creation source.\n *\n * LOAD_3D (ComfyUI_frontend src/extensions/core/load3d.ts, verified\n * 2026-07-31): the LOAD_3D custom widget handler runs\n * node.addWidget('button', 'upload 3d model', 'upload3dmodel', …)\n * node.addWidget('button', 'upload extra resources', 'uploadExtraResources', …)\n * node.addWidget('button', 'clear', 'clear', …)\n * THEN creates the scene widget, so the serialized run is\n * [btn, btn, btn, value] with the real value LAST. Lax domain: '' in saved\n * files, an {image, mask, normal, camera_info, …} dict at queue time.\n */\nconst EMPTY_CONFIG_FRONTEND_WIDGETS: Record<string, { prefixValues: readonly unknown[] }> = {\n LOAD_3D: { prefixValues: ['upload3dmodel', 'uploadExtraResources', 'clear'] },\n}\n\nexport const classifyWidgetInput = (p: {\n name: string\n type: string | readonly unknown[]\n opts: unknown\n /** true when type is a generated `E_*` union name (parsed 2024-era enum) */\n isEnumUnion?: boolean\n}): InputWidgetKind => {\n const o = isRecord(p.opts) ? p.opts : null\n // 1. forceInput gates widget creation upstream, whatever the type says\n if (o?.['forceInput'] === true) return { kind: 'slot' }\n // 2. enum arrays / parsed E_ unions are combo widgets\n if (Array.isArray(p.type) || p.isEnumUnion === true) {\n const tn = typeof p.type === 'string' ? p.type : 'COMBO'\n return { kind: 'widget', consumes: controlConsumes(o, tn, p.name), strictValues: true, prefixValues: [] }\n }\n if (typeof p.type !== 'string') return { kind: 'slot' }\n // 3. widgetType names the widget for multi-type unions (frontend: widgets.get(widgetType ?? type))\n const widgetTypeName = typeof o?.['widgetType'] === 'string' ? o['widgetType'] : p.type\n // 4. primitives\n if (ComfyPrimitiveMapping[widgetTypeName] != null)\n return {\n kind: 'widget',\n consumes: controlConsumes(o, widgetTypeName, p.name),\n strictValues: true,\n prefixValues: [],\n }\n // 5. options array: dynamic {key, inputs} family, else plain combo\n const options = o?.['options']\n if (Array.isArray(options)) {\n const dynOptions = parseDynamicOptions(options)\n if (dynOptions != null) {\n const first = dynOptions[0]\n if (first == null) return { kind: 'slot' } // unreachable: parseDynamicOptions rejects empty\n const defaultKey = typeof o?.['default'] === 'string' ? o['default'] : first.key\n return { kind: 'dynamic-combo', options: dynOptions, defaultKey }\n }\n return { kind: 'widget', consumes: controlConsumes(o, p.type, p.name), strictValues: true, prefixValues: [] }\n }\n // 6. template WITH nested input = autogrow container; WITHOUT = matchtype slot typing\n const template = o?.['template']\n if (isRecord(template)) {\n if (isRecord(template['input'])) return parseContainer(template)\n return { kind: 'slot' }\n }\n // 7. socketless: a widget that never has a socket (IMAGECOMPARE, COLOR); value domain unknown\n if (o?.['socketless'] === true) return { kind: 'widget', consumes: 1, strictValues: false, prefixValues: [] }\n // 8. known empty-config frontend widgets (LOAD_3D), the one non-config exception\n const emptyConfigEntry = EMPTY_CONFIG_FRONTEND_WIDGETS[widgetTypeName]\n if (emptyConfigEntry != null)\n return {\n kind: 'widget',\n consumes: emptyConfigEntry.prefixValues.length + 1,\n strictValues: false,\n prefixValues: emptyConfigEntry.prefixValues,\n }\n return { kind: 'slot' }\n}\n\nexport const classifySchemaInput = (input: NodeInputExt): InputWidgetKind =>\n classifyWidgetInput({\n name: input.nameInComfy,\n type: input.typeName,\n opts: input.opts,\n isEnumUnion: input.isEnum,\n })\n\n/**\n * what ComfyUI's frontend gives a widget created with no serialized value\n * (`getWidgetDefaultValue` semantics), used when a positional array is\n * shorter than the schema's widget list. `null` for custom widgets — the\n * backend accepts an explicit null but errors on an ABSENT required key.\n */\nexport const defaultValueForWidget = (p: {\n type: string\n opts: unknown\n /** resolved values when the type is a generated E_ union or an inline enum array */\n enumValues?: readonly (string | boolean | number)[]\n}): unknown => {\n const o = isRecord(p.opts) ? p.opts : null\n if (o != null && o['default'] !== undefined) return o['default']\n const widgetTypeName = typeof o?.['widgetType'] === 'string' ? o['widgetType'] : p.type\n if (widgetTypeName === 'INT' || widgetTypeName === 'FLOAT') return 0\n if (widgetTypeName === 'BOOLEAN') return false\n if (widgetTypeName === 'STRING') return ''\n const options = o?.['options']\n if (Array.isArray(options) && options.length > 0) {\n const first: unknown = options[0]\n if (typeof first === 'string' || typeof first === 'number' || typeof first === 'boolean') return first\n }\n if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0]\n return null\n}\n","import type {\n CanonicalInput,\n CanonicalLink,\n CanonicalNode,\n CanonicalWorkflow,\n} from 'src/litegraph/CanonicalWorkflow.ts'\nimport type { LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport type { NodeInputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { howManyWidgetValuesForThisInputType } from 'src/sdk-generator/Primitives.ts'\nimport {\n classifySchemaInput,\n classifyWidgetInput,\n defaultValueForWidget,\n isRecord,\n type DynamicComboOption,\n type RawInputSpecEntry,\n} from 'src/sdk-generator/inputWidgetKind.ts'\n\ntype PromptInputValue = ComfyApiNodeJson['inputs'][string]\n\nexport type WorkflowConvertErrorCode =\n | 'unknown-node'\n | 'missing-widget-value'\n | 'invalid-widget-value'\n | 'unknown-dynamic-combo-option'\n | 'dangling-link'\n | 'missing-required-input'\n | 'unsupported-feature'\n\n/** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */\nexport class WorkflowConvertError extends Error {\n constructor(\n public code: WorkflowConvertErrorCode,\n message: string,\n public node?: { id: number; type: string },\n ) {\n super(`[workflow ${code}] ${message}`)\n this.name = 'WorkflowConvertError'\n }\n}\n\n/**\n * closed set: frontend-only node types that NEVER execute. PrimitiveString /\n * PrimitiveInt / PrimitiveBoolean etc are REAL backend nodes — do not add them.\n */\nconst VIRTUAL_NODE_TYPES: ReadonlySet<string> = new Set(['Note', 'MarkdownNote', 'Reroute', 'PrimitiveNode'])\n\nconst isNeverExecuted = (node: CanonicalNode): boolean => node.isVirtualNode || VIRTUAL_NODE_TYPES.has(node.type)\n\n/** exact match, or `*` wildcard on either side (Reroute-style slots) */\n/** frontend isValidConnection parity: exact, `*` wildcard, or any member of a comma-separated multi-type */\nconst linkTypeMatches = (a: string, b: string): boolean => {\n if (a === b || a === '*' || b === '*') return true\n if (!a.includes(',') && !b.includes(',')) return false\n const as = a.split(',')\n const bs = b.split(',')\n return as.some((x) => bs.includes(x))\n}\n\n/** what an inlined PrimitiveNode may contribute: scalar widget values only */\nconst isPromptScalar = (v: unknown): v is string | number | boolean | null =>\n v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'\n\n/**\n * convert a normalized workflow (CanonicalWorkflow — see parseWorkflowJson)\n * into the api.json (prompt format) ComfyUI's POST /prompt takes.\n * Handles: muted nodes (skipped, consumers resolve unconnected), bypassed\n * nodes (mode 4: link resolution walks through to the first type-matching\n * input), Note/MarkdownNote/Reroute/PrimitiveNode virtual nodes (reroutes\n * unwrapped, primitives inlined into their consumers), widget values both\n * positional (with the phantom `control_after_generate` offset after seeds)\n * and named (object-form widgets_values + subgraph promotion overrides —\n * named wins, but a live link wins over both). Widget-ness is decided from\n * the input CONFIG (inputWidgetKind.ts): V3 string-spelled widget types\n * (COMBO options, dynamic combos, autogrow containers, socketless customs)\n * and 2024-era enums go through ONE classifier; a positional array shorter\n * than the schema's widget list fills schema defaults, never throws\n * (agent/architecture.md owns both decisions).\n */\nexport const convertLiteGraphToPrompt = (\n /** the ComfySchema object (to look for references/definitions) */\n schema: ComfySchema,\n /** the normalized litegraph document */\n workflow: CanonicalWorkflow,\n opts: { verbose?: boolean } = {},\n): ComfyApiJson => {\n const prompt: ComfyApiJson = {}\n const LOG = opts.verbose ? (...args: unknown[]): void => console.log('[🔥] converter:', ...args) : (): void => {}\n\n // 1. cache primitive node values so links from PrimitiveNode inline as values.\n // A PrimitiveNode may serialize WITHOUT a value (real corpus case): its\n // consumers then resolve unconnected and fall back to their OWN serialized\n // widget values — the primitive only mirrors the consumer's widget.\n const PRIMITIVE_VALUES: { [nodeId: string]: unknown } = {}\n for (const node of workflow.nodes) {\n if (node.type !== 'PrimitiveNode') continue\n if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0]\n else if (Object.hasOwn(node.widgets.named, 'value')) PRIMITIVE_VALUES[node.id] = node.widgets.named['value']\n }\n\n // 2. every executable node\n for (const node of workflow.nodes) {\n if (isNeverExecuted(node)) continue // frontend-only nodes (reroutes/primitives unwrapped below)\n if (node.mode !== 'normal') continue // muted skipped, bypassed passthrough'd at link resolution\n\n const inputs: ComfyApiNodeJson['inputs'] = {}\n const fieldNamesPresent = new Set(node.inputs.map((i) => i.name))\n const nodeSchema_ = schema.nodesByNameInComfy[node.type]\n if (nodeSchema_ == null)\n throw new WorkflowConvertError(\n 'unknown-node',\n `node ${node.id}(${node.type}) has no schema on this host; a custom node is missing`,\n node,\n )\n const nodeSchema: ComfyNodeSchema = nodeSchema_\n\n // 2.a widget values, walked in schema order. Widget-ness comes from the\n // input CONFIG (classifySchemaInput — agent/architecture.md): named wins,\n // else positional cursor, else SCHEMA-DEFAULT FILL (what the frontend\n // does when an old file meets a grown schema — a throw would reject files\n // ComfyUI runs fine). The offset advances past named-shadowed slots\n // whenever a positional array exists (promotion case). A LIVE LINK on\n // the field wins over both — the widget value is kept as the fallback\n // for dead-end link resolution (muted/bypassed parents).\n let offset = 0\n const positional = node.widgets.positional\n const named = node.widgets.named\n const widgetFallback = new Map<string, PromptInputValue>()\n const inputsInNodeJSON: CanonicalInput[] = node.inputs\n const inputsInNodeSchema: NodeInputExt[] = nodeSchema.inputs\n\n /** arrays ride wrapped (a bare 2-list is a link server-side); objects pass only in lax (custom-widget) domains */\n const toPromptValue = (value: unknown, p: { promptName: string; strict: boolean }): PromptInputValue => {\n if (value == null) return null\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value\n if (Array.isArray(value)) return { __value__: value }\n if (!p.strict && isRecord(value)) return value\n throw new WorkflowConvertError(\n 'invalid-widget-value',\n `node ${node.id}(${node.type}) has an invalid widget value for \"${p.promptName}\": ${JSON.stringify(value)}`,\n node,\n )\n }\n\n /** named wins, then positional cursor (+prefixLen skips leading button values, LOAD_3D); filled=true when both miss (caller falls back to the schema default) */\n const resolveWidgetValue = (p: {\n promptName: string\n consumes: number\n prefixLen: number\n }): { value: unknown; filled: boolean } => {\n let value: unknown\n let has = false\n if (Object.hasOwn(named, p.promptName)) {\n value = named[p.promptName]\n has = true\n } else if (offset + p.prefixLen < positional.length) {\n value = positional[offset + p.prefixLen]\n has = true\n }\n if (positional.length > 0) offset += p.consumes // named-shadow still advances (promotion case)\n return { value, filled: !has }\n }\n\n const consumePlainWidget = (p: {\n promptName: string\n typeName: string\n opts: unknown\n consumes: number\n prefixLen: number\n strict: boolean\n enumValues?: readonly (string | boolean | number)[]\n linkedInput: CanonicalInput | undefined\n }): void => {\n const r = resolveWidgetValue({ promptName: p.promptName, consumes: p.consumes, prefixLen: p.prefixLen })\n const raw = r.filled\n ? defaultValueForWidget({\n type: p.typeName,\n opts: p.opts,\n enumValues: p.enumValues ?? schema.knownUnionByName.get(p.typeName)?.values,\n })\n : r.value\n const value = toPromptValue(raw, { promptName: p.promptName, strict: p.strict })\n if (r.filled) LOG(`${node.type}#${node.id}.${p.promptName} = ${JSON.stringify(value)} (schema-default fill)`)\n if (p.linkedInput?.link != null) widgetFallback.set(p.promptName, value)\n else inputs[p.promptName] = value\n }\n\n /** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */\n const consumeDynamicCombo = (p: { path: string; options: DynamicComboOption[]; defaultKey: string }): void => {\n const r = resolveWidgetValue({ promptName: p.path, consumes: 1, prefixLen: 0 })\n const key = r.filled ? p.defaultKey : r.value\n if (typeof key !== 'string')\n throw new WorkflowConvertError(\n 'invalid-widget-value',\n `node ${node.id}(${node.type}): dynamic combo \"${p.path}\" key is not a string: ${JSON.stringify(key)}`,\n node,\n )\n const opt = p.options.find((o) => o.key === key)\n // own code: usually the template is NEWER than this host's node\n // (version drift, same class as unknown-node), not a garbage value\n if (opt == null)\n throw new WorkflowConvertError(\n 'unknown-dynamic-combo-option',\n `node ${node.id}(${node.type}): \"${key}\" is not an option of dynamic combo \"${p.path}\" (options: ${p.options.map((o) => o.key).join(', ')})`,\n node,\n )\n if (r.filled) LOG(`${node.type}#${node.id}.${p.path} = ${key} (schema-default fill)`)\n inputs[p.path] = key\n for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub)\n }\n\n const consumeBranchInput = (subPath: string, sub: RawInputSpecEntry): void => {\n const kind = classifyWidgetInput({ name: sub.name, type: sub.type, opts: sub.opts })\n // slots and containers materialize as dotted serialized inputs, resolved as links in 2.b\n if (kind.kind === 'slot' || kind.kind === 'dynamic-container') return\n if (kind.kind === 'dynamic-combo')\n return consumeDynamicCombo({ path: subPath, options: kind.options, defaultKey: kind.defaultKey })\n const inlineEnum = Array.isArray(sub.type)\n ? sub.type.filter(\n (v): v is string | number | boolean =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean',\n )\n : undefined\n consumePlainWidget({\n promptName: subPath,\n typeName: typeof sub.type === 'string' ? sub.type : 'COMBO',\n opts: sub.opts,\n consumes: kind.consumes,\n prefixLen: kind.prefixValues.length,\n strict: kind.strictValues,\n enumValues: inlineEnum,\n linkedInput: inputsInNodeJSON.find((i) => i.name === subPath),\n })\n }\n\n for (const field of inputsInNodeSchema) {\n const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy)\n let kind = classifySchemaInput(field)\n // era drift: the file serialized this input widget-backed while the\n // schema now says slot (e.g. forceInput added later) — the file\n // proves a widget value was written, so consume per the file's era\n if (kind.kind === 'slot' && input?.widgetName != null) {\n const legacyConsumes = howManyWidgetValuesForThisInputType(input.type, field.nameInComfy)\n kind = { kind: 'widget', consumes: legacyConsumes === 2 ? 2 : 1, strictValues: true, prefixValues: [] }\n }\n\n if (kind.kind === 'widget') {\n consumePlainWidget({\n promptName: field.nameInComfy,\n typeName: field.typeName,\n opts: field.opts,\n consumes: kind.consumes,\n prefixLen: kind.prefixValues.length,\n strict: kind.strictValues,\n linkedInput: input,\n })\n } else if (kind.kind === 'dynamic-combo') {\n consumeDynamicCombo({ path: field.nameInComfy, options: kind.options, defaultKey: kind.defaultKey })\n } else if (kind.kind === 'dynamic-container') {\n // the declaration itself never appears; the first template.min\n // instances must be connected (backend requires them by name)\n for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {\n const iname = `${field.nameInComfy}.${instName}`\n const inst = inputsInNodeJSON.find((i) => i.name === iname)\n if (inst?.link == null)\n throw new WorkflowConvertError(\n 'missing-required-input',\n `node ${node.id}(${node.type}): autogrow \"${field.nameInComfy}\" requires instance \"${iname}\" connected (template.min = ${kind.requiredCount})`,\n node,\n )\n }\n } else if (!fieldNamesPresent.has(field.nameInComfy)) {\n if (field.required)\n throw new WorkflowConvertError(\n 'missing-required-input',\n `node ${node.id}(${node.type}): required input \"${field.nameInComfy}\" (${field.typeName}) has neither widget value nor link`,\n node,\n )\n }\n }\n\n // 2.b links\n type ParentInfo = { node: CanonicalNode; link: CanonicalLink }\n const getParentNode = (linkId: LiteGraphLinkID): ParentInfo => {\n const link = workflow.links.find((link) => link.id === linkId)\n if (link == null)\n throw new WorkflowConvertError(\n 'dangling-link',\n `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`,\n node,\n )\n const parentNode = workflow.nodes.find((n) => n.id === link.originId)\n if (parentNode == null)\n throw new WorkflowConvertError(\n 'dangling-link',\n `link ${linkId} references a non-existent parent node ${link.originId}`,\n node,\n )\n return { node: parentNode, link }\n }\n\n // mirrors frontend ExecutableNodeDTO._getBypassSlotIndex (verified\n // 2026-07-29, agent/architecture.md \"Bypass passthrough\"): wildcard\n // consumer type short-circuits to the same-slot input; else same-slot\n // preferred when connection-valid against output AND consumer type; else\n // first EXACT consumer-type match; else first wildcard-tolerant match.\n // The pick ignores link-state on purpose — an unlinked winner resolves\n // unconnected, like the frontend's null link.\n const pickBypassInput = (p: {\n inputs: CanonicalInput[]\n outSlot: number\n outputType: string\n consumerType: string\n }): CanonicalInput | null => {\n const sameSlot = p.inputs[p.outSlot]\n if (p.consumerType === '*' || p.consumerType === '') return sameSlot ?? p.inputs[0] ?? null\n if (\n sameSlot != null &&\n linkTypeMatches(sameSlot.type, p.outputType) &&\n linkTypeMatches(sameSlot.type, p.consumerType)\n )\n return sameSlot\n const exact = p.inputs.find((i) => i.type === p.consumerType)\n if (exact != null) return exact\n return (\n p.inputs.find((i) => linkTypeMatches(i.type, p.outputType) && linkTypeMatches(i.type, p.consumerType)) ??\n null\n )\n }\n\n // walk through follow-through parents: Reroute unwraps, bypassed nodes\n // redirect per pickBypassInput above. The match type is RE-DERIVED at\n // each bypass hop from the picked input (frontend resolveOutput calls\n // resolveInput WITHOUT the type param, so the next hop matches on that\n // input's own type); muted parents and dead-end bypasses resolve\n // UNCONNECTED. Visited-set guards link cycles.\n type LinkResolution =\n | { kind: 'link'; nodeId: number; slot: number }\n | { kind: 'primitive'; nodeId: number }\n | { kind: 'unconnected'; reason: string }\n const resolveThroughParents = (startLink: LiteGraphLinkID, consumerType: string): LinkResolution => {\n const visited = new Set<number>()\n let linkId = startLink\n let effectiveType = consumerType\n while (true) {\n const parent: ParentInfo = getParentNode(linkId)\n if (visited.has(parent.node.id))\n throw new WorkflowConvertError(\n 'dangling-link',\n `node ${node.id}(${node.type}): link resolution loops through node ${parent.node.id}`,\n node,\n )\n visited.add(parent.node.id)\n if (parent.node.type === 'Reroute') {\n const rerouteIn = parent.node.inputs[0]?.link\n if (rerouteIn == null) return { kind: 'unconnected', reason: 'reroute chain ends on an empty slot' }\n linkId = rerouteIn\n continue\n }\n if (parent.node.mode === 'muted')\n return { kind: 'unconnected', reason: `parent ${parent.node.id}(${parent.node.type}) is muted` }\n if (parent.node.mode === 'bypassed') {\n const outputType = parent.node.outputs[parent.link.originSlot]?.type ?? parent.link.type\n const through = pickBypassInput({\n inputs: parent.node.inputs,\n outSlot: parent.link.originSlot,\n outputType,\n consumerType: effectiveType,\n })\n if (through?.link == null)\n return {\n kind: 'unconnected',\n reason: `bypassed parent ${parent.node.id}(${parent.node.type}) has no connected ${effectiveType} input to pass through`,\n }\n linkId = through.link\n effectiveType = through.type\n continue\n }\n if (parent.node.type === 'PrimitiveNode') {\n if (!(parent.node.id in PRIMITIVE_VALUES))\n return { kind: 'unconnected', reason: `PrimitiveNode#${parent.node.id} has no widget value` }\n return { kind: 'primitive', nodeId: parent.node.id }\n }\n return { kind: 'link', nodeId: parent.node.id, slot: parent.link.originSlot }\n }\n }\n\n for (const ipt of node.inputs) {\n if (ipt.link == null) {\n LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (widget-backed or optional)`)\n continue\n }\n const resolved = resolveThroughParents(ipt.link, ipt.type)\n if (resolved.kind === 'primitive') {\n // inline primitive nodes as plain values — GUARDED: primitives are\n // scalar widgets, a non-scalar value would cast garbage (or a\n // fake link 2-array) into the prompt\n const pv: unknown = PRIMITIVE_VALUES[resolved.nodeId]\n if (!isPromptScalar(pv))\n throw new WorkflowConvertError(\n 'invalid-widget-value',\n `node ${node.id}(${node.type}): PrimitiveNode#${resolved.nodeId} value is not a scalar: ${JSON.stringify(pv)}`,\n node,\n )\n inputs[ipt.name] = pv\n LOG(`${node.type}#${node.id}.${ipt.name} = ${pv} (inlined primitive)`)\n continue\n }\n if (resolved.kind === 'link') {\n LOG(`${node.type}#${node.id}.${ipt.name} = [${resolved.nodeId}, ${resolved.slot}] (link)`)\n inputs[ipt.name] = [String(resolved.nodeId), resolved.slot]\n continue\n }\n // unconnected: the serialized widget value covers it, else loud when required\n if (widgetFallback.has(ipt.name)) {\n inputs[ipt.name] = widgetFallback.get(ipt.name) ?? null\n LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (widget fallback, ${resolved.reason})`)\n continue\n }\n const field = inputsInNodeSchema.find((f) => f.nameInComfy === ipt.name)\n if (field?.required)\n throw new WorkflowConvertError(\n 'missing-required-input',\n `node ${node.id}(${node.type}): required input \"${ipt.name}\" resolves unconnected (${resolved.reason}) and no widget value covers it`,\n node,\n )\n LOG(`${node.type}#${node.id}.${ipt.name}: resolves unconnected (${resolved.reason})`)\n }\n\n prompt[String(node.id)] = { inputs, class_type: node.type }\n }\n\n return prompt\n}\n\n/** alias cause I keep forgetting about this */\nexport const convertWorkflowToPrompt = convertLiteGraphToPrompt\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","// ComfyUI's own words for a refused prompt. The body carries `error` (what went wrong overall)\n// and `node_errors` (per node, with the offending value), and those sentences are the only\n// thing that says WHICH input the host would not take.\nimport { isRecord } from 'src/utils/isRecord.ts'\n\nfunction str(v: unknown): string {\n return typeof v === 'string' ? v.trim() : ''\n}\n\nexport function describePromptRejection(body: unknown): string {\n if (!isRecord(body)) return 'no reason given'\n const parts: string[] = []\n const err = body['error']\n if (isRecord(err)) {\n const head = str(err['message'])\n const detail = str(err['details'])\n if (head !== '') parts.push(detail === '' ? head : `${head} (${detail})`)\n }\n const nodes = body['node_errors']\n if (isRecord(nodes)) {\n for (const [nodeId, raw] of Object.entries(nodes)) {\n if (!isRecord(raw)) continue\n const list = raw['errors']\n if (!Array.isArray(list)) continue\n for (const e of list) {\n if (!isRecord(e)) continue\n const detail = str(e['details'])\n const msg = str(e['message'])\n parts.push(`node ${nodeId}: ${[msg, detail].filter((x) => x !== '').join(' — ')}`)\n }\n }\n }\n return parts.length === 0 ? 'no reason given' : parts.join(' · ')\n}\n","import type { ExecutionSnapshot } from 'src/runner/ComfyWorkflow.ts'\n\nexport class InvalidPromptError extends Error {\n constructor(\n public override message: string,\n /** exactly what was sent to the host when the error happened */\n public snapshot: ExecutionSnapshot,\n public details: unknown,\n ) {\n super(message)\n }\n}\n","export const palette = {\n primitive: 'var(--comfy-primitive)',\n loader: 'var(--comfy-loader)',\n latent: 'var(--comfy-latent)',\n conditioning: 'var(--comfy-conditioning)',\n sampl: 'var(--comfy-sampl)',\n image: 'var(--comfy-image)',\n}\n\nexport const paletteKeys = Object.keys(palette) as (keyof typeof palette)[]\n\nexport const comfyColors: { [category: string]: string } = {\n loaders: palette.loader,\n latent: palette.latent,\n 'latent/transform': palette.latent,\n conditioning: palette.conditioning, // '#0d430d',\n 'conditioning/style_model': palette.conditioning,\n sampling: palette.sampl,\n image: palette.image,\n primitive: palette.primitive,\n}\n\nexport const getColorForCategory = (_category: string): string | undefined => {\n const category = _category.toLowerCase()\n if (category in comfyColors) return comfyColors[category]\n return 'var(--comfy-default)'\n}\n\n// INPUT ----------------------------------------------------------------\nexport const getColorForInputNameInComfy = (nameInComfy: string): string | undefined => {\n const name = nameInComfy.toLowerCase()\n if (name.includes('width')) return palette.primitive\n if (name.includes('height')) return palette.primitive\n for (const k of paletteKeys) if (name.startsWith(k)) return palette[k]\n return 'var(--comfy-default)'\n}\n\n// OUTPUTS ----------------------------------------------------------------\n","import type { Branded } from 'src/types/index.ts'\n\n/**\n * a fake value that is detected at serialization\n * time to try to magically inject stuff\n * */\nexport type AUTO = Branded<{ ___AUTO___: true }, { AUTO: true }>\n\n/**\n * you can use this as a placeholder anywhere in your graph\n * comfy-ts wires the most recent output of a matching type at serialization time\n */\n// sanctioned cast (agent/coding.md): auto() is a SENTINEL detected at\n// serialization time and replaced by a real link — it never survives to runtime\nexport const auto = <T>(): T => auto_ as T\n\nexport const auto_: AUTO = { ___AUTO___: true } as AUTO\n","import type { ComfyNode } from 'src/graph/ComfyNode.ts'\n\nexport class ComfyNodeOutput<T extends string = string, Ix extends number = number> {\n constructor(\n public node: ComfyNode<object>,\n public slotIx: Ix,\n public type: T,\n /**\n * as of 2024-11-16, output slots have no name in comfy, only a type.\n * Problem is that some nodes have multiple outputs of the same type.\n * so subsequent outputs with a previous used name will be suffixed\n * and have named like `output_2`, `output_3`, etc.\n */\n public name: string,\n ) {}\n}\n","import type { ComfyWorkflow, ProgressReport } from 'src/runner/ComfyWorkflow.ts'\nimport type { NodeProgress } from 'src/runner/ComfyWsApi.ts'\nimport type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport type { NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { ComfyDefaultNodeWhenUnknown_Name } from 'src/sdk-generator/Primitives.ts'\nimport {\n classifySchemaInput,\n containerInstanceSlotType,\n defaultValueForWidget,\n} from 'src/sdk-generator/inputWidgetKind.ts'\nimport type { DynamicComboOption } from 'src/sdk-generator/inputWidgetKind.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { comfyColors } from 'src/utils/ComfyColors.ts'\nimport { auto_ } from 'src/graph/autoValue.ts'\nimport type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'\nimport { NodeSlotSize, NodeTitleHeight, nodeLineHeight } from 'src/graph/NodeSlotSize.ts'\n\ntype NodeExecutionStatus = 'executing' | 'done' | 'error' | 'waiting' | 'cached' | null\n\nconst isScalarValue = (x: unknown): x is string | number | boolean =>\n typeof x === 'string' || typeof x === 'number' || typeof x === 'boolean'\n\nexport type NodePort = {\n id: string\n label: string\n width: number\n height: number\n type: string\n x: number\n y: number\n toNode?: ComfyNode<object, object> | undefined\n fromNode?: ComfyNode<object, object> | undefined\n}\n\nexport type ComfyNodeUID = string\n\n/** ComfyNode\n * - correspond to a signal in the graph\n * - belongs to a script\n */\nexport class ComfyNode<\n //\n ComfyNode_input extends object = object,\n ComfyNode_output extends object = object,\n> {\n storeAs(storeName: string): this {\n this.meta.storeAs = storeName\n return this\n }\n\n tag(tagName: string): this {\n this.addTag(tagName)\n return this\n }\n\n addTag(tag: string): this {\n if (this.meta.tags == null) this.meta.tags = [tag]\n else this.meta.tags.push(tag)\n return this\n }\n // ---------------------------------------\n\n /** reported though websocket by ComfyUI */\n status: NodeExecutionStatus = null\n\n /** last raw progress message reported by comfy */\n progress: NodeProgress | null = null\n\n /**\n * updated on websocket progress report from the progress property just above\n * between [0, 1]\n * */\n progressRatio: number = 0\n\n get progressReport(): ProgressReport {\n const percent = this.status === 'done' ? 100 : this.progressRatio * 100\n const isDone = this.status === 'done'\n return { percent, isDone, countDone: this.progressRatio * 100, countTotal: 100 }\n }\n\n $schema: ComfyNodeSchema\n updatedAt: number = Date.now()\n json: ComfyApiNodeJson\n\n get isExecuting(): boolean {\n return this.status === 'executing'\n }\n\n disabled: boolean = false\n\n disable(): void {\n this.disabled = true\n }\n\n get inputs(): ComfyNode_input {\n // sanctioned cast (agent/coding.md): runtime graph json <-> generated\n // static face; both derive from the same object_info\n return this.json.inputs as ComfyNode_input\n }\n\n /** update a node */\n set(p: Partial<ComfyNode_input>): this {\n for (const [key, value] of Object.entries(p)) {\n const next = this.serializeValue(key, value)\n const prev = this.json.inputs[key]\n if (next === prev) continue\n this.json.inputs[key] = next as any // 🔴\n }\n return this\n // 🔴 wrong resonsibility\n // console.log('CHANGES', changes)\n }\n\n get color(): string {\n return comfyColors[this.$schema.category] ?? '#aaa'\n }\n\n uidNumber: number\n $outputs: ComfyNodeOutput<string>[] = []\n outputs: ComfyNode_output\n uidPrefixed: string\n\n constructor(\n public graph: ComfyWorkflow,\n public uid: ComfyNodeUID, // = graph.getUID(),\n jsonExt: ComfyApiNodeJson,\n public meta: ComfyNodeMetadata = {},\n ) {\n // strictly-numeric uids keep uid === uidNumber (litegraph export must agree\n // with prompt keys); anything else gets the next free number ('12abc' must\n // NOT partial-parse to 12 — that collides with node '12')\n const parsedUid = /^\\d+$/.test(uid) ? Number(uid) : Number.NaN\n this.uidNumber = Number.isNaN(parsedUid) ? this.graph._uidNumber++ : parsedUid\n if (this.uidNumber >= this.graph._uidNumber) this.graph._uidNumber = this.uidNumber + 1\n if (jsonExt == null) throw new Error('invariant violation: jsonExt is null')\n // this.json = graph.data.apiJson[uid]\n // if (this.json == null) graph.data.apiJson = {}\n // console.log('CONSTRUCTING', xxx.class_type, uid)\n\n // this.uidNumber = parseInt(uid) // 🔴 ugly\n const exactSchema = graph.schema.nodesByNameInComfy[jsonExt.class_type]\n if (exactSchema == null) {\n // loud fallback: imported json referencing a node this host doesn't have\n graph.recordProblem(\n `unknown node type \"${jsonExt.class_type}\" — schema fallback to ${ComfyDefaultNodeWhenUnknown_Name}; install the missing custom node on the host`,\n )\n }\n this.$schema = exactSchema ?? graph.schema.nodesByNameInComfy[ComfyDefaultNodeWhenUnknown_Name]!\n\n if (this.$schema == null) {\n console.log(`❌ available nodes:`, Object.keys(graph.schema.nodesByNameInComfy).join(','))\n throw new Error(`❌ no schema found for node \"${jsonExt.class_type}\"`)\n // throw new Error('')\n }\n this.uidPrefixed = `${this.$schema.nodeKey}_${this.uidNumber}`\n let ix = 0\n\n // 🔶 1 this declare the json locally,\n // but Node are not live instances, they're local subinstances to a LiveGraph\n this.json = this._convertPromptExtToPrompt(jsonExt)\n // 🔶 2 so we need to ensure the json is properly synced with the LiveGraph data\n // register node ensure this\n this.graph.registerNode(this)\n\n // dynamically add properties for every outputs\n const outputs: { [key: string]: any } = {}\n for (const x of this.$schema.outputs) {\n const output = new ComfyNodeOutput(this, ix++, x.typeName, x.nameInComfy)\n outputs[x.outKey] = output\n this.$outputs.push(output)\n // console.log(` - .${x.outKey} as ComfyNodeOutput(${ix})`)\n }\n this.outputs = outputs as ComfyNode_output\n\n // implements the _<typeName> properties (HasSingle interfaces)\n const extensions: { [key: string]: any } = {}\n for (const x of this.$schema.singleOutputs) {\n extensions[`_${x.typeName}`] = outputs[x.outKey]\n }\n Object.assign(this, extensions)\n }\n\n _convertPromptExtToPrompt(promptExt: ComfyApiNodeJson): ComfyApiNodeJson {\n const inputs: { [inputName: string]: any } = {}\n const _done = new Set<string>()\n /** every dotted key of every branch: the selected ones are written here, the rest are dropped */\n const _comboBranchKeys = new Set<string>()\n for (const i of this.$schema.inputs) {\n _done.add(i.nameInComfy)\n const kind = classifySchemaInput(i)\n if (kind.kind === 'dynamic-combo') {\n this._writeDynamicCombo({\n name: i.nameInComfy,\n options: kind.options,\n defaultKey: kind.defaultKey,\n provided: promptExt.inputs,\n out: inputs,\n claimed: _comboBranchKeys,\n })\n continue\n }\n const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy])\n // absent optionals (autogrow containers included) stay OUT of the\n // prompt: an `undefined` value would already be dropped by JSON\n // serialization, keeping the key would only lie to Object.keys\n if (value !== undefined) inputs[i.nameInComfy] = value\n }\n for (const [nameInComfy, rawVal] of Object.entries(promptExt.inputs)) {\n if (_done.has(nameInComfy) || _comboBranchKeys.has(nameInComfy)) continue\n const value = this.serializeValue(nameInComfy, rawVal)\n inputs[nameInComfy] = value\n }\n return { class_type: this.$schema.nameInComfy, inputs }\n }\n\n /** dynamic combo → the key plus ONLY the selected branch's dotted inputs, absent ones\n * filled from the schema (agent/architecture.md, dynamic-combo fill). The host declares\n * those branch inputs required and default-fills none of them */\n private _writeDynamicCombo(p: {\n name: string\n options: DynamicComboOption[]\n defaultKey: string\n provided: { [k: string]: unknown }\n out: { [k: string]: any }\n claimed: Set<string>\n }): void {\n for (const opt of p.options) for (const e of opt.inputs) p.claimed.add(`${p.name}.${e.name}`)\n const raw = p.provided[p.name]\n const key = typeof raw === 'string' ? raw : p.defaultKey\n const branch = p.options.find((o) => o.key === key)\n if (branch == null) {\n const known = p.options.map((o) => o.key).join(', ')\n console.error(`🔴 unknown \"${p.name}\" option ${JSON.stringify(key)} (known: ${known})`)\n this.graph.recordProblem(\n `🔴 unknown \"${p.name}\" option ${JSON.stringify(key)} on ${this.$schema.nodeKey}#${this.uid} (known: ${known})`,\n )\n return\n }\n p.out[p.name] = key\n for (const e of branch.inputs) {\n const dotted = `${p.name}.${e.name}`\n const given = p.provided[dotted]\n p.out[dotted] =\n given === undefined\n ? defaultValueForWidget({\n type: typeof e.type === 'string' ? e.type : 'COMBO',\n opts: e.opts,\n enumValues: Array.isArray(e.type) ? e.type.filter(isScalarValue) : undefined,\n })\n : this.serializeValue(dotted, given)\n }\n }\n\n /** return the list of nodes piped into this node */\n _incomingNodes(): ComfyNodeId[] {\n const incomingNodes: ComfyNodeId[] = []\n for (const [_name, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) {\n const [from, _slotIx] = val\n incomingNodes.push(from)\n }\n }\n return incomingNodes\n }\n\n _primitives(): { inputName: string; value: string }[] {\n const primitives: { inputName: string; value: string }[] = []\n for (const [inputName, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) continue\n primitives.push({ inputName: inputName, value: val?.toString() })\n }\n return primitives\n }\n\n /** return true if the given node is plugged into this one */\n isChildrenOf(node: ComfyNode<any>): boolean {\n return this._incomingNodes().includes(node.uid)\n }\n\n get parents(): ComfyNode<any>[] {\n return this._incomingNodes().map((id) => this.graph.getNode(id)!)\n }\n // get children(): ComfyNode<any>[] {\n // return this._incomingNodes().map((id) => this.graph.getNode(id)!)\n // }\n\n _visible: boolean = true\n set visible(value: boolean) {\n this._visible = value\n } // biome-ignore format: misc\n get visible(): boolean {\n return this._visible\n } // biome-ignore format: misc\n\n _x: number = 0\n get x(): number {\n return this._x\n } // biome-ignore format: misc\n set x(value: number) {\n this.isDirty = true\n this._x = value\n }\n\n _y: number = 0\n get y(): number {\n return this._y\n } // biome-ignore format: misc\n set y(value: number) {\n this.isDirty = true\n this._y = value\n }\n\n isDirty = true\n\n tagDirty(value: boolean): void {\n this.isDirty = value\n }\n\n col: number = 0\n selected: boolean = false\n get outgoingPorts(): NodePort[] {\n return this.$outputs.map(\n (o, ix): NodePort => ({\n id: this.uid + '#' + o.slotIx,\n label: o.type,\n width: NodeSlotSize,\n height: NodeSlotSize,\n fromNode: this,\n toNode: o.node ?? undefined,\n type: o.type,\n x: this.x + this.width, // + NodeSlotSize / 2,\n y:\n this.y + // start\n NodeTitleHeight + // title\n ix * nodeLineHeight + // e.fromSlotIx * 10,\n nodeLineHeight / 2, //\n }),\n )\n }\n\n get incomingPorts(): NodePort[] {\n return this._incomingEdges().map(\n (e, ix): NodePort => ({\n id: this.uid + '<-' + e.from + '#' + e.fromSlotIx,\n width: NodeSlotSize,\n height: NodeSlotSize,\n fromNode: this.graph.getNode(e.from) ?? undefined,\n toNode: this,\n label: e.inputName,\n type: e.type,\n x: this.x, // - NodeSlotSize / 2,\n y:\n this.y + // start\n NodeTitleHeight + // title\n ix * nodeLineHeight + // e.fromSlotIx * 10,\n nodeLineHeight / 2,\n }),\n )\n }\n\n _incomingEdges(): {\n from: ComfyNodeId\n inputName: string\n type: string\n fromSlotIx: number\n }[] {\n const incomingEdges: {\n from: ComfyNodeId\n inputName: string\n fromSlotIx: number\n type: string\n }[] = []\n\n for (const [inputName, val] of Object.entries(this.inputs)) {\n if (Array.isArray(val)) {\n const [from, _slotIx] = val as [ComfyNodeId, number]\n const type = this.graph.getNode(from)?.$outputs[_slotIx]?.type ?? 'UNKNOWN'\n incomingEdges.push({ from, inputName, fromSlotIx: _slotIx, type })\n }\n }\n return incomingEdges\n }\n\n /** number of primitive fields in this node */\n primitivesCount(): number {\n return Object.values(this.inputs).filter((val) => !Array.isArray(val)).length\n }\n\n /** width dimensions for autolayout algorithm */\n get width(): number {\n return 200\n }\n\n /** height dimensions for autolayout algorithm */\n get height(): number {\n const inputLen = this._incomingEdges().length\n const outputLen = this.$schema.outputs.length\n const headerCount = Math.max(inputLen, outputLen)\n\n // max height since some nodes have many invisible inputs\n return (this.primitivesCount() + headerCount + 1) * nodeLineHeight\n }\n\n serializeValue(field: string, value: unknown): unknown {\n if (value == null) {\n const schema = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === field)\n if (schema == null) throw new Error(`❌ no schema for field \"${field}\" (of node ${this.$schema.nodeKey})`)\n // console.log('def1=', field, schema.opts.default)\n const opts = schema.opts == null || typeof schema.opts !== 'object' ? undefined : schema.opts\n if (opts?.default != null) return opts.default\n // console.log('def2=', field, schema.required)\n if (!schema.required) return undefined\n console.error(field, 'is required but value is ', value, this.json) //, this)\n this.graph.recordProblem(\n `🔴 [serializeValue] field \"${field}\" (of node ${this.$schema.nodeKey}#${this.uid}) value is null but field is not optional`,\n )\n return undefined\n // throw new Error(\n // `🔴 [serializeValue] field \"${field}\" (of node ${this.$schema.nodeKey}#${this.uid}) value is null`,\n // )\n }\n if (typeof value === 'function') {\n return this.serializeValue(field, value(this.graph.builder, this.graph))\n }\n if (value === auto_) {\n const expectedType = this._getExpectedTypeForField(field)\n console.info(`🔍 looking for type ${expectedType} for field ${field}`)\n for (const node of this.graph.nodes.slice().reverse()) {\n const output = node._getOutputForTypeOrNull(expectedType)\n if (output != null) return [node.uid, output.slotIx]\n }\n throw new Error(`🔴 [AUTO failed] field \"${field}\" (of node ${this.$schema.nodeKey}) value is null`)\n }\n if (value instanceof ComfyNodeOutput) return [value.node.uid, value.slotIx]\n if (value instanceof ComfyNode) {\n const expectedType = this._getExpectedTypeForField(field)\n const output = value._getOutputForTypeOrCrash(expectedType)\n return [value.uid, output.slotIx]\n }\n return value\n }\n\n private _getExpectedTypeForField(name: string): string {\n const input = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name)\n if (input != null) return input.typeName\n // autogrow instance key `decl.<instance>`: the container template carries the slot type\n const dot = name.indexOf('.')\n const decl =\n dot > 0 ? this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name.slice(0, dot)) : undefined\n if (decl != null) {\n const kind = classifySchemaInput(decl)\n const slotType = containerInstanceSlotType(decl.opts)\n if (kind.kind === 'dynamic-container' && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null)\n return slotType\n }\n throw new Error(\n `🔴 no input \"${name}\" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`,\n )\n }\n\n private _getOutputForTypeOrCrash(type: string): ComfyNodeOutput<any> {\n const i: NodeOutputExt = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)!\n const val = (this.outputs as any)[i.outKey]\n // console.log(`this[i.name] = ${this.$schema.name}[${i.name}] = ${val}`)\n if (val instanceof ComfyNodeOutput) return val\n throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)\n }\n\n private _getOutputForTypeOrNull(type: string): ComfyNodeOutput<any> | null {\n const i: Maybe<NodeOutputExt> = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)\n if (i == null) return null\n const val = (this.outputs as any)[i.outKey]\n if (val == null) return null\n if (val instanceof ComfyNodeOutput) return val\n throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)\n }\n}\n","import { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\n\n/**\n * runtime builder: one factory method per node of the live schema, defined\n * dynamically. The typed face is `SdkForHost<ID>['Builder']`, obtained via\n * `workflow.builder` (see ComfyWorkflow). The index signature below is what\n * makes the cast between the two legal.\n */\nexport interface ComfyWorkflowBuilder {\n [nodeName: string]: unknown\n}\nexport class ComfyWorkflowBuilder {\n constructor(public graph: ComfyWorkflow) {\n const schema = graph.host.schema\n\n for (const node of schema.nodes) {\n try {\n Object.defineProperty(this, node.nodeKey, {\n value: (inputs: ComfyApiNodeJson['inputs'], meta?: ComfyNodeMetadata) => {\n const uidString = this.___allocateNodeUID(meta)\n const nodePayload: ComfyApiNodeJson = {\n class_type: node.nameInComfy,\n inputs,\n }\n return new ComfyNode(graph, uidString, nodePayload, meta ?? {})\n },\n })\n } catch (e) {\n console.log(e)\n console.error('impossible to create builder for node')\n console.log(`current:`, JSON.stringify(node.nameInComfy), JSON.stringify(node.nodeKey))\n const prev = schema.nodes.find((n) => n.nodeKey === node.nodeKey)\n console.log(`prev`, JSON.stringify(prev?.nameInComfy), JSON.stringify(prev?.nodeKey))\n throw e\n }\n }\n }\n\n /**\n * helper function to allocate an unique node Id while\n * while respecting user provided metadata id if present.\n */\n private ___allocateNodeUID(meta?: ComfyNodeMetadata): string {\n let uidString: string\n if (meta?.id != null && meta.id !== '') {\n // increment the graph _uiNumber, so if we modify this later\n // we won't reuse the same uid and have broken conflicts\n const uidNumber = parseInt(meta.id, 10)\n if (!Number.isNaN(uidNumber) && uidNumber > this.graph._uidNumber)\n this.graph._uidNumber = Math.round(uidNumber + 1)\n uidString = meta.id\n } else {\n uidString = (this.graph._uidNumber++).toString()\n }\n return uidString\n }\n}\n","import type { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { classifySchemaInput } from 'src/sdk-generator/inputWidgetKind.ts'\nimport type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'\nimport type { LiteGraphLinkTuple } from 'src/litegraph/LiteGraphLink.ts'\nimport { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'\nimport type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'\nimport type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'\nimport type { LiteGraphNodeOutput } from 'src/litegraph/LiteGraphNodeOutput.ts'\nimport { asLiteGraphSlotIndex } from 'src/litegraph/LiteGraphSlotIndex.ts'\n\nexport const convertFlowToLiteGraphJSON = (graph: ComfyWorkflow): LiteGraphJSON => {\n const ctx = new LiteGraphCtx(graph)\n const last_node_id = Math.max(...graph.nodes.map((n) => n.uidNumber))\n const xxx = graph.nodes.map((comfyNode) => ({\n liteGraphNode: convertNodeToLiteGraphNode(ctx, comfyNode),\n comfyNode,\n }))\n for (const xx of xxx) {\n const n = xx.liteGraphNode\n n.pos[0] = bang(xx.comfyNode.x)\n n.pos[1] = bang(xx.comfyNode.y)\n for (const o of n.outputs ?? []) {\n o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0])\n }\n }\n return {\n last_node_id,\n last_link_id: ctx.nextLinkId,\n nodes: xxx.map((n) => n.liteGraphNode),\n links: ctx.links,\n config: {},\n extra: {},\n groups: [],\n version: 0.4,\n }\n}\n\nconst convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): LiteGraphNode => {\n const inputs: LiteGraphNodeInput[] = []\n const widgets_values: unknown[] = []\n for (const ipt of node.$schema.inputs) {\n const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy])\n const kind = classifySchemaInput(ipt)\n if (_isLink(raw)) {\n const nodeUidNumber = bang(\n ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber,\n `link target node \"${raw[0]}\" not found in graph`,\n )\n inputs.push({\n name: ipt.nameInComfy,\n type: ipt.typeName,\n // target_slot = index within THIS node's litegraph inputs array,\n // not the schema input index (widget inputs are not litegraph slots)\n link: ctx.allocateLink(\n nodeUidNumber,\n raw[1],\n node.uidNumber,\n asLiteGraphSlotIndex(inputs.length),\n ipt.typeName,\n ),\n })\n } else if (kind.kind === 'widget') {\n // frontend button-widget values ride BEFORE the real value (LOAD_3D)\n widgets_values.push(...kind.prefixValues, raw)\n // control_after_generate phantom AFTER the value: the classifier's\n // consumes covers prefix + value + control, config-driven (the 2024\n // INT-named-seed heuristic lives inside controlConsumes), so export\n // and import can never disagree on the run length\n const phantoms = kind.consumes - 1 - kind.prefixValues.length\n for (let i = 0; i < phantoms; i++) widgets_values.push(false)\n } else {\n // unconnected link-kind input: a litegraph slot with no link —\n // NEVER a widget value (that would misalign the round-trip import)\n inputs.push({ name: ipt.nameInComfy, type: ipt.typeName, link: null })\n }\n }\n const outputs = node.$schema.outputs.map(\n (i, ix): LiteGraphNodeOutput => ({\n // ❌9 name: i.nameInComfy,\n type: i.typeName,\n links: [], // empty links by default 🔴\n slot_index: asLiteGraphSlotIndex(ix),\n name: i.outKey,\n }),\n )\n return {\n type: node.$schema.nameInComfy,\n id: node.uidNumber,\n inputs,\n outputs,\n pos: [0, 0],\n size: [node.width, node.height],\n widgets_values,\n }\n}\n\nconst _isLink = (v: unknown): v is [string, number] => {\n return Array.isArray(v) && v.length === 2 && typeof v[0] === 'string' && typeof v[1] === 'number'\n}\n\nexport class LiteGraphCtx {\n constructor(public graph: ComfyWorkflow) {}\n nextLinkId: number = 0\n links: LiteGraphLinkTuple[] = []\n allocateLink = (\n fromNodeId: number,\n fromNodeOutputIx: number,\n toNodeId: number,\n toNodeInputIx: number,\n linkType: string,\n ): LiteGraphLinkID => {\n const linkId = asLiteGraphLinkID(++this.nextLinkId)\n this.links.push([linkId, fromNodeId, fromNodeOutputIx, toNodeId, toNodeInputIx, linkType])\n return linkId\n }\n}\n","/**\n * local output naming, relative to `.comfy-ts/outputs/`:\n * the server filename is NOT unique — cloud hosts reset the\n * `_00001_` counter every run, so trusting it overwrote the same file — and\n * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name\n * prefix. Local names are ours: dir from the prompt's own filename_prefix\n * (or an explicit save.prefix override), then\n * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically\n * per stem and nothing ever collides.\n */\nexport const localOutputPath = (p: {\n /** explicit local dir override (SaveOptions.prefix) — wins when set */\n localDir?: string\n /** the SaveImage node's own filename_prefix as sent in the prompt */\n filenamePrefix?: string\n /** server-reported subfolder (fallback when no prefix is known) */\n subfolder: string\n /** server-reported filename, e.g. krea_00001_.png */\n filename: string\n /** run timestamp, YYYYMMDD-HHmmss */\n timestamp: string\n}): string => {\n // server name → stem / counter / extension: `krea_00001_.png`\n const dot = p.filename.lastIndexOf('.')\n const ext = dot === -1 ? '' : p.filename.slice(dot)\n const base = dot === -1 ? p.filename : p.filename.slice(0, dot)\n const counterMatch = /_(\\d+)_$/.exec(base)\n const counter = counterMatch?.[1]\n const serverStem = counterMatch != null ? base.slice(0, base.length - counterMatch[0].length) : base\n\n // directory + stem intent: explicit local dir > prompt prefix > server\n // layout. The stem SURVIVES a localDir override — identity keeps sorting\n let dir: string\n let stem: string\n if (p.filenamePrefix != null && p.filenamePrefix !== '') {\n const slash = p.filenamePrefix.lastIndexOf('/')\n dir = slash === -1 ? '' : p.filenamePrefix.slice(0, slash)\n stem = slash === -1 ? p.filenamePrefix : p.filenamePrefix.slice(slash + 1)\n } else {\n dir = p.subfolder\n stem = serverStem\n }\n if (p.localDir != null) dir = p.localDir\n\n const name = [stem === '' ? null : stem, p.timestamp, counter].filter((x) => x != null).join('_') + ext\n return dir === '' ? name : `${dir}/${name}`\n}\n\n/** REPLACE the extension (never append one): a re-encoded save owns its whole\n * name now that local naming is ours, so `save: {format:'image/webp'}` writes\n * `shot_20260731-154210_00001.webp`, not `…_00001.png.webp` — appending\n * described the bytes twice and the first description was a lie */\nexport const withExtension = (path: string, ext: string): string => {\n const slash = path.lastIndexOf('/')\n const dot = path.lastIndexOf('.')\n const stem = dot > slash ? path.slice(0, dot) : path\n return `${stem}.${ext}`\n}\n\n/**\n * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR\n * was already CLAIMED by a still-downloading retrieval (two same-second runs\n * on a counter-resetting cloud host compute the same name).\n * The chosen path is claimed before returning.\n */\nexport const uniquifyOutputPath = (p: {\n path: string\n exists: (path: string) => boolean\n claimed: Set<string>\n}): string => {\n let out = p.path\n if (p.exists(out) || p.claimed.has(out)) {\n const dot = out.lastIndexOf('.')\n const stem = dot === -1 ? out : out.slice(0, dot)\n const ext = dot === -1 ? '' : out.slice(dot)\n for (let n = 2; p.exists(out) || p.claimed.has(out); n++) out = `${stem}-${n}${ext}`\n }\n p.claimed.add(out)\n return out\n}\n\n/** YYYYMMDD-HHmmss, local time — sortable, text-encodable, no colons for filesystems */\nexport const runTimestamp = (d: Date): string => {\n const pad = (n: number): string => String(n).padStart(2, '0')\n return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`\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","// sharp is node-only; the web graph must never carry it (architecture item 13).\n// The import specifier is a VARIABLE on purpose: bundlers cannot statically\n// chase it, so browser builds of comfy-ts/web don't try to resolve sharp —\n// in a browser the import throws at runtime and callers get the loud error.\nimport type SharpNS from 'sharp'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\n\nexport type SharpModule = typeof SharpNS\n\nlet cached: SharpModule | null = null\n\nexport async function importSharp(reason: string): Promise<SharpModule> {\n if (cached != null) return cached\n const specifier = 'sharp'\n try {\n const mod = (await import(specifier)) as { default: SharpModule }\n cached = mod.default\n return cached\n } catch (e) {\n throw new Error(\n `sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`,\n { cause: e },\n )\n }\n}\n","// #region Safety\nexport type Flavor<T, FlavorT> = T & { __tag?: FlavorT }\nexport type Tagged<O, Tag> = O & { __tag?: Tag }\nexport type Branded<O, Brand extends { [key: string]: true }> = O & Brand\n\n// #region Utils\nexport type Maybe<T> = T | null | undefined\n/**\n * Make some keys optional\n * Usage: PartialOmit<{ a: string, b: string }, 'a'> -> { a?: string, b: string }\n */\nexport type PartialOmit<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>\nexport type IsEqual<T, S> = [T] extends [S] ? ([S] extends [T] ? true : false) : false\nexport type EmptyRecord = Record<never, never>\n\n// #region Misc\nexport type number_Timestamp = Tagged<number, 'Timestamp'>\n\n// #region Paths\nexport type AbsolutePath = Tagged<string, { AbsolutePath: true }>\nexport type RelativePath = Tagged<string, { RelativePath: true }>\nexport const asAbsolutePath = (path: string): AbsolutePath => path as AbsolutePath\nexport const asRelativePath = (path: string): RelativePath => path as RelativePath\n\n// #region Image\nexport type ConvertibleImageFormat = 'image/png' | 'image/jpeg' | 'image/webp' | 'raw'\n/** local disk saving is OPT-IN per run: `save: true` = raw bytes, an object re-encodes/relocates */\nexport type SaveOptions = {\n /** 'raw' (default) writes the bytes untouched; an image/* mime re-encodes through sharp */\n format?: ConvertibleImageFormat\n /** local dir under `.comfy-ts/outputs/` (wins over the prompt's own filename_prefix) */\n prefix?: string\n /** 0..1, re-encode only */\n quality?: number\n}\n\n// #region Either\nexport type Either<L, R> = { success: false; value: L } | { success: true; value: R }\nexport const resultSuccess = <T>(value: T): Either<never, T> => ({ success: true, value })\nexport const resultFailure = <T>(value: T): Either<T, never> => ({ success: false, value })\n\n// #region Result\nexport type ResultFailure = { success: false; message: string; error: unknown; value: undefined }\nexport type Result<R> = { success: true; value: R } | ResultFailure\nexport const __OK = <T>(value: T): Result<T> => ({ success: true, value })\nexport const __FAIL = (message: string, error?: unknown): Result<any> => ({\n success: false,\n message,\n error,\n value: undefined,\n})\n\n// #region Markdown\nexport type MDContent = Branded<string, { MDContent: true }>\nexport const asMDContent = (s: string): MDContent => s as MDContent\n\n// #region HTML\nexport type HTMLContent = Branded<string, { HTML: true }>\nexport const asHTMLContent = (s: string): HTMLContent => s as HTMLContent\n","import { type Either, resultFailure, resultSuccess } from 'src/types/index.ts'\n\nexport type TextChunks = {\n [key: string]: string\n}\n\nexport const getPngMetadataFromUint8Array = (pngData: Uint8Array): Either<string, TextChunks> => {\n const dataView = new DataView(\n pngData.buffer,\n pngData.byteOffset, // <-- it just doesn't work without this\n pngData.byteLength, // <-- it just doesn't work without this\n )\n\n // console.log('🟢', dataView.getUint32(0))\n // console.log('🟢', dataView)\n\n // Check that the PNG signature is present\n if (dataView.getUint32(0) !== 0x89504e47) {\n // 🔴 showErrorMessage('Not a valid PNG file')\n return resultFailure('Not a valid PNG file')\n }\n\n // Start searching for chunks after the PNG signature\n let offset = 8\n\n const txt_chunks: TextChunks = {}\n\n // Loop through the chunks in the PNG file\n while (offset < pngData.length) {\n // Get the length of the chunk\n const length = dataView.getUint32(offset)\n // Get the chunk type\n const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8))\n if (type === 'tEXt') {\n // Get the keyword\n let keyword_end = offset + 8\n while (pngData[keyword_end] !== 0) {\n keyword_end++\n }\n const keyword = String.fromCharCode(...pngData.slice(offset + 8, keyword_end))\n // Get the text\n const contentArraySegment = pngData.slice(keyword_end + 1, offset + 8 + length)\n const contentJson = Array.from(contentArraySegment)\n .map((s) => String.fromCharCode(s))\n .join('')\n txt_chunks[keyword] = contentJson\n }\n\n offset += 12 + length\n }\n\n return resultSuccess(txt_chunks)\n}\n","/* please, keep this file as minimal as possible; it's imported by many apps */\nexport function exhaust(x: never): never {\n return x\n}\n","// 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","import { sha1Hex } from 'src/utils/sha1.ts'\n\nexport const hashArrayBuffer = (buffer: Uint8Array): string => {\n return sha1Hex(buffer)\n}\n","import { type } from 'arktype'\nimport type { Maybe, Tagged } from 'src/types/index.ts'\n\n// #region ComfyNodeID\nexport type ComfyNodeId = Tagged<string, 'ComfyNodeId'>\nexport const ComfyNodeId_ark = type.string.as<ComfyNodeId>()\n\n// #region ComfyNodeMetadata\nexport type ComfyNodeMetadata = {\n id?: Maybe<ComfyNodeId>\n\n tag?: string\n\n /** list of tags;\n * those tags will be copied to assets generated by this node.\n * e.g. you can add tags to SaveImage or PreviewImage to automatically tag images they'll produce. */\n tags?: string[]\n\n /** If the node produces an image, image will be stored in an ImageStore with given name.\n * ImageStore are useful for example to always have access to the image when re-running a workflow despite ComfyUI caching. */\n storeAs?: string\n}\nexport const ComfyNodeMetadata_ark = type({\n 'id?': ComfyNodeId_ark,\n 'tag?': 'string',\n 'tags?': 'string[]',\n 'storeAs?': 'string',\n}).as<ComfyNodeMetadata>()\n","import { scope, type } from 'arktype'\nimport { ComfyNodeId_ark } from 'src/graph/ComfyNodeID.ts'\nimport type { Tagged } from 'src/types/index.ts'\n\n/** the id ComfyUI assigns to one queued execution (wire-level name kept) */\nexport type PromptID = Tagged<string, { PromptID: true }>\nexport const PromptID_ark = type.string.as<PromptID>()\n\n// Define the scope and export its types for inference\nconst tempScope = scope({\n PromptID: PromptID_ark,\n ComfyNodeID: ComfyNodeId_ark, // Use the aliased schema\n Timestamp: 'number', // Define Timestamp directly in the scope\n\n ApiPromptInput: {\n client_id: 'string',\n extra_data: { extra_pnginfo: 'unknown' },\n prompt: 'unknown',\n },\n\n NodeProgress: { value: 'number', max: 'number' },\n\n ComfyStatusData: {\n 'sid?': 'string',\n status: {\n exec_info: { queue_remaining: 'number' },\n 'sid?': 'string',\n },\n },\n WsMsgStatus: {\n type: \"'status'\",\n data: 'ComfyStatusData',\n },\n\n _WsMsgExecutionStartData: { prompt_id: 'PromptID' },\n WsMsgExecutionStart: {\n type: \"'execution_start'\",\n data: '_WsMsgExecutionStartData',\n },\n\n _WsMsgExecutionCachedData: { nodes: 'ComfyNodeID[]', prompt_id: 'PromptID' },\n WsMsgExecutionCached: {\n type: \"'execution_cached'\",\n data: '_WsMsgExecutionCachedData',\n },\n\n // node is null on the final 'executing' message (prompt done)\n _WSMsgExecutingData: {\n prompt_id: 'PromptID',\n 'node?': 'ComfyNodeID | null',\n },\n WsMsgExecuting: {\n type: \"'executing'\",\n data: '_WSMsgExecutingData',\n },\n\n ComfyImageInfo: {\n filename: 'string',\n subfolder: 'string',\n type: 'string',\n },\n _WsMsgExecutedData: {\n node: 'ComfyNodeID',\n output: {\n 'previews?': [{ filepath: 'string' }, '[]'],\n 'images?': 'ComfyImageInfo[]',\n // ui payload of a text output node (PreviewAny, and how TextGenerate\n // results reach the client); entries are soft, non-strings are dropped\n 'text?': 'unknown[]',\n },\n prompt_id: 'PromptID',\n },\n WsMsgExecuted: {\n type: \"'executed'\",\n data: '_WsMsgExecutedData',\n },\n\n WsMsgExecutionSuccessData: {\n prompt_id: 'PromptID',\n timestamp: 'Timestamp',\n },\n WsMsgExecutionSuccess: {\n type: \"'execution_success'\",\n data: 'WsMsgExecutionSuccessData',\n },\n\n _WsMsgExecutionErrorData: {\n prompt_id: 'PromptID',\n node_id: 'ComfyNodeID',\n node_type: 'string',\n executed: 'ComfyNodeID[]',\n exception_message: 'string',\n exception_type: 'string',\n traceback: 'string[]',\n current_inputs: 'Record<string, unknown>',\n current_outputs: 'Record<string, unknown>',\n },\n WsMsgExecutionError: {\n type: \"'execution_error'\",\n data: '_WsMsgExecutionErrorData',\n },\n\n WSMsgManagerFeedbackData: { data: 'string' },\n WSMsgManagerFeedback: {\n type: \"'manager-terminal-feedback'\",\n data: 'WSMsgManagerFeedbackData',\n },\n\n // server console stream (/internal/logs): entries are WRITE CHUNKS, not lines\n LogEntry: { t: 'string', m: 'string' },\n _WsMsgLogsData: { entries: 'LogEntry[]', 'size?': 'unknown' },\n WsMsgLogs: {\n type: \"'logs'\",\n data: '_WsMsgLogsData',\n },\n\n // WsMsgProgress must be after NodeProgress\n WsMsgProgress: { type: \"'progress'\", data: 'NodeProgress' },\n\n // per-node progress map (ComfyUI ≥ 0.3.x)\n _WsMsgProgressStateData: {\n prompt_id: 'PromptID',\n nodes: 'Record<string, unknown>',\n },\n WsMsgProgressState: {\n type: \"'progress_state'\",\n data: '_WsMsgProgressStateData',\n },\n\n // UNION TYPES\n PromptRelated_WsMsg:\n 'WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess',\n WsMsg: 'WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg',\n})\n\nexport const types = tempScope.export()\n\n// REQUEST PAYLOADS ------------------------------------------------\nexport type ApiPromptInput = typeof types.ApiPromptInput.infer\n\n// MISC -------------------------------------------------------------\nexport type NodeProgress = typeof types.NodeProgress.infer\n\n// LIVE UPDATES ----------------------------------------------------\nexport type PromptRelated_WsMsg = typeof types.PromptRelated_WsMsg.infer\n\n/** a binary preview-kind ws frame buffered IN ORDER with the json messages\n * during the pre-registration window (ComfyHost._pendingMsgs) — replayed by\n * ComfyExecution.onCreate, which decides output-vs-latent at replay time */\nexport type PendingBinaryFrame = { type: 'binary_preview_frame'; bytes: Uint8Array; mime: string }\nexport type PendingWsItem = PromptRelated_WsMsg | PendingBinaryFrame\nexport type WsMsg = typeof types.WsMsg.infer\nexport type ComfyStatusData = typeof types.ComfyStatusData.infer\nexport type WsMsgStatus = typeof types.WsMsgStatus.infer\nexport type WsMsgExecutionStart = typeof types.WsMsgExecutionStart.infer\nexport type WsMsgExecutionCached = typeof types.WsMsgExecutionCached.infer\nexport type _WSMsgExecutingData = typeof types._WSMsgExecutingData.infer\nexport type WsMsgExecuting = typeof types.WsMsgExecuting.infer\nexport type WsMsgProgress = typeof types.WsMsgProgress.infer\nexport type WsMsgProgressState = typeof types.WsMsgProgressState.infer\nexport type WsMsgExecuted = typeof types.WsMsgExecuted.infer\nexport type WsMsgExecutionSuccess = typeof types.WsMsgExecutionSuccess.infer\nexport type WsMsgExecutionError = typeof types.WsMsgExecutionError.infer\nexport type WSMsgManagerFeedback = typeof types.WSMsgManagerFeedback.infer\nexport type LogEntry = typeof types.LogEntry.infer\nexport type WsMsgLogs = typeof types.WsMsgLogs.infer\nexport type _WsMsgExecutionStartData = typeof types._WsMsgExecutionStartData.infer\nexport type _WsMsgExecutionCachedData = typeof types._WsMsgExecutionCachedData.infer\nexport type ComfyImageInfo = typeof types.ComfyImageInfo.infer\nexport type _WsMsgExecutedData = typeof types._WsMsgExecutedData.infer\nexport type _WsMsgExecutionErrorData = typeof types._WsMsgExecutionErrorData.infer\nexport type PromptId = typeof types.PromptID.infer\n\nexport type PromptInfo = { prompt_id: PromptID }\nexport const PromptInfo_ark = type({ prompt_id: types.PromptID }).as<PromptInfo>()\n\nexport const WsMsg_ark = types.WsMsg\nexport const ComfyImageInfo_ark = types.ComfyImageInfo\nexport const WsMsgLogsData_ark = types._WsMsgLogsData\n","import { type } from 'arktype'\nimport { type ImageMeta, imageMeta } from 'image-meta'\nimport { basename } from 'pathe'\nimport type { Sharp } from 'sharp'\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { importSharp } from 'src/utils/lazySharp.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport { type AbsolutePath, asAbsolutePath, type Maybe } from 'src/types/index.ts'\nimport type { NodeOf } from 'src/types/comfy-sdk.ts'\nimport type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { hashArrayBuffer } from 'src/utils/hashArrayBuffer.ts'\nimport type { ComfyExecution } from 'src/runner/ComfyExecution.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport { type ComfyImageInfo, ComfyImageInfo_ark } from 'src/runner/ComfyWsApi.ts'\nimport { ComfyNode } from 'src/graph/ComfyNode.ts'\n\n/** base64 image loader nodes we know how to wire, in preference order — each\n * verified against a real object_info dump before entering the table */\nexport const BASE64_IMAGE_LOADERS: { nameInComfy: string; inputs: (b64: string) => ComfyApiNodeJson['inputs'] }[] = [\n // comfyui-tooling-nodes: outputs IMAGE + MASK (alpha)\n { nameInComfy: 'ETN_LoadImageBase64', inputs: (b64) => ({ image: b64 }) },\n // ComfyUI-Easy-Use: image_output 'Hide' + empty prefix so the node itself saves nothing\n {\n nameInComfy: 'easy loadImageBase64',\n inputs: (b64) => ({ base64_data: b64, image_output: 'Hide', save_prefix: '' }),\n },\n]\n\nexport type MediaImageData = {\n /** absent = in-memory image (ws output with local saving off) — the buffer is then required */\n path?: Maybe<AbsolutePath>\n\n // to avoid having to read the file if we already have the buffer around\n buffer?: Uint8Array\n\n // provenance ?\n execution?: ComfyExecution\n promptNodeID?: string | null\n\n comfyUIInfos?: ImageInfos_ComfyGenerated\n}\n\nexport type ImageInfos_ComfyGenerated = {\n comfyHostHttpURL: string\n comfyImageInfo: ComfyImageInfo\n}\n\nexport const ImageInfos_ComfyGenerated_ark = type({\n comfyHostHttpURL: 'string',\n comfyImageInfo: ComfyImageInfo_ark,\n})\n\nexport class MediaImage {\n /** null for in-memory images (local saving is opt-in — architecture.md item 14) */\n absPath: AbsolutePath | null\n\n /** the execution this image came from (null when not generated via comfy-ts) */\n execution: Maybe<ComfyExecution>\n\n /** return the workflow from which this image was generated */\n get workflow(): ComfyWorkflow | undefined {\n return this.execution?.workflow\n }\n\n promptNodeID: Maybe<string>\n\n constructor(data: MediaImageData) {\n this.absPath = data.path ?? null\n this.execution = data.execution\n this.promptNodeID = data.promptNodeID\n if (data.path == null && data.buffer == null)\n throw new Error('❌ MediaImage: an in-memory image (no path) requires a buffer')\n if (data.buffer != null) this.updateBuffer(data.buffer)\n }\n\n /** free-form labels; filled from ComfyNodeMetadata.tag(s) when generated via a prompt */\n tags: string[] = []\n\n /** the image as a Blob, e.g. to feed FormData uploads */\n getAsBlob(): Blob {\n return new Blob([this.buffer as Uint8Array<ArrayBuffer>], { type: `image/${this.metadata.type ?? 'png'}` })\n }\n\n /** return the image filename (in-memory images get a stable hash-derived name) */\n get filename(): string {\n if (this.absPath != null) return basename(this.absPath)\n return `image-${this.hash.slice(0, 8)}.${this.metadata.type ?? 'png'}`\n }\n\n get baseNameWithoutExtension(): string {\n const fname = this.filename\n return fname.slice(0, fname.lastIndexOf('.'))\n }\n\n /**\n * return file extension including dot\n * e.g. `.png`, or `.webp`\n * */\n get extension(): string {\n const fname = this.filename\n return fname.slice(((fname.lastIndexOf('.') - 1) >>> 0) + 1)\n }\n\n /** get the expected enum name (hash) */\n get enumName(): ComfyImageName {\n return `${this.hash}${this.extension}` as ComfyImageName\n }\n\n uploadAndReturnEnumName = async (host: ComfyHost): Promise<ComfyImageName> => {\n const finalName = await host.uploader.uploadImage(this, { type: 'input', override: true })\n return finalName\n }\n\n /** upload the media (hash-named, deduped) and load it in the given workflow as a `LoadImage` node */\n loadInWorkflow_viaLoadImageNode = async <WID extends string>(\n workflow: ComfyWorkflow<WID>,\n ): Promise<NodeOf<WID, 'LoadImage'>> => {\n const enumName = await this.uploadAndReturnEnumName(workflow.host)\n const img = bang(workflow.builderBase.LoadImage, 'host has no LoadImage node')({ image: enumName })\n // sanctioned cast: uploaded names are runtime-known; the node itself is the host's LoadImage\n return img as NodeOf<WID, 'LoadImage'>\n }\n\n /** load an image as mask in a comfy workflow beeing created */\n loadInWorkflowAsMask_viaLoadImageMask = async <WID extends string>(\n /** \"alpha\" | \"blue\" | \"green\" | \"red\" */\n channel: 'alpha' | 'blue' | 'green' | 'red',\n /** workflow to load image as mask into */\n workflow: ComfyWorkflow<WID>,\n ): Promise<NodeOf<WID, 'LoadImageMask'>> => {\n const enumName = await this.uploadAndReturnEnumName(workflow.host)\n const mask = bang(\n workflow.builderBase.LoadImageMask,\n 'host has no LoadImageMask node',\n )({\n image: enumName,\n channel,\n })\n // sanctioned cast: same as above\n return mask as NodeOf<WID, 'LoadImageMask'>\n }\n\n /** load this image into the workflow WITHOUT any server-side file: the\n * image rides base64 inside the prompt JSON (architecture.md item 14 —\n * the prompt still enters server history; `scrubHistory` covers that).\n * Feature-detected against the host schema; no supported node = loud throw. */\n loadInWorkflow_viaBase64Node = <WID extends string>(workflow: ComfyWorkflow<WID>): NodeOf<WID, 'LoadImage'> => {\n const schema = workflow.host.schema\n const entry = BASE64_IMAGE_LOADERS.find((t) => schema.nodes.some((n) => n.nameInComfy === t.nameInComfy))\n if (entry == null) {\n throw new Error(\n `❌ host '${workflow.host.data.id}' has no base64 image loader node ` +\n `(looked for: ${BASE64_IMAGE_LOADERS.map((t) => `'${t.nameInComfy}'`).join(', ')}). ` +\n `Install one (e.g. comfyui-tooling-nodes) or fall back to loadInWorkflow_viaLoadImageNode (uploads persist server-side).`,\n )\n }\n const node = new ComfyNode(\n workflow,\n (workflow._uidNumber++).toString(),\n { class_type: entry.nameInComfy, inputs: entry.inputs(this.getBase64Payload()) },\n {},\n )\n // sanctioned cast (family 1, like the two sibling loaders): both table\n // nodes output IMAGE+MASK, the LoadImage face is the shape consumers wire\n return node as NodeOf<WID, 'LoadImage'>\n }\n\n /** return the json of the ComfyNode that led to this image */\n get ComfyNode(): Maybe<ComfyApiNodeJson> {\n const nodeID = this.promptNodeID\n if (nodeID == null) return null\n return this.workflow?.apiJson[nodeID]\n }\n\n /**\n * return the metadata of the ComfyNode that led to this image\n * null if not generated by comfy through a ComfyTS prompt\n * null if no metadata associated in the node in ComfyTS\n */\n get ComfyNodeMetadata(): Maybe<ComfyNodeMetadata> {\n const nodeID = this.promptNodeID\n if (nodeID == null) return null\n return this.workflow?.data.metadata[nodeID]\n }\n\n get width(): number | undefined {\n return this.metadata.width\n } // biome-ignore format: misc\n get height(): number | undefined {\n return this.metadata.height\n } // biome-ignore format: misc\n\n get width_orCrash(): number {\n return bang(this.metadata.width)\n } // biome-ignore format: misc\n get height_orCrash(): number {\n return bang(this.metadata.height)\n } // biome-ignore format: misc\n\n /**\n * return the base64 url for this file, regardless of it's exact representation\n * includes the prefix `data:image/<type>;base64,`\n */\n getBase64Url(): string {\n const imgType = this.metadata.type ?? 'png'\n return `data:image/${imgType};base64,${this.getBase64Payload()}`\n }\n\n /**\n * return the base64 url for this file, regardless of it's exact representation\n * does not includes the prefix `data:image/png;base64,`\n */\n getBase64Payload(): string {\n const bytes = this.buffer\n let bin = ''\n const chunk = 0x8000 // String.fromCharCode arg-count limit\n for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk))\n return btoa(bin)\n }\n\n /** return the ArrayBuffer for this file, regardless it's exact representation */\n\n /** lazilly loaded, call recomputeMetadata to expire */\n private _buffer: Maybe<Uint8Array> = null\n get buffer(): Uint8Array {\n if (this._buffer != null) return this._buffer\n this._buffer = getComfyStorage().readBytes(bang(this.absPath, 'in-memory MediaImage lost its buffer'))\n return this._buffer\n }\n /** no-op on in-memory images: the buffer is the only copy */\n freeBuffer = (): void => {\n if (this.absPath != null) this._buffer = null\n }\n updateBuffer = (buff: Uint8Array): void => {\n this._buffer = buff\n this._metadata = null // expire metadata\n this._hash = null // expire hash\n }\n reloadBuffer = (): Uint8Array => {\n this._buffer = null // expire buffer\n this._metadata = null // expire metadata\n this._hash = null // expire hash\n return this.buffer\n }\n\n /** lazilly computed, call recomputeMetadata to expire */\n private _metadata: Maybe<ImageMeta> = null\n get metadata(): ImageMeta {\n if (this._metadata != null) return this._metadata\n this._metadata = imageMeta(this.buffer)\n return this._metadata\n }\n\n private _hash: Maybe<string> = null\n get hash(): string {\n if (this._hash != null) return this._hash\n this._hash = hashArrayBuffer(this.buffer)\n return this._hash\n }\n\n /**\n * Modify the image directly (inplace) by passing it though a `Sharp` pipeline\n * Sharp is a high performance image processing library.\n */\n processWithSharp_inplace = async (\n /** processing function */\n fn: (sharp: Sharp) => Sharp,\n ): Promise<this> => {\n const sharp = await importSharp('processWithSharp_inplace')\n const buff = await fn(sharp(this.buffer)).toBuffer()\n if (this.absPath != null) getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff))\n this.updateBuffer(new Uint8Array(buff))\n return this\n }\n\n /**\n * Allow to run an image though some `Sharp` pipeline to produce an other image.\n * Sharp is a high performance image processing library.\n * to modify the image directly (inplace), use `processWithSharp_inplace` instead.\n */\n processWithSharp = async (\n /** processing function */\n fn: (sharp: Sharp) => Sharp,\n /** where to save the resulting image */\n path?: AbsolutePath,\n ): Promise<MediaImage> => {\n const sharp = await importSharp('processWithSharp')\n path ??=\n this.absPath != null ? asAbsolutePath(this.absPath + `.processed-${Date.now()}` + this.extension) : undefined\n const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer())\n if (path != null) getComfyStorage().writeBytes(path, buffer)\n return new MediaImage({ path, buffer })\n }\n}\n","import type { FormatEnum } from 'sharp'\nimport { localOutputPath, runTimestamp, uniquifyOutputPath, withExtension } from 'src/runner/outputPath.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { importSharp } from 'src/utils/lazySharp.ts'\nimport { getPngMetadataFromUint8Array } from 'src/image-utils/_getPngMetadata.ts'\nimport type { ComfyNodeId } from 'src/graph/ComfyNodeID.ts'\nimport { type AbsolutePath, asAbsolutePath, type Maybe, type SaveOptions } from 'src/types/index.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { exhaust } from 'src/utils/exhaust.ts'\nimport type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'\nimport type { ComfyWorkflow, ComfyWorkflowID, ExecutionSnapshot, ProgressReport } from 'src/runner/ComfyWorkflow.ts'\n\nimport type {\n ComfyImageInfo,\n PromptID,\n PendingWsItem,\n WsMsgExecuted,\n WsMsgExecuting,\n WsMsgExecutionError,\n WsMsgExecutionSuccess,\n} from 'src/runner/ComfyWsApi.ts'\nimport { MediaImage } from 'src/runner/MediaImage.ts'\n\n/** paths claimed by in-flight retrievals: two same-second runs on a\n * counter-resetting cloud host compute the same name before either writes.\n * A claim is released as soon as the write lands (the file itself then holds\n * the name) or fails (the name is free again) — the set never accumulates */\nconst CLAIMED_OUTPUT_PATHS = new Set<string>()\n\nexport type ComfyExecutionData = {\n id: PromptID\n graphID: ComfyWorkflowID\n executed: boolean\n error?: WsMsgExecutionError | null\n status?: ComfyExecutionStatus | null\n}\n\n/** one text output as an output node published it (`nodeKey` is null when the node left the snapshot) */\nexport type ComfyTextOutput = {\n nodeId: ComfyNodeId\n nodeKey: string | null\n text: string\n}\n\nexport type ExecutionProgress = ProgressReport & {\n promptId: PromptID\n nodeName: string | null\n elapsedMs: number\n /** the executing node's OWN counter, in its own unit: sampler steps, or generated\n * tokens on a text node. Null between nodes. The global percent normalizes this away,\n * and the unit is the only live detail worth reading on a long node */\n nodeProgress: { value: number; max: number } | null\n /** the executing node's live display text, when it publishes one. A streaming generator\n * puts its partial answer here every few tokens */\n progressText: string | null\n}\n\nexport class ComfyExecution {\n get host(): ComfyHost {\n return this.workflow.host\n }\n\n constructor(\n public workflow: ComfyWorkflow,\n public data: ComfyExecutionData,\n init: {\n snapshot?: ExecutionSnapshot\n save?: Maybe<boolean | SaveOptions>\n scrubHistory?: boolean\n ephemeral?: boolean\n onProgress?: Maybe<(p: ExecutionProgress) => void>\n logProgress?: boolean\n } = {},\n ) {\n // settings FIRST: onCreate flushes buffered ws messages whose handlers read them\n this.snapshot = init.snapshot ?? null\n this.save = init.save === true ? {} : init.save === false ? null : (init.save ?? null)\n this.scrubHistory = init.scrubHistory ?? false\n this.ephemeral = init.ephemeral ?? false\n this.onProgress = init.onProgress ?? null\n this.logProgress = init.logProgress ?? false\n // register with the host so websocket messages route here,\n // then flush messages that arrived before we existed\n this.host.executions.set(data.id, this)\n this.onCreate()\n }\n\n /** local disk saving, OPT-IN (architecture.md item 14); null = outputs stay in memory */\n save: Maybe<SaveOptions> = null\n /** delete this run's server history entry after `done` */\n scrubHistory: boolean = false\n /** this run's SaveImage nodes were rewritten to SaveImageWebsocket in the snapshot */\n ephemeral: boolean = false\n\n /** exactly what was sent to the host, frozen at send time (replayable) */\n snapshot: Maybe<ExecutionSnapshot> = null\n\n // ---- progress ----------------------------------------------------------\n /** called on every progress-relevant websocket message */\n onProgress: Maybe<(p: ExecutionProgress) => void> = null\n /** render a live single-line progress report to the console */\n logProgress: boolean = false\n readonly startedAt: number = Date.now()\n\n get progress(): ExecutionProgress {\n const report = this.progressGlobal\n return {\n ...report,\n promptId: this.data.id,\n nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,\n elapsedMs: Date.now() - this.startedAt,\n nodeProgress: this.workflow.currentExecutingNode?.progress ?? null,\n progressText: this.progressText,\n }\n }\n\n private _lastLoggedLine: string = ''\n private emitProgress(): void {\n const p = this.progress\n this.onProgress?.(p)\n if (!this.logProgress) return\n const width = 12\n const filled = Math.round((p.percent / 100) * width)\n const bar = '█'.repeat(filled) + '░'.repeat(width - filled)\n const node = p.nodeName ? ` · ${p.nodeName}` : ''\n // the node's own counter: sampler steps, or generated tokens. Core TextGenerate\n // publishes no partial text, so on it this is the only thing that moves\n const count = p.nodeProgress ? ` ${p.nodeProgress.value}/${p.nodeProgress.max}` : ''\n const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node}${count} · ${(p.elapsedMs / 1000).toFixed(0)}s`\n // a streaming node's newest words, on the same line: the run stays ONE line, and what\n // the model is writing is the thing worth watching on it\n const tail = p.progressText?.replaceAll('\\n', ' ').trimEnd().slice(-60)\n const full = tail == null || tail === '' ? line : `${line} · …${tail}`\n if (full === this._lastLoggedLine) return\n this._lastLoggedLine = full\n if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\\r\\x1b[2K${full}`)\n else console.log(full)\n }\n\n private finishProgressLine(): void {\n if (!this.logProgress) return\n const p = this.progress\n const outputs = [`${this.images.length} image(s)`]\n if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`)\n const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${outputs.join(' · ')}`\n if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\\r\\x1b[2K${line}\\n`)\n else console.log(line)\n }\n\n // promise handle so that we can wait for this execution to finish.\n // resolves in BOTH success and failure — inspect `status` / `data.error`.\n private _resolve!: (value: this) => void\n done: Promise<this> = new Promise((resolve) => {\n this._resolve = resolve\n })\n\n log(...args: unknown[]): void {\n console.log(`[ComfyExecution#${this.data.id}]`, ...args)\n }\n\n onCreate(): void {\n const data: ComfyExecutionData = this.data\n const pending = this.host._pendingMsgs.get(data.id)\n if (pending == null) return\n this.log(`🟢 onCreate: ${pending.length} pending messages`)\n this.host._pendingMsgs.delete(data.id) // buffered once, never again\n for (const msg of pending) this.onPromptRelatedMessage(msg)\n }\n\n get progressGlobal(): ProgressReport {\n if (this.data.status === 'Success') return { countDone: 1, countTotal: 1, isDone: true, percent: 100 }\n return this.workflow.progressGlobal\n }\n\n get status(): 'New' | 'Scheduled' | 'Running' | 'Success' | 'Failure' {\n return this.data.status ?? 'New'\n }\n\n onPromptRelatedMessage = (msg: PendingWsItem): void => {\n const graph = this.workflow\n // replayed pre-registration binary frame: an OUTPUT only when the ws\n // saver was executing at this point of the stream; stale latents drop\n if (msg.type === 'binary_preview_frame') {\n if (this.wsOutputNodeExecuting) this.onWsImageOutput({ bytes: msg.bytes, mime: msg.mime })\n return\n }\n if (msg.type === 'execution_start') return\n else if (msg.type === 'execution_cached') graph.onExecutionCached(msg)\n else if (msg.type === 'executing') this.onExecuting(msg)\n else if (msg.type === 'progress') graph.onProgress(msg)\n else if (msg.type === 'progress_state') {\n // per-node progress map; global progress is derived from the msgs above\n } else if (msg.type === 'executed') this.onExecuted(msg)\n else if (msg.type === 'execution_error') return void this.onError(msg)\n else if (msg.type === 'execution_success') return void this.onExecutionSuccess(msg)\n else {\n console.log(`🔴 UNEXPECTED MESSAGE:`, msg)\n return exhaust(msg)\n }\n this.emitProgress()\n }\n\n /** update pointer to the currently executing node */\n private onExecuting = (msg: WsMsgExecuting): void => {\n this.workflow.onExecuting(msg)\n }\n\n private onExecutionSuccess = async (_msg: WsMsgExecutionSuccess): Promise<void> => {\n await Promise.all(this.pendingPromises)\n return this._finish({ status: 'Success' })\n }\n\n private onError = async (msg: WsMsgExecutionError): Promise<void> => {\n console.error('❌ Execution error:')\n console.error(msg)\n return this._finish({ status: 'Failure', error: msg })\n }\n\n /** update execution list */\n private onExecuted = (msg: WsMsgExecuted): void => {\n const promptNodeID = msg.data.node\n // a STRING output reaches the client ONLY through an output node's ui\n // payload (PreviewAny), never through the prompt result\n for (const entry of msg.data.output?.text ?? []) {\n if (typeof entry !== 'string') continue\n const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null\n this.texts.push({ nodeId: promptNodeID, nodeKey, text: entry })\n }\n const images = msg.data.output?.images\n if (images) {\n for (const img of images) {\n // guard every retrieval: one failed download must not hang `done`\n this.pendingPromises.push(\n this.retrieveImage(img, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to retrieve ${img.filename}:`, e)\n this.imageErrors.push({ image: img, error: e })\n }),\n )\n }\n }\n }\n private pendingPromises: Promise<void>[] = []\n\n /** image retrievals that failed (their images are missing from `images`);\n * `image` is null for SaveImageWebsocket frames (no server-side file info exists) */\n imageErrors: { image: Maybe<ComfyImageInfo>; error: unknown }[] = []\n\n retrieveImage = async (\n //\n comfyImageInfo: ComfyImageInfo,\n promptNodeID: ComfyNodeId,\n ): Promise<void> => {\n // retrieve the node\n const promptNode = this.workflow.data.apiJson?.[promptNodeID]\n if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`)\n\n // image route on the host (cloud answers a 302 signed url — fetchFile follows it unauthed)\n const imgRoute = '/view?' + new URLSearchParams(comfyImageInfo).toString()\n const response = await this.host.fetchFile(imgRoute)\n const bytes = new Uint8Array(await response.arrayBuffer())\n\n const comfyUIInfos = { comfyImageInfo, comfyHostHttpURL: this.host.getServerHostHTTP() }\n\n // local saving is OPT-IN (architecture.md item 14): no save → in-memory only\n const sf = this.save\n if (sf == null) {\n return this.pushImage(\n new MediaImage({ buffer: bytes, execution: this, promptNodeID: promptNodeID, comfyUIInfos }),\n promptNodeID,\n )\n }\n\n const promptPrefix = promptNode.inputs['filename_prefix']\n const written = await this.encodeAndWrite({\n bytes,\n sf,\n filenamePrefix: typeof promptPrefix === 'string' ? promptPrefix : undefined,\n subfolder: comfyImageInfo.subfolder,\n filename: comfyImageInfo.filename,\n })\n this.pushImage(\n new MediaImage({\n path: written.path,\n buffer: written.bytes,\n execution: this,\n promptNodeID: promptNodeID,\n comfyUIInfos,\n }),\n promptNodeID,\n )\n }\n\n /** re-encode when asked, then write under OUR local naming — never the raw\n * server filename: a cloud host resets its _00001_ counter per run, so the\n * server name overwrote the same local file on every run */\n private encodeAndWrite = async (p: {\n bytes: Uint8Array\n sf: SaveOptions\n filenamePrefix?: string\n subfolder: string\n filename: string\n }): Promise<{ path: AbsolutePath; bytes: Uint8Array }> => {\n let bytes = p.bytes\n const reencode = p.sf.format != null && p.sf.format !== 'raw'\n if (reencode) {\n // PNG text chunk (workflow provenance) survives the re-encode as EXIF\n let textChunk = {}\n try {\n const res = getPngMetadataFromUint8Array(p.bytes)\n if (res.success) textChunk = res.value\n } catch {}\n\n const format = ((): keyof FormatEnum => {\n if (p.sf.format === 'image/jpeg') return 'jpeg'\n if (p.sf.format === 'image/webp') return 'webp'\n return 'png'\n })()\n\n // node-only branch: re-encoding needs sharp (save 'raw' is the web path)\n const sharp = await importSharp(`save format '${p.sf.format}' re-encoding`)\n const encoded = await sharp(p.bytes)\n .withMetadata()\n .withExif({ IFD0: textChunk })\n // sharp expect quality between 1 and 100\n .toFormat(format, p.sf.quality ? { quality: Math.round(p.sf.quality * 100) } : undefined)\n .toBuffer()\n bytes = new Uint8Array(encoded)\n }\n\n let absPath: string = comfyts.resolveFromOutput(\n localOutputPath({\n localDir: p.sf.prefix,\n filenamePrefix: p.filenamePrefix,\n subfolder: p.subfolder,\n filename: p.filename,\n timestamp: runTimestamp(new Date(this.startedAt)),\n }),\n )\n if (reencode) absPath = withExtension(absPath, bang(bang(p.sf.format).split('/')[1]))\n // last-resort uniquifier: bump past files on disk AND paths claimed by\n // still-downloading retrievals — never overwrite\n const storage = getComfyStorage()\n absPath = uniquifyOutputPath({ path: absPath, exists: (x) => storage.exists(x), claimed: CLAIMED_OUTPUT_PATHS })\n try {\n storage.writeBytes(asAbsolutePath(absPath), bytes)\n } finally {\n // the file (or the failure) now owns the name — holding the claim\n // forever would grow the set for the whole life of a `serve` process\n CLAIMED_OUTPUT_PATHS.delete(absPath)\n }\n return { path: asAbsolutePath(absPath), bytes }\n }\n\n /** accumulate an output on the prompt; tags from node metadata ride along */\n private pushImage(img: MediaImage, promptNodeID: Maybe<string>): void {\n const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null\n if (promptMeta?.tag) img.tags.push(promptMeta.tag)\n if (promptMeta?.tags) img.tags.push(...promptMeta.tags)\n this.images.push(img)\n }\n\n /** true while the currently executing node is a SaveImageWebsocket in the\n * SENT snapshot (the ephemeral rewrite only touches the snapshot, so the\n * live graph may still say SaveImage) — binary frames are then OUTPUTS */\n get wsOutputNodeExecuting(): boolean {\n const uid = this.workflow.currentExecutingNode?.uid\n if (uid == null) return false\n const apiJson = this.snapshot?.apiJson ?? this.workflow.apiJson\n return apiJson[uid]?.class_type === 'SaveImageWebsocket'\n }\n\n /** one binary ws frame = one output image of the executing SaveImageWebsocket\n * node (architecture.md item 14 — the zero-server-disk path) */\n onWsImageOutput = (p: { bytes: Uint8Array; mime: string }): void => {\n const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null\n this.pendingPromises.push(\n this.storeWsImage(p, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to store a SaveImageWebsocket output:`, e)\n this.imageErrors.push({ image: null, error: e })\n }),\n )\n }\n\n private storeWsImage = async (\n p: { bytes: Uint8Array; mime: string },\n promptNodeID: Maybe<string>,\n ): Promise<void> => {\n const sf = this.save\n if (sf == null) {\n return this.pushImage(new MediaImage({ buffer: p.bytes, execution: this, promptNodeID }), promptNodeID)\n }\n const ext = p.mime === 'image/jpeg' ? 'jpg' : (p.mime.split('/')[1] ?? 'png')\n const written = await this.encodeAndWrite({\n bytes: p.bytes,\n sf,\n subfolder: '',\n // ws frames carry no server filename — the workflow id is the stem\n filename: `${this.workflow.id}.${ext}`,\n })\n this.pushImage(\n new MediaImage({ path: written.path, buffer: written.bytes, execution: this, promptNodeID }),\n promptNodeID,\n )\n }\n\n /** images retrieved for this execution, in arrival order (final once `done` resolves) */\n images: MediaImage[] = []\n\n /** text outputs emitted for this execution, in arrival order (final once `done` resolves) */\n texts: ComfyTextOutput[] = []\n\n /** live display text per node WHILE it runs, newest wins (`send_progress_text` is a\n * replacement, not a delta). This is the only channel carrying text DURING a node: a\n * generator that streams its tokens shows up here, and nowhere in the final outputs */\n progressTexts: Map<string, string> = new Map()\n\n /** the node that most recently published live text — what \"watch it work\" means */\n progressText: string | null = null\n\n /** @internal a live-text frame for one node */\n onProgressText(p: { nodeId: string; text: string }): void {\n this.progressTexts.set(p.nodeId, p.text)\n this.progressText = p.text\n this.emitProgress()\n }\n\n /** the last text output, the one a single-generator workflow means by \"the result\" */\n get text(): string | null {\n return this.texts.at(-1)?.text ?? null\n }\n\n update(data: Partial<ComfyExecutionData>): void {\n Object.assign(this.data, data)\n }\n\n private alreadyDone: boolean = false\n private _finish = async (p: Pick<ComfyExecutionData, 'status' | 'error'>): Promise<void> => {\n if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`)\n this.alreadyDone = true\n this.update({ ...p, executed: true })\n await Promise.all(this.pendingPromises)\n // finished executions receive no further messages — free the routing maps\n this.host.executions.delete(this.data.id)\n this.host._pendingMsgs.delete(this.data.id)\n\n // the inputs gap, stated loud (item 14): ephemeral covers OUTPUTS only —\n // uploaded inputs persist in the server's input/ dir, no upstream delete API\n if (this.ephemeral) {\n const classTypes = Object.values(this.snapshot?.apiJson ?? {}).map((n) => n.class_type)\n if (classTypes.includes('LoadImage') || classTypes.includes('LoadImageMask')) {\n console.warn(\n `🟡 ephemeral run ${this.data.id}: outputs never touched the server disk, but the graph's ` +\n `LoadImage nodes reference files in the host's input/ folder (uploads persist — ComfyUI has ` +\n `no delete API). Use MediaImage.loadInWorkflow_viaBase64Node to keep inputs off the server too.`,\n )\n }\n }\n\n // history scrub AFTER retrievals: loud but never fatal — a privacy\n // feature that crashes the run would push users to disable it\n if (this.scrubHistory) {\n await this.host.deleteHistory(this.data.id).catch((e: unknown) => {\n console.error(`🔴 failed to scrub history entry ${this.data.id} on host ${this.host.data.id}:`, e)\n })\n }\n\n this.finishProgressLine()\n this._resolve(this)\n }\n}\n","import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'\n\n/**\n * the `ephemeral: true` rewrite (architecture.md item 14): every SaveImage\n * node in the SENT snapshot becomes a SaveImageWebsocket (core node, `images`\n * input only), so outputs stream over the ws and never touch the server disk.\n * Mutates the given apiJson IN PLACE — callers pass the run's deep-copied\n * snapshot, never the live graph. Returns how many nodes were rewritten so\n * callers can warn when a graph had nothing to rewrite.\n */\nexport function rewriteSaveNodesToWebsocket(apiJson: ComfyApiJson): number {\n let rewritten = 0\n for (const node of Object.values(apiJson)) {\n if (node.class_type !== 'SaveImage') continue\n const images = node.inputs['images']\n node.class_type = 'SaveImageWebsocket'\n node.inputs = images == null ? {} : { images }\n rewritten++\n }\n return rewritten\n}\n","export const deepCopyNaive = <T>(x: T): T => JSON.parse(JSON.stringify(x))\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","// 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","import type { ArkErrors } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { isQuiet } from 'src/utils/log.ts'\n\nconst MAX_PRINTED_ERRORS = 10\n\nexport function printArkResultInConsole(res: ArkErrors): void {\n if (isQuiet()) return\n console.log(chalk.red(' ❌ Ark validation failed:'))\n for (const error of res.slice(0, MAX_PRINTED_ERRORS)) {\n console.log(chalk.red(` - ${error.path.join('.')} : ${error.message}`))\n }\n if (res.length > MAX_PRINTED_ERRORS) {\n console.log(chalk.red(` … ${res.length - MAX_PRINTED_ERRORS} more (${res.length} total)`))\n }\n}\n","import { type Type, type } from 'arktype'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\n\nexport const softValidate = <T>(schema: Type<T>, stuff: unknown): T => {\n const res = schema(stuff)\n if (res instanceof type.errors) printArkResultInConsole(res)\n return stuff as T\n}\n","type ObjMap<T> = { [key: string]: T }\n\nexport type TNode = string\nexport type TEdge = [TNode, TNode]\n\nexport function toposort(nodes: TNode[], edges: TEdge[]): TNode[] {\n return toposortAlgo(nodes, edges)\n}\n\nfunction toposortAlgo(nodes: TNode[], edges: TEdge[]) {\n let cursor = nodes.length\n const sorted = Array.from<TNode>({ length: cursor })\n const visited: ObjMap<boolean> = {}\n let k = cursor\n\n while (k--) {\n if (!visited[k]) visit(BONG(nodes[k]), k, [])\n }\n\n return sorted\n\n function visit(node: TNode, ix: number, predecessors: TNode[]): void {\n let i = ix\n if (predecessors.indexOf(node) >= 0) {\n console.log(predecessors, node)\n throw new Error('Cyclic dependency: ' + JSON.stringify(node))\n }\n\n if (nodes.indexOf(node) === -1) {\n throw new Error(\n '[toposort] Found unknown node. Make sure to provided all involved nodes. Unknown node: ' +\n JSON.stringify(node) +\n '; known nodes are ' +\n JSON.stringify(nodes),\n )\n }\n\n if (visited[i]) return\n visited[i] = true\n\n // outgoing edges\n const outgoing = edges.filter((edge) => edge[0] === node)\n i = outgoing.length\n if (i) {\n const preds = predecessors.concat(node)\n do {\n const child = BONG(outgoing[--i])[1]\n visit(child, nodes.indexOf(child), preds)\n } while (i)\n }\n\n sorted[--cursor] = node\n }\n}\n\nfunction BONG<T>(x: T): NonNullable<T> {\n if (x == null) throw new Error('BONG')\n return x\n}\n","/** biome-ignore-all lint/style/noNonNullAssertion: later */\nimport type { ComfyNode, ComfyNodeUID } from 'src/graph/ComfyNode.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { type TEdge, toposort } from 'src/utils/toposort.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\n\n/**\n * compute autolayout\n *\n * 💬 2025-06-11 rvion: I tried various autolayout algorithm, but those massive\n * libraries were pretty bad; ended up writing my own simple algorithm, and I'm\n * happy with it. Feel free to improve it, but I think it works well enough.\n * I will accept PRs for new layout algorithms if they don't have massive dependencies.\n **/\nexport function comfyWorkflowAutoLayout(\n this: ComfyWorkflow,\n p?: {\n /** @default: 40 */\n node_vsep?: number\n /** @default: 100 */\n node_hsep?: number\n /** @default false */\n forceLeft?: boolean\n },\n): ComfyWorkflow {\n const nodeIds = toposort(\n this.nodes.map((n) => n.uid),\n this.nodes.flatMap((n) => n._incomingNodes().map((from) => [from, n.uid] as TEdge)),\n )\n const nodes = nodeIds.map((id) => bang(this.getNode(id), `Node not found: ${id}`))\n const cols: ComfyNode[][] = Array.from({ length: nodeIds.length })\n\n type NodePlacement = {\n node: ComfyNode\n minCol: number\n maxCol?: number\n }\n const ranges: {\n [nodeId: ComfyNodeUID]: NodePlacement\n } = {}\n\n // console.log(`[🤠] 1/3 ----------------------------`)\n for (const node of nodes) {\n // must be at least 1 after the closest parent\n const parentCols = node.parents.map((p) => ranges[p.uid]!.minCol)\n const minCol = Math.max(...parentCols, -1) + 1\n const range: NodePlacement = { node: node, minCol: minCol }\n ranges[node.uid] = range\n }\n\n // console.log(`[🤠] 2/3 ----------------------------`)\n if (!p?.forceLeft === true) {\n for (const node of nodes) {\n const range = ranges[node.uid]!\n for (const p of node.parents) {\n const parentRange = ranges[p.uid]!\n parentRange.maxCol =\n parentRange.maxCol != null\n ? Math.min(parentRange.maxCol, (range.maxCol ?? range.minCol) - 1)\n : (range.maxCol ?? range.minCol) - 1\n }\n }\n }\n\n // console.log(`[🤠] 3/3 ----------------------------`)\n for (const node of nodes) {\n const range = ranges[node.uid]!\n const at = range.maxCol ?? range.minCol\n if (cols[at]) cols[at]!.push(node)\n else cols[at] = [node]\n }\n\n // real ComfyUI nodes render wider than the 200px layout estimate, so the\n // horizontal gap is generous to keep pasted graphs readable\n const HSEP = p?.node_hsep ?? 100\n const VSEP = p?.node_vsep ?? 40\n // cols.reverse()\n let colX = 0\n let maxY = 0\n for (const col of cols) {\n if (col == null) continue\n let colWidth = 0\n let currNodeY = 32\n const nodesSorted = col.toSorted((a, b) => b.height - a.height)\n for (const node of nodesSorted) {\n colWidth = Math.max(colWidth, node.width)\n node.x = colX\n node.y = currNodeY\n currNodeY += node.height + VSEP /* V SEP */\n }\n maxY = Math.max(maxY, currNodeY)\n colX += colWidth + HSEP /* H SEP */\n }\n\n this.height = maxY\n this.width = colX\n return this\n}\n","import { nanoid } from 'nanoid'\nimport { describePromptRejection } from 'src/runner/describePromptRejection.ts'\nimport { join } from 'pathe'\nimport { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'\nimport { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'\nimport type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'\nimport { ComfyNode } from 'src/graph/ComfyNode.ts'\nimport type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'\nimport { ComfyExecution, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'\nimport { rewriteSaveNodesToWebsocket } from 'src/runner/ephemeral.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport { type AbsolutePath, type Maybe, type SaveOptions, type Tagged } from 'src/types/index.ts'\nimport type { SdkForHost } from 'src/types/comfy-sdk.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { deepCopyNaive } from 'src/utils/deepCopyNaive.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport { comfyWorkflowAutoLayout } from 'src/runner/ComfyWorkflowLayout.ts'\nimport {\n type ApiPromptInput,\n type PromptInfo,\n PromptInfo_ark,\n type WsMsgExecuting,\n type WsMsgExecutionCached,\n type WsMsgProgress,\n} from 'src/runner/ComfyWsApi.ts'\n\nexport type ProgressReport = {\n percent: number\n isDone: boolean\n countDone: number\n countTotal: number\n}\n\nexport type ComfyNodeIdMode = 'use_stringified_numbers_only' | 'use_class_name_and_number'\n\nexport type RunSettings = {\n /** local disk saving is OPT-IN: unset/false keeps outputs in memory only\n * (`execution.images` buffers); `true` = raw save, an object re-encodes/relocates */\n save?: boolean | SaveOptions\n /** rewrite every SaveImage node to SaveImageWebsocket in the SENT prompt —\n * outputs never touch the server disk. Implies `scrubHistory` unless that\n * is explicitly false. (architecture.md item 14) */\n ephemeral?: boolean\n /** delete this run's server history entry (workflow JSON, prompts, filenames)\n * after `done` — loud but non-fatal on failure */\n scrubHistory?: boolean\n idMode?: ComfyNodeIdMode\n /** render a live single-line progress report to the console */\n log?: boolean\n /** called on every progress-relevant websocket message */\n onProgress?: (p: ExecutionProgress) => void\n}\n\n/** exactly what was sent to the host for one execution, frozen at send time */\nexport type ExecutionSnapshot = {\n apiJson: ComfyApiJson\n workflowJson: LiteGraphJSON\n}\n\n/**\n * ComfyWorkflowL\n * - holds the nodes\n * - can be instanciated in both extension and webview\n * - so no link to workspace or run\n */\n\n// #region ComfyWorkflow\nexport type ComfyWorkflow_metadata = { [key: ComfyNodeId]: ComfyNodeMetadata }\n\nexport type ComfyWorkflowID = Tagged<string, { ComfyWorkflowID: true }>\nexport const asComfyWorkflowID = (x: string): ComfyWorkflowID => x\n\nexport type ComfyWorkflowData = {\n id?: Maybe<ComfyWorkflowID>\n\n apiJson?: ComfyApiJson\n metadata: ComfyWorkflow_metadata\n}\n\nexport class ComfyWorkflow<ID extends string = string> {\n id: ComfyWorkflowID\n apiJson: ComfyApiJson\n outputFolder: AbsolutePath\n\n constructor(\n public host: ComfyHost<ID>,\n public data: ComfyWorkflowData,\n ) {\n this.id = data.id ?? (nanoid(8) as ComfyWorkflowID)\n // ONE json object, shared by the field and the data record (registerNode writes there)\n this.apiJson = data.apiJson ?? {}\n data.apiJson = this.apiJson\n this.outputFolder = join(comfyts.outputPath, `workflow-${this.id}`)\n }\n\n /** nodes, in creation order */\n nodes: ComfyNode[] = []\n\n /** @internal every node constructor must call this */\n registerNode = (node: ComfyNode): void => {\n if (this.data.apiJson == null) throw new Error('graph not hydrated')\n this.data.apiJson[node.uid] = node.json\n this.data.metadata[node.uid] = node.meta\n this.nodesIndex.set(node.uid, node)\n this.nodes.push(node)\n }\n\n /** number of node in the graph */\n get size(): number {\n return this.nodes.length\n }\n\n setMetadata = (nodeID: ComfyNodeId, meta: ComfyNodeMetadata): void => {\n this.data.metadata[nodeID] = meta\n }\n\n getMetadata = (nodeID: ComfyNodeId): Maybe<ComfyNodeMetadata> => {\n return this.data.metadata[nodeID] ?? null\n }\n\n /** problem accumulator */\n problems: { title: string; data?: unknown }[] = []\n\n recordProblem = (title: string, data?: unknown): void => {\n this.problems.push({ title, data })\n }\n\n /** workflow builder, typed from the generated per-host sdk when one is in scope */\n private _builder: ComfyWorkflowBuilder | null = null\n get builder(): SdkForHost<ID>['Builder'] {\n if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this)\n // sanctioned cast (see agent/coding.md): the runtime builder defines its\n // methods dynamically from the live schema; the static face comes from\n // the generated per-host sdk. Both derive from the same object_info.\n return this._builder as SdkForHost<ID>['Builder']\n }\n\n /** base (untyped) view of the same builder, for generic library code */\n get builderBase(): Comfy.Builder {\n if (this._builder == null) this._builder = new ComfyWorkflowBuilder(this)\n return this._builder as Comfy.Builder\n }\n\n onUpdate = (prev: Maybe<ComfyWorkflowData>, next: ComfyWorkflowData): void => {\n if (prev != null) {\n this.nodes = []\n this.nodesIndex.clear()\n this.currentExecutingNode = null\n }\n for (const [uid, node] of Object.entries(bang(next.apiJson))) {\n const meta: Maybe<ComfyNodeMetadata> = next.metadata?.[uid]\n new ComfyNode(this, uid, node, meta)\n }\n }\n\n /** proxy to this.db.schema */\n get schema(): ComfySchema {\n return this.host.schema\n }\n\n /** nodes that are still pending execution */\n get pendingNodes(): ComfyNode[] {\n return this.nodes.filter((n) => n.status == null || n.status === 'waiting')\n }\n\n get nodesByUpdatedAt(): ComfyNode[] {\n return this.nodes //\n .filter((n) => n.status != null && n.status !== 'waiting')\n .sort((a, b) => b.updatedAt - a.updatedAt)\n // return this.nodes.slice().sort((a, b) => b.updatedAt - a.updatedAt)\n }\n\n // findNodeByType = <T extends keyof ComfySetup>(nodeKey: T): Maybe<ReturnType<ComfySetup[T]>> => {\n // return this.nodes.find((n) => n.$schema.nodeKey === nodeKey) as any\n // }\n\n /** nodes, indexed by nodeID */\n nodesIndex = new Map<string, ComfyNode>()\n\n /** convert to mermaid DSL expression for nice graph rendering */\n toMermaid = (DIR: 'LR' | 'TD' = 'LR'): string => {\n const out = [\n `graph ${DIR}`,\n this.nodes.map((n) => `${n.uid}[${n.$schema.nodeKey}]`).join('\\n'),\n this.nodes\n .map((n) =>\n n\n ._incomingEdges()\n .map((i) => {\n const from = this.nodesIndex.get(i.from)\n\n return `${from?.uid ?? i.from}[${from?.$schema.nodeKey ?? i.from}] --> |${i.inputName}|${n.uid}[${\n n.$schema.nodeKey\n }]`\n })\n .join('\\n'),\n )\n .join('\\n'),\n ].join('\\n')\n return out\n }\n\n /** export the graph in ComfyUI's saved-workflow format (autolayouted by default) */\n toWorkflowJson = async (p: { layout?: boolean } = {}): Promise<LiteGraphJSON> => {\n if (p.layout !== false) this.autoLayout()\n return convertFlowToLiteGraphJSON(this)\n }\n\n /** export the graph in ComfyUI's api format (what POST /prompt takes) */\n toApiJson = (ns: ComfyNodeIdMode = 'use_stringified_numbers_only'): ComfyApiJson => {\n const json: ComfyApiJson = {}\n const keyOf = (uid: string): string =>\n ns === 'use_stringified_numbers_only' ? uid : (this.nodesIndex.get(uid)?.uidPrefixed ?? uid)\n for (const node of this.nodes) {\n if (node.disabled) continue\n const key = ns === 'use_stringified_numbers_only' ? node.uid : node.uidPrefixed\n // links reference node keys — remap them to whatever key scheme we emit\n const inputs: ComfyApiNodeJson['inputs'] = {}\n for (const [name, value] of Object.entries(node.json.inputs)) {\n inputs[name] =\n Array.isArray(value) && typeof value[0] === 'string' && typeof value[1] === 'number'\n ? [keyOf(value[0]), value[1]]\n : value\n }\n json[key] = { class_type: node.json.class_type, inputs }\n }\n return json\n }\n\n /** @internal pointer to the currently executing node */\n currentExecutingNode: ComfyNode | null = null\n\n get progressCurrentNode(): Maybe<ProgressReport> {\n return this.currentExecutingNode?.progressReport\n }\n\n get progressGlobal(): ProgressReport {\n const totalNode = this.nodes.length\n const doneNodes = this.nodes.filter((n) => n.status === 'done' || n.status === 'cached').length\n const bonus = this.currentExecutingNode?.progressRatio ?? 0\n const score = (doneNodes + bonus) / totalNode\n const percent = this.done ? 100 : score * 100\n const isDone = this.done\n return { percent, isDone, countDone: doneNodes + bonus, countTotal: totalNode }\n }\n\n /** @internal update the progress value of the currently focused onde */\n onProgress = (msg: WsMsgProgress): void => {\n if (this.currentExecutingNode == null) return void console.log('❌ no current executing node', msg)\n this.currentExecutingNode.progress = msg.data\n this.currentExecutingNode.progressRatio = (msg.data.value ?? 0) / (msg.data.max || 1)\n }\n\n getTargetWorkflowFilePath = (): AbsolutePath => {\n return join(this.cacheFolderPath, 'workflow.json')\n }\n\n getTargetPromptFilePath = (): AbsolutePath => {\n return join(this.cacheFolderPath, 'prompt.json')\n }\n\n get cacheFolderPath(): AbsolutePath {\n return comfyts.resolveFromOutput(`workflows/${this.id}`)\n }\n\n // private outputs: WsMsgExecuted[] = []\n // images: ImageL[] = []\n\n done: boolean = false\n\n /** @internal update pointer to the currently executing node */\n onExecuting = (msg: WsMsgExecuting): void => {\n // 1. mark currentExecutingNode as done\n if (this.currentExecutingNode) {\n this.currentExecutingNode.status = 'done'\n // this.currentExecutingNode.updatedAt = Date.now() + 1000\n }\n // 2. then two cases:\n // 2.A. no node => the prompt is done\n if (msg.data.node == null) {\n this.currentExecutingNode = null\n this.done = true\n return\n }\n\n this.done = false\n // 2.B. a node => node evaluation is starting\n const node = this.getNodeOrCrash(msg.data.node)\n this.currentExecutingNode = node\n node.status = 'executing'\n node.updatedAt = Date.now()\n }\n\n onExecutionCached = (msg: WsMsgExecutionCached): void => {\n for (const x of msg.data.nodes) {\n const node = this.getNodeOrCrash(x)\n node.status = 'cached'\n }\n }\n\n // onExecuted = (msg: WsMsgExecuted) => {\n // const node = this.getNodeOrCrash(msg.data.node)\n // const images = msg.data.output.images.map((i) => new PromptOutputImage(this, i))\n\n // // console.log(`🟢 `, images.length, `CushyImages`)\n // // accumulate in self\n // this.outputs.push(msg)\n // this.images.push(...images)\n // // console.log(`🟢 `, this.uid, 'has', this.images.length, `CushyImages`)\n\n // // accumulate in node\n // node.artifacts.push(msg.data)\n // node.images.push(...images)\n // }\n\n _uidNumber: number = 0\n\n getNodeOrCrash = (nodeID: ComfyNodeId): ComfyNode => {\n const node = this.nodesIndex.get(nodeID)\n if (node == null) throw new Error('Node not found:' + nodeID)\n return node\n }\n\n getNode = (nodeID: ComfyNodeId): Maybe<ComfyNode> => {\n const node = this.nodesIndex.get(nodeID)\n return node\n }\n\n width: number = 100\n height: number = 100\n\n /** compute autolayout **/\n autoLayout = comfyWorkflowAutoLayout.bind(this)\n\n /** send the workflow and wait for it to finish (with all outputs downloaded) */\n run = async (p: RunSettings = {}): Promise<ComfyExecution> => {\n const execution = await this.start(p)\n await execution.done\n return execution\n }\n\n /** reset per-run node state so the same workflow can run again cleanly */\n private resetRunState(): void {\n this.done = false\n this.currentExecutingNode = null\n for (const node of this.nodes) {\n node.status = null\n node.progress = null\n node.progressRatio = 0\n }\n }\n\n /** send the workflow; returns the live execution (await `execution.done` yourself) */\n start = async (p: RunSettings = {}): Promise<ComfyExecution> => {\n // without a ws the prompt still RUNS on the host, but its messages route to a session\n // that is not ours, so `execution.done` never settles: a silent forever-hang, the one\n // failure mode with no error to read. DefinedWorkflow.run() connects for you\n if (this.host.ws == null)\n throw new Error(\n `🔴 host '${this.host.data.id}' was never connected — call \\`await host.connect()\\` before running a workflow`,\n )\n this.resetRunState()\n // snapshot: exactly what runs, frozen at send time (the live workflow stays editable)\n const snapshot: ExecutionSnapshot = {\n apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? 'use_stringified_numbers_only')),\n workflowJson: await this.toWorkflowJson(),\n }\n // ephemeral: rewrite in the SNAPSHOT only — the live graph stays editable/exportable as authored\n if (p.ephemeral) {\n const rewritten = rewriteSaveNodesToWebsocket(snapshot.apiJson)\n const hasWsSaver = Object.values(snapshot.apiJson).some((n) => n.class_type === 'SaveImageWebsocket')\n if (rewritten === 0 && !hasWsSaver)\n console.warn(\n `🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`,\n )\n }\n const out: ApiPromptInput = {\n client_id: this.host.comfySessionId,\n prompt: snapshot.apiJson,\n extra_data: {\n extra_pnginfo: {\n // regular ComfyUI metadata (drag the file in the editor -> the graph)\n workflow: snapshot.workflowJson,\n comfy_ts_workflow_id: this.id,\n comfy_ts_version: comfyts.version,\n },\n },\n }\n\n const res = await this.host.fetch('/prompt', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(out),\n })\n const promptInfoJson: unknown = await res.json()\n // a REJECTED prompt is not a malformed success: ComfyUI answers non-200 with its own\n // reason and no prompt_id, so validating first reported \"prompt_id must be a string\"\n // and threw away the sentence that says which node and which value it refused\n if (res.status !== 200) {\n throw new InvalidPromptError(\n `ComfyUI refused the prompt: ${describePromptRejection(promptInfoJson)}`,\n snapshot,\n promptInfoJson,\n )\n }\n const promptInfo: PromptInfo = softValidate(PromptInfo_ark, promptInfoJson)\n // settings + snapshot go through the constructor: the ctor flushes ws\n // messages that raced ahead, and those handlers need the settings\n const execution = new ComfyExecution(\n this,\n {\n id: promptInfo.prompt_id,\n executed: false,\n graphID: this.id,\n },\n {\n snapshot,\n save: p.save,\n ephemeral: p.ephemeral ?? false,\n // ephemeral implies the scrub unless the caller explicitly opted out\n scrubHistory: p.scrubHistory ?? p.ephemeral ?? false,\n onProgress: p.onProgress,\n logProgress: p.log ?? false,\n },\n )\n return execution\n }\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","/** having a bunch of sensible default will help slightly */\nexport function getUnionNameBasedOnFirstFoundEnumName(\n //\n enumName: string,\n hash: string,\n hashContent: string,\n): string {\n // core enums\n if (enumName === 'KSampler.sampler_name') return 'E_SamplerName'\n if (enumName === 'KSampler.scheduler') return 'E_SchedulerName'\n if (enumName === 'CheckpointLoaderSimple.ckpt_name') return 'E_CkptName'\n if (enumName === 'VAELoader.vae_name') return 'E_VaeName'\n if (enumName === 'LoraLoader.lora_name') return 'E_LoraName'\n // upscape methods\n if (enumName === 'LatentUpscale.upscale_method') return 'E_LatentUpscaleMethod'\n if (enumName === 'ImageScale.upscale_method') return 'E_ImageUpscaleMethod'\n // core objects\n if (enumName === 'LoadImage.image') return 'E_Image'\n if (enumName === 'LoadImageMask.channel') return 'E_Channel'\n // misc\n if (enumName === 'KSamplerAdvanced.add_noise') return 'E_EnableOrDisable'\n if (enumName === 'LatentRotate.rotation') return 'E_Rotation'\n if (enumName === 'LatentFlip.flip_method') return 'E_FlipMethod'\n if (enumName === 'CLIPLoader.type') return 'E_ClipType'\n if (enumName === 'UNETLoader.weight_dtype') return 'E_WeightDType'\n if (enumName === 'DualCLIPLoader.type') return 'E_DualClipType'\n if (enumName === 'CheckpointLoader.config_name') return 'E_CkptConfigName'\n\n // civitai_comfy_nodes\n if (enumName === 'civitai_comfy_nodes.CivitAI_Checkpoint_Loader.ckpt_name') return 'E_CivitAICkptName'\n\n // Impact-Specific\n if (enumName === 'Impact-Pack.SAMDetectorCombined.detection_hint') return 'E_ImpactDetectionHint'\n\n // Misc\n if (hashContent === 'false|true') return 'E_TrueOrFalse'\n if (hashContent === 'CPU|GPU') return 'E_CpuOrGpu'\n return 'E_' + hash\n}\n","export function pythonModuleToPrefix(pythonModule: string): string {\n // if (pythonModule == null) console.error(`[🔴🔴🔴🔴🔴🔴] `, pythonModule)\n if (pythonModule === 'nodes') return ''\n if (pythonModule.startsWith('comfy_extras.')) return '' //''\n // ships INSIDE the ComfyUI repo (upstream parks it under custom_nodes/):\n // the ephemeral-outputs saver reads `b.SaveImageWebsocket` like the core node it is\n if (pythonModule === 'custom_nodes.websocket_image_save') return ''\n if (pythonModule.startsWith('comfy_api_nodes.')) return pythonModule.replace('comfy_api_nodes.', 'api.')\n if (pythonModule.startsWith('custom_nodes.')) {\n // return `${pythonModuleToNamespace_(pythonModule.replace('custom_nodes.', ''))}.`\n return (\n pythonModule //\n // remove always present \"custom_nodes.\" prefix\n .replace(/^custom_nodes\\./i, '')\n // remove common ~comfyui prefixes and suffixes\n .replace(/^comfyui[-_]/i, '')\n .replace(/[-_]comfyui$/i, '')\n // remove common ~comfy prefixes and suffixes\n .replace(/^comfy[-_]/i, '')\n .replace(/[-_]comfy$/i, '')\n // remove common ~nodes prefixes and suffixes\n .replace(/^nodes[-_]/i, '')\n .replace(/[-_]node[-_]suite$/i, '') + '.'\n )\n }\n // unknown module layout: fall back to a sanitized module prefix instead of\n // crashing the whole codegen because of one unusual custom node\n console.warn(`[comfy-ts] unexpected pythonModule \"${pythonModule}\", using it as prefix as-is`)\n return `${pythonModule}.`\n}\n","import { pythonModuleToPrefix } from 'src/sdk-generator/_pythonModuleToNamespace.ts'\n\nexport const toQualifiedNodeKey = (pythonModule: string, nameInComfy: string): string => {\n return `${pythonModuleToPrefix(pythonModule)}${nameInComfy}`\n}\n","/** this class is used to buffer text and then write it to a file */\nexport class CodeBuffer {\n public tab: string = ' '\n constructor(\n private _indent: number = 0,\n lines: string[] = [],\n ) {\n for (const line of lines) this.writeLine(line)\n }\n\n content: string = ''\n\n // #region adding text\n newLine = (): string => (this.content += '\\n')\n line = (...txts: string[]): this => this.writeLine(txts.join(''))\n append = (str: string): string => (this.content += str)\n writeLine = (txt: string): this => {\n this.content +=\n txt\n .split('\\n')\n .map((line) => repeatStr(this._indent, this.tab) + line)\n .join('\\n') + '\\n'\n return this\n }\n w = (txt: string, opts: { if: boolean } = { if: true }): void => {\n if (opts.if) this.writeLine(txt)\n }\n\n // #region indentations\n indent = (): number => this._indent++\n deindent = (): number => this._indent--\n indented = (fn: () => void): void => {\n this._indent++\n fn()\n this._indent--\n }\n\n bar = (text: string): void => this.w(renderBar(text, '// '))\n\n // writeTS = (path: string) => {\n // // const prefix = `// FILE GENERATED: do not edit. Changes made manually will be overwritten.\\n\\n`\n // // const outPretty = prefix + prettify(this.content)\n // const outPretty = prettify(this.content)\n // writeFileSync(path, outPretty, 'utf-8')\n // }\n}\n\nexport const repeatStr = (x: number, str: string): string => {\n let out = ''\n for (let i = 0; i < x; i++) out += str\n return out\n}\n\nexport const renderBar = (text: string, prefix: string = ''): string => {\n const ___bar___ = '============================================================================='\n return (\n `${prefix}|${___bar___}|\\n` +\n `${prefix}| ${text} ${repeatStr(___bar___.length - text.length - 4, ' ')} |\\n` +\n `${prefix}|${___bar___}|`\n )\n}\n","const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/\n\nconst isValidJSKey = (s: string): boolean => {\n return regex.test(s)\n}\n\nexport const escapeJSKey = (s: string): string => {\n if (typeof s !== 'string') {\n return 'string'\n // console.log(s)\n // debugger\n }\n // ❌ probably wrong\n if (!isValidJSKey(s)) {\n // debugger\n return `\"${s}\"`\n }\n return s\n}\n\nexport const asJSAccessor = (s: string): string => {\n if (typeof s !== 'string') {\n return 'string'\n // console.log(s)\n // debugger\n }\n if (!isValidJSKey(s)) {\n // debugger\n return `[\"${s}\"]`\n }\n return `.${s}`\n}\n","import type { Maybe } from 'src/types/index.ts'\nimport { CodeBuffer } from 'src/utils/CodeBuffer.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport type { ComfyInputOpts, ComfyNodeSchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport type { ComfyUnionInfo, NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'\nimport { ComfyPrimitiveMapping } from 'src/sdk-generator/Primitives.ts'\n\nexport type NodeOwnEnum = {\n in: 'input' | 'output'\n ownName: string\n enum: ComfyUnionInfo\n}\n\nexport class ComfyNodeSchema {\n /** list of types the node has a single output of */\n _singleOutputs: Maybe<NodeOutputExt[]> = null\n\n get singleOutputs(): NodeOutputExt[] {\n if (this._singleOutputs != null) return this._singleOutputs\n const x: { [key: string]: number } = {}\n for (const i of this.outputs) x[i.typeName] = (x[i.typeName] ?? 0) + 1\n this._singleOutputs = this.outputs.filter((i) => x[i.typeName] === 1)\n return this._singleOutputs\n }\n\n constructor(\n public raw: ComfyNodeSchemaJSON,\n public nameInComfy: string,\n public nodeKey: string, // same but qualified to keep track of pythonNamespace\n public category: string,\n public inputs: NodeInputExt[],\n public outputs: NodeOutputExt[],\n public pythonModule: string,\n ) {\n this.category = this.category.replaceAll('/', '_')\n }\n\n codegenUI(): string {\n const b = new CodeBuffer()\n const p = b.w\n p(` ${escapeJSKey(this.nodeKey)}: {`)\n this.inputs.forEach((i, _ix) => {\n // 1/3\n if (i.isPrimitive) {\n const tsType = ComfyPrimitiveMapping[i.typeName]\n if (tsType == null) return console.log(`[🔶] invariant violation`)\n p(` ${escapeJSKey(i.nameInComfy)}: { kind: '${tsType}', type: ${tsType} }`)\n }\n // 2/3\n else if (i.isEnum) {\n p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: Union['${i.typeName}'] }`)\n // p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: '${this.nodeKey}.${i.nameInComfy}' }`) // prettier-ignore\n }\n // 3/3\n else {\n p(` // ${escapeJSKey(i.nameInComfy)}: { kind: 'object', type: ${i.typeName} }`)\n }\n })\n p(` }`)\n return b.content\n }\n\n renderOpts(opts?: ComfyInputOpts): Maybe<string> {\n if (opts == null) return null\n if (typeof opts === 'string') return null\n let out = '/**'\n if (opts.default != null) out += ` default=${JSON.stringify(opts.default)}`\n if (opts.min != null) out += ` min=${JSON.stringify(opts.min)}`\n if (opts.max != null) out += ` max=${JSON.stringify(opts.max)}`\n if (opts.step != null) out += ` step=${JSON.stringify(opts.step)}`\n out += ' */'\n return out\n }\n}\n\nexport const wrapQuote = (s: string): string => {\n if (s.includes(\"'\")) return `\"${s}\"`\n return `'${s}'`\n}\n","import type { Maybe } from 'src/types/index.ts'\nimport { CodeBuffer } from 'src/utils/CodeBuffer.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\n\nimport { type ComfyNodeSchema, wrapQuote } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport {\n classifySchemaInput,\n containerInstanceSlotType,\n isRecord,\n type DynamicComboOption,\n type RawInputSpecEntry,\n} from 'src/sdk-generator/inputWidgetKind.ts'\n\nconst isScalar = (x: unknown): x is string | number | boolean =>\n typeof x === 'string' || typeof x === 'number' || typeof x === 'boolean'\n\n/** a dynamic-combo branch input, typed the way its dotted prompt key is filled: inline enums\n * and COMBO option lists become literal unions, everything else stays a named slot */\nconst branchInputType = (entry: RawInputSpecEntry): string => {\n const opts = isRecord(entry.opts) ? entry.opts : null\n const literals = Array.isArray(entry.type) ? entry.type : Array.isArray(opts?.['options']) ? opts['options'] : []\n const scalars = literals.filter(isScalar)\n if (scalars.length > 0) return scalars.map((o) => JSON.stringify(o)).join(' | ')\n if (typeof entry.type === 'string') return `Accepts[${JSON.stringify(entry.type)}]`\n return 'string | number | boolean'\n}\n\n/** `& ({key:'a'; 'name.x'?: …} | {key:'b'})` — one member per branch, so a key from a branch\n * you did not select is a type error. Branch fields are optional: ComfyNode fills them\n * from the schema at serialization (agent/architecture.md, dynamic-combo fill) */\nconst dynamicComboUnion = (p: {\n name: string\n nameEscaped: string\n options: DynamicComboOption[]\n keyOptional: boolean\n}): string => {\n const members = p.options.map((opt) => {\n const fields = opt.inputs.map(\n (e) => `${escapeJSKey(`${p.name}.${e.name}`)}?: ${branchInputType(e)}`, //\n )\n const key = `${p.nameEscaped}${p.keyOptional ? '?' : ''}: ${JSON.stringify(opt.key)}`\n return `{ ${[key, ...fields].join('; ')} }`\n })\n return ` & (${members.join(' | ')})`\n}\n\n/**\n * convert a host id to the namespace name it gets inside the global `Comfy` namespace\n * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'\n */\nexport function hostIdToNamespace(hostId: string): string {\n const parts = hostId.split(/[^a-zA-Z0-9]+/).filter(Boolean)\n const ns = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('')\n if (ns.length === 0) throw new Error(`cannot derive a namespace from host id \"${hostId}\"`)\n // namespaces can't start with a digit\n return /^[0-9]/.test(ns) ? `Host${ns}` : ns\n}\n\nexport type CodegenOptions = {\n /** host id; drives both the `Comfy.Hosts` registry key and the namespace name */\n hostId: string\n /** module to import runtime-facing types from (default: 'comfy-ts') */\n packageName?: string\n}\n\n/**\n * emit the typed SDK for one host:\n *\n * declare global {\n * namespace Comfy {\n * namespace <HostNs> { IN / OUT / Node / Builder / Slots / Accepts / Union / ... }\n * interface Hosts { '<host-id>': <HostNs>.Sdk }\n * }\n * }\n */\nexport function codegenSDK(this: ComfySchema, opts: CodegenOptions): string {\n const ns = hostIdToNamespace(opts.hostId)\n const packageName = opts.packageName ?? 'comfy-ts'\n const b = new CodeBuffer()\n const p = b.w\n\n p(`/** generated by comfy-ts for host \"${opts.hostId}\" — do not edit */`)\n p(``)\n p(`import type { ComfyNode, ComfyNodeOutput, ComfyNodeMetadata, ComfyNodeSchemaJSON } from '${packageName}'`)\n p(``)\n p(`declare global {`)\n b.indent()\n\n p(`namespace Comfy {`)\n b.indent()\n\n p(`namespace ${ns} {`)\n b.indent()\n\n // #region PythonModules ----------------------------------------------------------------------\n p(`// #${''}region PythonModules`)\n p(`/** list of all python modules installed on this host */`)\n p(`export type PythonModules =`)\n b.indent()\n const pythonModulesArr: [string, string[]][] = Array.from(this.pythonModules.entries()) //\n .toSorted((a, b) => a[0].localeCompare(b[0]))\n for (const [k, v] of pythonModulesArr) {\n p(`/**`)\n p(`* Nodes: ${v.join(', ')}`)\n p(`*/`)\n p(`| ${wrapQuote(k)}`)\n }\n b.deindent()\n p(`// #${''}endregion`)\n\n // #region IN ---------------------------------------------------------------------------------\n const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey))\n p(`interface IN {`)\n b.indent()\n for (const n of nodes) {\n p(`${escapeJSKey(n.nodeKey)}: {`)\n // dynamic combos leave the flat body and come back as an intersected\n // union suffix, one member per branch (agent/sdk-codegen.md)\n const comboSuffixes: string[] = []\n for (const i of n.inputs) {\n // autogrow container: emit dotted instance keys, never the container\n // decl itself — the backend prompt input is `<name>.<inst>`, the\n // first template.min instances required (agent/sdk-codegen.md)\n const kind = classifySchemaInput(i)\n if (kind.kind === 'dynamic-container') {\n const instType = containerInstanceSlotType(i.opts)\n if (instType != null) {\n kind.instanceNames.forEach((instName, ix) => {\n const opt = ix >= kind.requiredCount ? '?' : ''\n p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`)\n })\n }\n continue\n }\n if (kind.kind === 'dynamic-combo') {\n const optsDyn = typeof i.opts === 'string' ? null : i.opts\n comboSuffixes.push(\n dynamicComboUnion({\n name: i.nameInComfy,\n nameEscaped: i.nameInComfyEscaped,\n options: kind.options,\n keyOptional: optsDyn?.default !== undefined || !i.required,\n }),\n )\n continue\n }\n const opts_ = typeof i.opts === 'string' ? null : i.opts\n let type = `Accepts[${JSON.stringify(i.typeName)}]`\n // COMBO inputs (ComfyUI ≥ 0.3.x) carry literal choices in opts.options\n const comboOptions =\n i.typeName === 'COMBO' && Array.isArray(opts_?.options)\n ? opts_.options.filter(\n (o): o is string | number | boolean =>\n typeof o === 'string' || typeof o === 'number' || typeof o === 'boolean',\n )\n : []\n if (comboOptions.length > 0) {\n type = `${comboOptions.map((o) => JSON.stringify(o)).join(' | ')} | ${type}`\n }\n // custom text/primitive widget types (placeholder/multiline/default in opts)\n // also accept the raw literal, e.g. AUTOCOMPLETE_TEXT_LORAS is just a string\n else if (opts_ && !i.isPrimitive && !i.isEnum) {\n if (typeof opts_.default === 'string' || opts_.placeholder != null || opts_.multiline != null) {\n type = `string | ${type}`\n } else if (typeof opts_.default === 'number') {\n type = `number | ${type}`\n } else if (typeof opts_.default === 'boolean') {\n type = `boolean | ${type}`\n }\n }\n if (opts_) {\n const rendered = n.renderOpts(opts_)\n if (rendered) p(` ${rendered}`)\n }\n const canBeOmmited = opts_?.default !== undefined || !i.required\n p(` ${i.nameInComfyEscaped}${canBeOmmited ? '?' : ''}: ${type}`)\n }\n p(`}${comboSuffixes.join('')},`)\n }\n b.deindent()\n p('}')\n p('')\n\n // #region OUT --------------------------------------------------------------------------------\n p(`interface OUT {`)\n b.indent()\n for (const n of nodes) {\n p(`${escapeJSKey(n.nodeKey)}: {`)\n n.outputs.forEach((i, ix) => {\n p(` ${escapeJSKey(i.outKey)}: ComfyNodeOutput<'${i.typeName}', ${ix}>,`)\n })\n p(`}`)\n }\n b.deindent()\n p('}')\n\n // #region Node -------------------------------------------------------------------------------\n p(`interface Node {`)\n for (const n of nodes) {\n p(\n ` ${escapeJSKey(n.nodeKey)}: ComfyNode<IN[${JSON.stringify(n.nodeKey)}], OUT[${JSON.stringify(n.nodeKey)}]> & {`,\n )\n for (const hassingle of n.singleOutputs) {\n p(` ${escapeJSKey(`_${hassingle.typeName}`)}: ComfyNodeOutput<'${hassingle.typeName}'>`)\n }\n p(` }`)\n }\n p('}')\n\n // #region Builder ----------------------------------------------------------------------------\n p(`interface Builder {`)\n for (const n of nodes) {\n const baseDescription = `displayName=\"${n.raw.display_name}\" category=\"${n.category}\" name=\"${n.nameInComfy}\" output=[${n.outputs.map((o) => o.outKey).join(', ')}]`\n if (n.raw.description) {\n p(` /**`)\n p(\n n.raw.description\n .split('\\n')\n .map((i) => ` * ${i}`)\n .join('\\n'),\n )\n p(` * ${baseDescription}`)\n p(` **/`)\n } else {\n p(` /** ${baseDescription} */`)\n }\n p(\n ` ${escapeJSKey(n.nodeKey)}(p: IN[${JSON.stringify(n.nodeKey)}], meta?: ComfyNodeMetadata): Node[${JSON.stringify(n.nodeKey)}]`,\n )\n }\n p(`}`)\n\n // #region Slots ------------------------------------------------------------------------------\n p(`interface Slots {`)\n for (const e of this.knownUnionByHash.values()) {\n p(' // ' + e.unionName)\n for (const alias of e.enumNames) {\n p(` ${escapeJSKey(alias)}: Union['${e.unionName}']`)\n }\n }\n p(`}`)\n\n // #region Embeddings -------------------------------------------------------------------------\n p(`type Embeddings = ${this.data.embeddings.map((e) => wrapQuote(e)).join(' | ') || '\"\"'}`)\n\n const slotTypes = [...this.knownSlotTypes.values()] //\n .map((comfyType) => ({\n comfyType,\n tsType: this.toTSType(comfyType),\n tsType2: this.toAcceptsType(comfyType),\n }))\n .sort((a, b) => b.tsType.length - a.tsType.length)\n\n // #region Producer ---------------------------------------------------------------------------\n p('')\n p('interface Producer {')\n b.indent()\n for (const tp of slotTypes) {\n const allProducingNodes: Maybe<ComfyNodeSchema[]> = this.nodesByProduction[tp.comfyType]\n if (allProducingNodes) {\n p(`${escapeJSKey(tp.comfyType)}: Pick<Builder, ${allProducingNodes.map((i) => `'${i.nodeKey}'`).join(' | ')}>`)\n } else {\n p(`${escapeJSKey(tp.comfyType)}: {}, // no node can output this type.`)\n }\n }\n b.deindent()\n p('}')\n\n // #region Accepts -----------------------------------------------------------------------------\n p(`interface Accepts {`)\n b.indent()\n // 1/3\n p('// injected bottom type (broken/null input specs land here)')\n p(`INVALID_null: any`)\n\n // 2/3\n p('')\n p('// named slot types: everything an input of that type accepts')\n for (const t of slotTypes) {\n p(\n `${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`,\n )\n }\n\n // 3/3\n p('')\n p('// enum unions: literal values or an output carrying one')\n for (const t of this.knownUnionByHash.values()) {\n p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`)\n }\n b.deindent()\n p(`}\\n`)\n\n // #region Union ------------------------------------------------------------------------------\n p('interface Union {')\n for (const e of this.knownUnionByHash.values()) {\n if (e.values.length > 0) {\n p(` // ${JSON.stringify(e.enumNames)}`)\n p(` ${e.unionName}: ${e.values.map((v) => `${JSON.stringify(v)}`).join(' | ')}`)\n } else {\n p(` ${e.unionName}: '🔴' // never`)\n }\n }\n p('}')\n\n // #region HasSingle --------------------------------------------------------------------------\n p(`export interface HasSingle {`)\n for (const t of slotTypes) {\n p(` ${escapeJSKey(t.comfyType)}: { '_${t.comfyType}': ${t.tsType} }`)\n }\n p(`}`)\n\n for (const t of this.enumsAppearingInOutput.values()) {\n p(`export interface HasSingle_${t} { _${t}: Union['${t}'] }`)\n }\n\n // #region Schemas ----------------------------------------------------------------------------\n p(`export type Schemas = { [k in NodeType]: ComfyNodeSchemaJSON }`)\n p(`export type NodeType = ${this.nodes.map((i) => `'${i.nodeKey}'`).join(' | ')}`)\n\n // #region Sdk --------------------------------------------------------------------------------\n p(``)\n p(`/** everything above, packaged for the Comfy.Hosts registry */`)\n p(`interface Sdk {`)\n p(` IN: IN`)\n p(` OUT: OUT`)\n p(` Node: Node`)\n p(` Builder: Builder`)\n p(` Slots: Slots`)\n p(` Accepts: Accepts`)\n p(` Union: Union`)\n p(` Producer: Producer`)\n p(` Embeddings: Embeddings`)\n p(` Schemas: Schemas`)\n p(` NodeType: NodeType`)\n p(`}`)\n\n b.deindent()\n p(`}`) // end namespace <HostNs>\n\n p(``)\n p(`interface Hosts {`)\n p(` ${wrapQuote(opts.hostId)}: ${ns}.Sdk`)\n p(`}`)\n\n b.deindent()\n p('}') // end namespace Comfy\n\n b.deindent()\n p('}') // end declare global\n p(``)\n p(`export {}`)\n\n return b.content\n}\n","import type { Branded } from 'src/types/index.ts'\nimport type { ComfyInputOpts } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\n\nexport type ComfyUnionHash = string // '26c34bf761d4be4554ab944105c5a3c017c99453\nexport type ComfyUnionName = string // 'E_26c34bf761d4be4554ab944105c5a3c017c99453'\nexport type ComfyUnionValue = string | boolean | number\n\nexport type ComfyPythonModule = string\nexport type NodeNameInComfy = string\nexport type QualifiedNodeKey = string\n\n/**\n * the textual name of a slot type (slot = input or output of a node),\n * e.g. 'MODEL', 'IMAGE', 'E_CkptName'.\n * Branded string — internals never depend on the global Comfy namespace\n * (that would break host encapsulation: slot types are per-host).\n */\nexport type ComfyNodeSlotTypeName = Branded<string, { SlotTypeName: true }>\nexport const asComfyNodeSlotTypeName = (x: string): ComfyNodeSlotTypeName => x as ComfyNodeSlotTypeName\n\n/** a fully-qualified slot name, e.g. 'LoadImage.image' or 'KSampler.LATENT.OUT' */\nexport type ComfyNodeSlotName = Branded<string, { SlotName: true }>\nexport const asComfyNodeSlotName = (x: string): ComfyNodeSlotName => x as ComfyNodeSlotName\n\nexport type EmbeddingName = Branded<string, { Embedding: true }>\n\nexport type NodeInputExt = {\n slotName: ComfyNodeSlotName\n nameInComfy: string\n nameInComfyEscaped: string\n typeName: ComfyNodeSlotTypeName\n opts?: ComfyInputOpts\n isPrimitive: boolean\n isEnum: boolean\n required: boolean\n index: number\n}\n\nexport type NodeOutputExt = {\n slotName: ComfyNodeSlotName\n typeName: ComfyNodeSlotTypeName\n outKey: string\n nameInComfy: string\n isPrimitive: boolean\n}\n\nexport type ComfyUnionInfo = {\n hash: ComfyUnionHash\n unionName: ComfyUnionName\n values: ComfyUnionValue[]\n enumNames: ComfyNodeSlotName[]\n}\n\n/** an image file name as known by the host (hash-named upload or existing input) */\nexport type ComfyImageName = Branded<string, { ComfyImageName: true }>\nexport const asComfyImageName = (x: string): ComfyImageName => x as ComfyImageName\n","import { sha1HexOfString } from 'src/utils/sha1.ts'\nimport { statelessRegex } from 'src/utils/matchesRegex.ts'\nimport { getUnionNameBasedOnFirstFoundEnumName } from 'src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts'\nimport { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'\nimport { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'\nimport type { ComfyEnumDef, ComfyNodeSchemaJSON, ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport { codegenSDK } from 'src/sdk-generator/comfyui-sdk-codegen.ts'\nimport { classifyWidgetInput, containerInstanceSlotType } from 'src/sdk-generator/inputWidgetKind.ts'\nimport {\n asComfyNodeSlotName,\n asComfyNodeSlotTypeName,\n type ComfyImageName,\n type ComfyNodeSlotName,\n type ComfyNodeSlotTypeName,\n type ComfyPythonModule,\n type ComfyUnionHash,\n type ComfyUnionInfo,\n type ComfyUnionName,\n type ComfyUnionValue,\n type EmbeddingName,\n type NodeInputExt,\n type NodeNameInComfy,\n type NodeOutputExt,\n type QualifiedNodeKey,\n} from 'src/sdk-generator/comfyui-types.ts'\nimport {\n ComfyDefaultNodeWhenUnknown_Name,\n ComfyDefaultNodeWhenUnknown_Schema,\n ComfyPrimitiveMapping,\n ComfyPrimitives,\n} from 'src/sdk-generator/Primitives.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { escapeJSKey } from 'src/utils/escapeJSKey.ts'\nimport { logInfo } from 'src/utils/log.ts'\n\nexport type ComfySchemaId = string\n\nexport type ComfySchemaData = {\n spec: ComfySchemaJSON\n embeddings: string[]\n}\n\n/**\n * ONE host's schema: the parsed view of its object_info.json + embeddings.\n * Owns union dedup (by sha1 of values), node indexing, and the per-host\n * sdk codegen (`codegenDTS`).\n */\nexport class ComfySchema {\n codegenDTS = codegenSDK.bind(this)\n\n constructor(public data: ComfySchemaData) {\n this.parse()\n }\n\n update(data: Partial<ComfySchemaData>): void {\n const prev: ComfySchemaData = { spec: this.data.spec, embeddings: this.data.embeddings }\n Object.assign(this.data, data)\n try {\n this.parse()\n this.isInvalid = false\n } catch (error) {\n console.error(`❌ [ComfySchema.update] bad schema — keeping the previous one`, error)\n // roll back: a failed update must not leave half-built indexes in use\n this.data = prev\n try {\n this.parse()\n } catch {\n // previous data unparsable too (first update): indexes stay empty\n }\n this.isInvalid = true\n }\n }\n\n isInvalid: boolean = false\n\n /** number of nodes in the current schema (quick way to check your instance infos) */\n get size(): number {\n return Object.keys(this.data.spec).length\n }\n\n // #region parsed indexes\n knownSlotTypes = new Set<ComfyNodeSlotTypeName>()\n knownUnionBySlotName = new Map<ComfyNodeSlotName, ComfyUnionInfo>()\n knownUnionByHash = new Map<ComfyUnionHash, ComfyUnionInfo>()\n knownUnionByName = new Map<ComfyUnionName, ComfyUnionInfo>()\n nodes: ComfyNodeSchema[] = []\n pythonModuleByNodeKey: Map<QualifiedNodeKey, ComfyPythonModule> = new Map()\n pythonModuleByNodeNameInComfy: Map<NodeNameInComfy, ComfyPythonModule> = new Map()\n nodesByNameInComfy: { [key: NodeNameInComfy]: ComfyNodeSchema } = {}\n nodesByKey: { [key: QualifiedNodeKey]: ComfyNodeSchema } = {}\n nodesByProduction: { [key in ComfyNodeSlotTypeName]?: ComfyNodeSchema[] } = {}\n\n // some nodes output anonymous unions. we need to keep track of them for codegen\n enumsAppearingInOutput = new Set<ComfyNodeSlotTypeName>()\n\n pythonModules = new Map<string, NodeNameInComfy[]>()\n\n // #region parse\n private parse(): void {\n // reset all indexes: parse() re-runs on every update()\n this.knownSlotTypes.clear()\n this.knownUnionBySlotName.clear()\n this.knownUnionByHash.clear()\n this.knownUnionByName.clear()\n this.nodes = []\n this.pythonModuleByNodeKey.clear()\n this.pythonModuleByNodeNameInComfy.clear()\n this.nodesByNameInComfy = {}\n this.nodesByKey = {}\n this.nodesByProduction = {}\n this.enumsAppearingInOutput.clear()\n this.pythonModules.clear()\n\n // skip log for the initial dummy empty data\n if (this.data.embeddings.length > 0 || Object.keys(this.data.spec).length > 0)\n this.log(`parsing ComfyUI object_info.json`)\n\n const entries: [string, ComfyNodeSchemaJSON][] = Object.entries(this.data.spec)\n entries.push([ComfyDefaultNodeWhenUnknown_Name, ComfyDefaultNodeWhenUnknown_Schema])\n\n for (const [KK, VV] of entries) {\n // record python module\n const pythonModule = VV.python_module\n const prev = this.pythonModules.get(pythonModule)\n if (prev == null) this.pythonModules.set(pythonModule, [KK])\n else prev.push(KK)\n\n const nodeNameInComfy = KK\n const nodeDef = VV\n const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy)\n\n if (typeof nodeDef.output === 'string') {\n console.log(\n `[❌ ERROR] nodeDef ${nodeDef.name} has an invalid output definition: ${JSON.stringify(nodeDef.output)}`,\n )\n nodeDef.output = []\n }\n this.pythonModuleByNodeKey.set(nodeKey, pythonModule)\n this.pythonModuleByNodeNameInComfy.set(nodeNameInComfy, pythonModule)\n\n const inputs: NodeInputExt[] = []\n const outputs: NodeOutputExt[] = []\n const node = new ComfyNodeSchema(VV, nodeNameInComfy, nodeKey, nodeDef.category, inputs, outputs, pythonModule)\n\n // INDEX NODE\n this.nodesByNameInComfy[nodeNameInComfy] = node\n this.nodesByKey[nodeKey] = node\n this.nodes.push(node)\n\n // #region outputs ----------------------------------------------------------------------\n const nameCountDict: { [key: string]: number } = {}\n for (const [ix, slotType] of nodeDef.output.entries()) {\n const rawOutputSlotName =\n nodeDef.output_name[ix] || //\n (typeof slotType === 'string' ? slotType : `input_${ix}`)\n\n const outputNameInComfy = rawOutputSlotName\n const at = (nameCountDict[outputNameInComfy] ??= 0)\n const outKeyValue = at === 0 ? outputNameInComfy : `${outputNameInComfy}_${at}`\n nameCountDict[outputNameInComfy]++\n\n let slotTypeName: ComfyNodeSlotTypeName\n const outputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${outKeyValue}.OUT`)\n\n // 1. Primitive\n if (typeof slotType === 'string') {\n slotTypeName = asComfyNodeSlotTypeName(slotType)\n this.knownSlotTypes.add(slotTypeName)\n }\n // 2. ENUM\n else if (Array.isArray(slotType)) {\n const RESX = this.processSlot({ pythonModule, slotName: outputSlotName, comfyUnionDef: slotType })\n slotTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n this.enumsAppearingInOutput.add(slotTypeName)\n }\n // 3. ????\n else {\n throw new Error(`invalid output ${ix} \"${slotType}\" in node \"${nodeNameInComfy}\"`)\n }\n\n // index production\n const arr = this.nodesByProduction[slotTypeName]\n if (arr == null) this.nodesByProduction[slotTypeName] = [node]\n else arr.push(node)\n\n outputs.push({\n slotName: outputSlotName,\n typeName: slotTypeName,\n nameInComfy: outputNameInComfy,\n outKey: outKeyValue,\n isPrimitive: false,\n })\n }\n\n // #region inputs ----------------------------------------------------------------------\n const optionalInputs = Object.entries(nodeDef.input?.optional ?? {}) //\n .map(([name, spec]) => ({ required: false, name, spec }))\n\n const requiredInputs = Object.entries(nodeDef.input?.required ?? {}) //\n .map(([name, spec]) => ({ required: true, name, spec }))\n // when an input is BOTH required and optional (seen in the wild), keep the optional one\n .filter((i) => optionalInputs.find((oi) => oi.name === i.name) == null)\n const allInputs = [...requiredInputs, ...optionalInputs]\n\n for (const ipt of allInputs) {\n const inputNameInComfy = ipt.name\n const typeDef = ipt.spec\n const slotType = typeDef[0]\n const slotOpts = typeDef[1]\n\n let inputTypeName: ComfyNodeSlotTypeName\n const inputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${inputNameInComfy}`)\n\n // 1/4 broken input (null type)\n if (slotType == null) {\n const RESX = this.processSlot({ pythonModule, slotName: inputSlotName, comfyUnionDef: ['❌'] })\n inputTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n }\n // 2/4 named slot type\n else if (typeof slotType === 'string') {\n inputTypeName = asComfyNodeSlotTypeName(slotType)\n this.knownSlotTypes.add(inputTypeName)\n }\n // 3/4 inline enum\n else if (Array.isArray(slotType)) {\n const RESX = this.processSlot({ pythonModule, slotName: inputSlotName, comfyUnionDef: slotType })\n inputTypeName = asComfyNodeSlotTypeName(RESX.unionName)\n }\n // 4/4\n else {\n throw new Error(\n `invalid schema (${JSON.stringify(slotType)}) for input \"${\n ipt.name\n }\" in node \"${nodeNameInComfy}\" (type: ${typeof slotType}; expected: Array | string)`,\n )\n }\n\n // autogrow container: the declaration is never a prompt input\n // (instances are `<name>.<inst>` link slots) — never required, and\n // its template sub-input slot type registers like any slot so\n // codegen can type the dotted instance keys (agent/sdk-codegen.md)\n const widgetKind =\n typeof slotType === 'string'\n ? classifyWidgetInput({ name: ipt.name, type: slotType, opts: slotOpts })\n : null\n const isAutogrowContainer = widgetKind?.kind === 'dynamic-container'\n if (isAutogrowContainer) {\n const instType = containerInstanceSlotType(slotOpts)\n if (instType != null) this.knownSlotTypes.add(asComfyNodeSlotTypeName(instType))\n }\n // dynamic combo: a branch input is typed by its dotted prompt key,\n // so its slot type must register like any slot (agent/sdk-codegen.md)\n if (widgetKind?.kind === 'dynamic-combo') {\n for (const opt of widgetKind.options) {\n for (const entry of opt.inputs) {\n if (typeof entry.type === 'string') this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type))\n }\n }\n }\n\n node.inputs.push({\n slotName: inputSlotName,\n required: ipt.required && !isAutogrowContainer,\n nameInComfy: inputNameInComfy,\n nameInComfyEscaped: escapeJSKey(inputNameInComfy),\n typeName: inputTypeName,\n opts: slotOpts,\n isPrimitive: ComfyPrimitives.includes(inputTypeName),\n isEnum: this.knownUnionByName.has(inputTypeName),\n index: node.inputs.length,\n })\n }\n }\n }\n\n // #region processSlot\n processSlot = (p: {\n pythonModule: string\n slotName: ComfyNodeSlotName\n comfyUnionDef: ComfyEnumDef\n }): ComfyUnionInfo => {\n // 1. build enum\n const enumValues: ComfyUnionValue[] = []\n for (const enumValue of p.comfyUnionDef) {\n if (typeof enumValue === 'string') enumValues.push(enumValue)\n else if (typeof enumValue === 'boolean') enumValues.push(enumValue)\n else if (typeof enumValue === 'number') enumValues.push(enumValue)\n else enumValues.push(enumValue.content)\n }\n // 2. hash its value\n const hashContent =\n enumValues.length === 0 //\n ? `[[empty]]`\n : enumValues.sort().join('|')\n const hash = sha1HexOfString(hashContent).slice(0, 8)\n\n // 3. retrieve or create an EnumInfo\n let unionInfo: Maybe<ComfyUnionInfo> = this.knownUnionByHash.get(hash)\n if (unionInfo == null) {\n const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent)\n unionInfo = { hash, unionName, values: enumValues, enumNames: [] }\n this.knownUnionByHash.set(hash, unionInfo)\n this.knownUnionByName.set(unionName, unionInfo)\n }\n unionInfo.enumNames.push(p.slotName)\n\n // 4. store enum by name\n this.knownUnionBySlotName.set(p.slotName, unionInfo)\n return unionInfo\n }\n\n private log(...args: unknown[]): void {\n logInfo(`[👅]: ${args.join(' ')}`)\n }\n\n toTSType(t: string): string {\n // '*' is ComfyUI's wildcard: any output or primitive fits\n if (t === '*') return `string | number | boolean | ComfyNodeOutput<string, number>`\n return ComfyPrimitiveMapping[t]\n ? `${ComfyPrimitiveMapping[t]} | ComfyNodeOutput<'${t}'>`\n : `ComfyNodeOutput<'${t}'>`\n }\n\n toAcceptsType(t: string): string {\n return `ComfyNodeOutput<'${t}'>`\n }\n\n // #region discovery helpers\n /**\n * every possible value for a given slot, straight from the live schema.\n * e.g. schema.values('LoraLoader.lora_name') -> all loras on this host\n */\n values(slotName: string): ComfyUnionValue[] {\n return this.knownUnionBySlotName.get(asComfyNodeSlotName(slotName))?.values ?? []\n }\n\n /** string values only (most enums are), for quick discovery */\n stringValues(slotName: string): string[] {\n return this.values(slotName).filter((v): v is string => typeof v === 'string')\n }\n\n /**\n * for now, simply ensure that the number of parsed nodes matches the number\n * of nodes present in the object_info.json\n */\n RUN_BASIC_CHECKS = (): void => {\n const numNodesInSource = Object.keys(this.data.spec).length\n // +1: the injected UnknownNodeXX default schema\n const numNodesInSchema = this.nodes.length - 1\n if (numNodesInSource !== numNodesInSchema) {\n console.log(`🔴 parsed ${numNodesInSchema} nodes but object_info has ${numNodesInSource}`)\n }\n }\n\n hasEmbedding(embedding: string): embedding is EmbeddingName {\n return this.data.embeddings.includes(embedding)\n }\n\n hasLora(loraName: string): boolean {\n return this.getLoras().includes(loraName)\n }\n\n /** all loras on the host, optionally narrowed by a regex */\n getLoras = (filter?: RegExp): string[] => {\n const all = this.stringValues('LoraLoader.lora_name')\n const stateless = filter == null ? null : statelessRegex(filter)\n return stateless == null ? all : all.filter((n) => stateless.test(n))\n }\n\n hasImage(imgName: string): imgName is ComfyImageName {\n return this.getImages().includes(imgName)\n }\n\n getImages = (): string[] => {\n return this.stringValues('LoadImage.image')\n }\n\n /**\n * only use this function after an upload success,\n * when you say this asset is now part of ComfyUI\n **/\n unsafely_addImageInSchemaWithoutReloading = (imgName: ComfyImageName): void => {\n const enumInfo = this.knownUnionBySlotName.get(asComfyNodeSlotName('LoadImage.image'))\n if (enumInfo == null) throw new Error(`LoadImage.image not found`)\n enumInfo.values.push(imgName)\n }\n\n hasCheckpoint(ckptName: string): boolean {\n return this.getCheckpoints().includes(ckptName)\n }\n\n getCheckpoints = (): string[] => {\n return this.stringValues('CheckpointLoaderSimple.ckpt_name')\n }\n}\n","import { scope, type } from 'arktype'\n\nexport const ComfyUIObjectInfoScope = scope({\n ComfySchemaJSON: { '[string]': 'ComfyNodeSchemaJSON' },\n ComfyNodeSchemaJSON: {\n input: {\n 'required?': { '[string]': 'ComfyInputSpec' },\n 'optional?': { '[string]': 'ComfyInputSpec' },\n 'hidden?': { '[string]': 'ComfyInputHiddenEntry' },\n },\n 'input_order?': {\n 'required?': 'string[]',\n 'optional?': 'string[]',\n 'hidden?': 'string[]',\n },\n output: 'ComfyInputType[]',\n output_is_list: 'boolean[]',\n output_name: 'string[]',\n name: 'string',\n display_name: 'string',\n description: 'string',\n /** */\n python_module: 'string',\n category: 'string',\n output_node: 'boolean',\n 'output_tooltips?': 'string[]',\n // Stability Flags\n 'deprecated?': 'boolean',\n 'experimental?': 'boolean',\n },\n ComfyInputSpecAlt1: ['ComfyInputType', 'ComfyInputOpts'],\n ComfyInputSpecAlt2: ['ComfyInputType'],\n // means it's broken: some nodes declare an input whose spec is literally\n // [null] — accepted here so ONE bad node cannot fail a whole schema parse\n ComfyInputSpecAlt3: type([type.null]),\n ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,\n\n ComfyInputType: `string | ComfyEnumDef`,\n\n ComfyInputHiddenEntry_broken1: '\"CHOOSE\"[][]', // BROKEN STUFF (e.g. found in several 'rgthree' nodes)\n ComfyInputHiddenEntry_broken2: type.Record('string', type.unknown), // BROKEN STUFF (e.g. found in \"ttN xyPlot\")\n ComfyInputHiddenEntry: 'string | ComfyInputHiddenEntry_broken1 | ComfyInputHiddenEntry_broken2 ',\n\n ComfyInputOpts_simple: 'string',\n ComfyInputOpts_advanced: {\n // 💬 2025-06-11 rvion: \"ComfyInputOpts_advanced\" added because of Segment.input.optional.background : Segment.input.optional.background[1].tooltip must be a string or null (was an object) or Segment.input.optional.background must be exactly length 1 (was 2)\n 'tooltip?': 'string | null | ComfyInputOpts_advanced',\n 'multiline?': 'boolean | null',\n\n // 💬 2025-06-11 rvion: \"number[]\" added because of CreateShapeImageOnPath.input.optional.size_multiplier : CreateShapeImageOnPath.input.optional.size_multiplier[1].default must be a number, a string, boolean or null (was an object) or CreateShapeImageOnPath.input.optional.size_multiplier must be exactly length 1 (was 2)\n 'default?': 'boolean | number | string | null | number[]',\n\n 'forceInput?': 'boolean | null',\n 'min?': 'number | null',\n 'round?': 'boolean | number | null',\n 'max?': 'number | null',\n 'step?': 'number | null',\n /** Observed on 2024-11-01; 171 occurrences */\n 'dynamicPrompts?': 'boolean',\n\n /** text widgets (e.g. LoraManager autocomplete fields) */\n 'placeholder?': 'string | null',\n\n /** COMBO-typed inputs (ComfyUI ≥ 0.3.x) carry their choices here */\n 'options?': 'unknown[] | null',\n 'multiselect?': 'boolean | null',\n\n // 💬 2025-06-11 rvion: \"0\" added because of CustomControlNetWeightsFluxFromList.input.optional.autosize : CustomControlNetWeightsFluxFromList.input.optional.autosize[1].padding must be boolean (was 0) or CustomControlNetWeightsFluxFromList.input.optional.autosize must be exactly length 1 (was 2)\n 'padding?': 'boolean | 0',\n },\n ComfyInputOpts: 'ComfyInputOpts_simple | ComfyInputOpts_advanced',\n\n ComfyEnumIllustratedItem: {\n content: 'string',\n 'image?': 'string | null',\n },\n ComfyEnumItem: 'string | number | boolean | ComfyEnumIllustratedItem',\n ComfyEnumDef: `ComfyEnumItem[]`,\n})\n\nconst types = ComfyUIObjectInfoScope.export()\n\nexport type ComfySchemaJSON = typeof types.ComfySchemaJSON.infer\nexport type ComfyNodeSchemaJSON = typeof types.ComfyNodeSchemaJSON.infer\nexport type ComfyInputSpec = typeof types.ComfyInputSpec.infer\nexport type ComfyInputType = typeof types.ComfyInputType.infer\nexport type ComfyEnumDef = typeof types.ComfyEnumDef.infer\nexport type ComfyInputOpts = typeof types.ComfyInputOpts.infer\n\nexport const ComfySchemaJSON_ark = types.ComfySchemaJSON\nexport const ComfyNodeSchemaJSON_ark = types.ComfyNodeSchemaJSON\nexport const ComfyInputSpec_ark = types.ComfyInputSpec\nexport const ComfyInputType_ark = types.ComfyInputType\nexport const ComfyEnumDef_ark = types.ComfyEnumDef\nexport const ComfyInputOpts_ark = types.ComfyInputOpts\n","const tab = ' '\n\nexport function readableStringify(obj: unknown, maxLevel = 3, level = 0): string {\n if (level > maxLevel) return JSON.stringify(obj)\n if (typeof obj !== 'object' || obj === null) return JSON.stringify(obj)\n const indent = ' '.repeat(level + 1)\n let result = '{\\n'\n const keys = Object.keys(obj)\n for (let i = 0; i < keys.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: don't care\n const key = keys[i]!\n // biome-ignore lint/suspicious/noExplicitAny: don't care\n const value = (obj as any)[key]\n if (value === undefined) continue\n const valueType = typeof value\n\n if (i > 0) result += ','\n const thisIndent = i > 0 ? indent.slice(1) : indent\n if (Array.isArray(value)) {\n result += `${thisIndent}${JSON.stringify(key)}: ${JSON.stringify(value)}`\n } else if (valueType === 'object' && value !== null) {\n result += `${thisIndent}${JSON.stringify(key)}: ${readableStringify(value, maxLevel, level + 1)}`\n } else {\n const formattedValue = valueType === 'string' ? JSON.stringify(value) : value\n result += `${thisIndent}${JSON.stringify(key)}: ${formattedValue}`\n }\n result += '\\n'\n }\n result += `${tab.repeat(Math.max(0, level))}}`\n\n return result\n}\n","import { type } from 'arktype'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\n\nexport type ComfyManagerAPIModelList = typeof ComfyManagerAPIModelList_ark.infer\nexport const ComfyManagerAPIModelList_ark = type({\n models: type({\n name: type.string.as<KnownModel_Name>(),\n installed: `'False' | 'True' | 'Update'`,\n }).array(),\n})\n","import { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\n\nexport type ComfyManagerAPIPluginList = typeof ComfyManagerAPIPluginList_ark.infer\nexport const ComfyManagerAPIPluginList_ark = type({\n custom_nodes: type({\n title: type.string.as<KnownComfyPluginTitle>(),\n installed: `'False' | 'True' | 'Update'`,\n }).array(),\n chanel: 'string',\n})\n","/** 🔶 NAMING DISCLAIMER: I call a \"custom node package\" => \"PLUGIN\" */\n\nimport type { Type } from 'arktype'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport type { ComfyManagerAPIFetchPolicy } from 'src/manager/types/ComfyManagerAPIFetchPolicy.ts'\nimport {\n type ComfyManagerAPIModelList,\n ComfyManagerAPIModelList_ark,\n} from 'src/manager/types/ComfyManagerAPIModelList.ts'\nimport {\n type ComfyManagerAPIPluginList,\n ComfyManagerAPIPluginList_ark,\n} from 'src/manager/types/ComfyManagerAPIPluginList.ts'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { logError as toastError, logSuccess as toastSuccess } from 'src/utils/log.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport type { PluginInstallStatus } from 'src/host/Requirements.ts'\n\nexport class ComfyManager {\n constructor(\n public host: {\n getServerHostHTTP: () => string\n fetch: (route: string, init?: RequestInit, p?: { apiPrefix?: boolean }) => Promise<Response>\n },\n ) {\n // void this.updateHostPluginsAndModels()\n }\n\n get registry(): ComfyRegistry {\n return comfyts.registry\n }\n\n fetchPluginsAndModels = async (): Promise<void> => {\n const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()])\n this.pluginList = _pluginList\n this.modelList = _modelList\n }\n\n // -----------\n configureLogging = (mi: boolean): Promise<unknown> => {\n // return this.repository.getModelInfoFinalFilePath(mi)\n return this.fetchGetText(`/manager/terminal?mode=${mi}`)\n }\n\n // utils ------------------------------------------------------------------------------\n getModelInfoFinalFilePath = (mi: ComfyManagerModelInfo): string => {\n return comfyts.registry.getModelInfoFinalFilePath(mi)\n }\n\n waitForHostToBeBackOnline(maxAttempt: 10): Promise<true> {\n return new Promise<true>((yes, no) => {\n let attempt = 0\n let abortCtrl: AbortController\n const interval = setInterval(async () => {\n attempt++\n if (attempt > maxAttempt) {\n console.log(` - failure`)\n clearInterval(interval)\n no()\n }\n if (abortCtrl) abortCtrl.abort()\n abortCtrl = new AbortController()\n try {\n console.log(` - trying...`)\n await this.host.fetch('/', { signal: abortCtrl.signal }, { apiPrefix: false })\n clearInterval(interval)\n yes(true)\n } catch {\n /* empty */\n }\n }, 1000)\n })\n }\n\n // actions ---------------------------------------------------------------------------\n rebootComfyUIAndUpdateHostPluginsAndModelsAfter10Seconds(): Promise<void> {\n // 🔴 bad code\n setTimeout(() => void this.fetchPluginsAndModels(), 10_000)\n return this.restartComfyUI()\n }\n\n /**\n * reboot the ComfyUI process (ComfyUI-Manager).\n *\n * The server dies mid-request, so a DROPPED CONNECTION is the success shape and the only\n * one most callers ever see. A 404 is not: the route is POST from Manager V3 on (verified\n * against V3.41), and a GET there answers 404 while the process keeps running — a caller\n * that treats every failure as \"expected mid-reboot disconnect\" then reports a reboot that\n * never happened. Both verbs are tried so an old and a new Manager both work, and anything\n * that is neither a disconnect nor a 404 throws with what the host actually said.\n */\n restartComfyUI = async (): Promise<void> => {\n const refusals: string[] = []\n for (const method of ['POST', 'GET'] as const) {\n let response: Response\n try {\n response = await this.host.fetch('/manager/reboot', { method })\n } catch {\n return // connection gone: the process is going down, which is what we asked for\n }\n if (response.ok) return\n refusals.push(`${method} → ${response.status}`)\n // only a missing route is worth retrying with the other verb\n if (response.status !== 404) break\n }\n throw new Error(\n `🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(', ')}) — ` +\n `ComfyUI-Manager is not installed there, or its reboot route moved again`,\n )\n }\n\n modelList: Maybe<ComfyManagerAPIModelList> = null\n\n fetchModels = (): Promise<ComfyManagerAPIModelList> => {\n return this.fetchGetJSON('/externalmodel/getlist?mode=cache', ComfyManagerAPIModelList_ark)\n }\n\n fetchLogs = (): Promise<any> => {\n return this.fetchGetJSON<unknown>('/internal/logs')\n }\n\n isModelInstalled = (name: KnownModel_Name): boolean => {\n return this.modelList?.models.some((x) => x.name === name && x.installed === 'True') ?? false\n }\n\n modelsBeeingInstalled = new Set<KnownModel_Name>()\n\n installModel = async (model: ComfyManagerModelInfo): Promise<boolean> => {\n try {\n this.modelsBeeingInstalled.add(model.name)\n await this.fetchPost('/model/install', model)\n this.modelsBeeingInstalled.delete(model.name)\n toastSuccess('Model installed')\n return true\n } catch (exception) {\n console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)\n toastError('Model Installation Failed')\n this.modelsBeeingInstalled.delete(model.name)\n return false\n }\n }\n\n getModelStatus = (modelName: KnownModel_Name): PluginInstallStatus => {\n if (this.modelList == null) return 'unknown'\n const entry = this.modelList?.models.find((x) => x.name === modelName)\n const status = ((): PluginInstallStatus => {\n if (!entry) return 'unknown'\n if (entry?.installed === 'False') return 'not-installed'\n if (entry?.installed === 'True') return 'installed'\n if (entry?.installed === 'Update') return 'update-available'\n return 'error'\n })()\n return status\n }\n\n // PLUGINS (A.K.A. Custom nodes) ----------------------------------------------------------------------------\n /**\n * you need to call `fetchPluginList()` to populate this field\n */\n pluginList: Maybe<ComfyManagerAPIPluginList> = null // hasModel = async (model: ModelInfo) => {\n\n get titlesOfAllInstalledPlugins(): KnownComfyPluginTitle[] {\n return (\n this.pluginList?.custom_nodes //\n .filter((x) => x.installed === 'True')\n .map((x) => x.title) ?? []\n )\n }\n\n isPluginInstalled = (title: KnownComfyPluginTitle): boolean => {\n if (!this.pluginList || !this.pluginList.custom_nodes) return false\n return this.pluginList.custom_nodes.some((x) => x.title === title && x.installed === 'True') ?? false\n }\n\n getPluginStatus = (title: KnownComfyPluginTitle): PluginInstallStatus => {\n if (this.pluginList == null) return 'unknown'\n const entry = this.pluginList?.custom_nodes.find((x) => x.title === title)\n const status = ((): PluginInstallStatus => {\n if (!entry) return 'unknown'\n if (entry?.installed === 'False') return 'not-installed'\n if (entry?.installed === 'True') return 'installed'\n if (entry?.installed === 'Update') return 'update-available'\n return 'error'\n })()\n return status\n }\n\n // --------------------------------------------------------------\n // https://github.com/ltdrdata/ComfyUI-Manager/blob/4649d216b1842aa48b95d3f064c679a1b698e506/js/custom-nodes-downloader.js#L14C25-L14C88\n fetchPlugins = async (\n /** @default: 'cache' */\n mode: ComfyManagerAPIFetchPolicy = 'cache',\n /** @default: true */\n skipUpdate: boolean = true,\n ): Promise<ComfyManagerAPIPluginList> => {\n try {\n const skip_update = skipUpdate ? '&skip_update=true' : ''\n return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark)\n } catch (exception) {\n console.error(`node list retrieval failed: ${exception}`)\n toastError('node list retrieveal failed')\n throw exception\n }\n }\n\n installPlugin = async (model: ComfyManagerPluginInfo): Promise<boolean> => {\n try {\n await this.fetchPost('/customnode/install', model)\n console.log('✅ Custom Node installed')\n toastSuccess('Custom Node installed')\n return true\n } catch (exception) {\n console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)\n toastError('Custom Node Installation Failed')\n return false\n }\n }\n\n // --------------------------------------------------------------\n private fetchPost = async <IN, OUT = unknown>(endpoint: string, body: IN, validator?: Type<OUT>): Promise<OUT> => {\n const response = await this.host.fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`)\n const status = await response.json()\n if (validator) return softValidate(validator, status)\n // wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json\n return status as OUT\n }\n\n private fetchGetJSON = async <OUT = unknown>(endpoint: string, validator?: Type<OUT>): Promise<OUT> => {\n const response = await this.host.fetch(endpoint)\n if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`)\n const jsonResult = await response.json()\n if (validator) return softValidate(validator, jsonResult)\n // wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json\n return jsonResult as OUT\n }\n\n private fetchGetText = async (endopint: string): Promise<string> => {\n const response = await this.host.fetch(endopint)\n const status = await response.text()\n return status\n }\n}\n","import { type } from 'arktype'\nimport type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'\nimport type { MediaImage } from 'src/runner/MediaImage.ts'\nimport type { Maybe } from 'src/types/index.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\n\nexport type ComfyUploadImageResult = {\n name: ComfyImageName\n subfolder: string\n type: string\n}\n\nexport const ComfyUploadImageResult_ark = type({\n name: type.string.as<ComfyImageName>(),\n subfolder: 'string',\n type: 'string',\n})\n\n/** all those functions are kinda legacy */\nexport class ComfyUploader {\n constructor(public host: ComfyHost) {}\n\n /** upload a blob */\n uploadImage = async (\n //\n img: MediaImage,\n p: {\n type?: Maybe<'input' | 'temp' | 'output'>\n override?: Maybe<boolean>\n subfolder?: string\n },\n ): Promise<ComfyImageName> => {\n const uniqFileName = img.enumName as ComfyImageName\n // console.warn(`[🌁] UPLOAD: ${img.relPath} required as \"${uniqFileName}\"...`)\n\n const expectedFinalName = p.subfolder //\n ? `${p.subfolder}/${uniqFileName}`\n : uniqFileName\n // 2. if image already exists, return it\n if (this.host.schema.hasImage(expectedFinalName)) {\n console.log(`[🌁] UPLOAD: 🩶 \"${img.absPath}\" already exists on current ComfyUI instance`)\n return expectedFinalName as ComfyImageName\n }\n\n // 3. upload\n const form = new FormData()\n form.set('image', img.getAsBlob(), uniqFileName)\n if (p.type) form.set('type', p.type)\n if (p.override ?? true) form.set('override', 'true')\n // const subfolder = p.subfolder ?? 'comfyts-upload'\n if (p.subfolder) form.set('subfolder', p.subfolder)\n const resp = await this.host.fetch('/upload/image', { method: 'POST', body: form })\n const result: ComfyUploadImageResult = softValidate(ComfyUploadImageResult_ark, await resp.json())\n\n // 4. check upload is successfull\n console.log('[🌁] UPLOAD: ✅ got', result)\n if (result.name == null) throw new Error('upload failed')\n\n const finalName = result.subfolder //\n ? (`${result.subfolder}/${result.name}` as ComfyImageName)\n : result.name\n\n if (finalName !== expectedFinalName) {\n console.warn(`[🌁] UPLOAD: ⚠️ expected \"${expectedFinalName}\" but got \"${finalName}\"`)\n } else {\n console.log(`[🌁] UPLOAD: ✅ finalName is \"${finalName}\"`)\n }\n\n // 5. patch the local ComfyUI schema locally\n this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName)\n\n // 6. return the image\n return finalName\n }\n\n /** upload an image present on disk to ComfyUI */\n // ⏸️ upload_FileAtAbsolutePath = async (filePath: AbsolutePath): Promise<ComfyUploadImageResult> => {\n // ⏸️ const mime = asSTRING_orCrash(lookup(filePath))\n // ⏸️ const file = new Blob([readFileSync(filePath)], { type: mime })\n // ⏸️ return await this.upload_Blob(file)\n // ⏸️ }\n\n // ⏸️ /** upload an image from dataURL */\n // ⏸️ upload_dataURL = async (dataURL: string): Promise<ComfyUploadImageResult> => {\n // ⏸️ const mime = dataURL.split(';')[0].split(':')[1]\n // ⏸️ console.log('[⬆️] upload_dataURL', mime)\n // ⏸️ const file = new Blob([Buffer.from(dataURL.split(',')[1], 'base64')], { type: mime })\n // ⏸️ return await this.upload_Blob(file)\n // ⏸️ }\n\n // ⏸️ /** upload an image present on disk to ComfyUI */\n // ⏸️ upload_NativeFile = async (file: File): Promise<ComfyUploadImageResult> => {\n // ⏸️ const blob = new Blob([await file.arrayBuffer()], { type: file.type })\n // ⏸️ return await this.upload_Blob(blob)\n // ⏸️ }\n\n // ⏸️ /** upload an image that can be downloaded form a given URL to ComfyUI */\n // ⏸️ upload_ImageAtURL = async (url: string): Promise<ComfyUploadImageResult> => {\n // ⏸️ const blob: Blob = await this.st.getUrlAsBlob(url)\n // ⏸️ return this.upload_Blob(blob)\n // ⏸️ }\n\n // ⏸️ /** upload a deck asset to ComfyUI */\n // ⏸️ upload_Asset = async (assetName: RelativePath): Promise<ComfyUploadImageResult> => {\n // ⏸️ const absPath = asAbsolutePath(path.join(this.st.rootPath, assetName))\n // ⏸️ return this.st.uploader.upload_FileAtAbsolutePath(absPath)\n // ⏸️ }\n}\n","/** pure url layer for ComfyHost: parse once, render everywhere. No comfyts global. */\n\nexport type ParsedHostBase = {\n scheme: 'http' | 'https'\n host: string\n /** always concrete (defaults 80/443 from the scheme when the url omits it) */\n port: number\n /** '' or '/segment…' with no trailing slash */\n basePath: string\n}\n\n/** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */\nexport function parseHostBase(p: {\n id: string\n url?: string\n host?: string\n port?: number\n https?: boolean\n}): ParsedHostBase {\n const hasLegacy = p.host != null || p.port != null || p.https != null\n if (p.url != null && hasLegacy)\n throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`)\n if (p.url == null) {\n if (p.host == null || p.port == null)\n throw new Error(`host '${p.id}': needs either url, or host AND port (got host=${p.host}, port=${p.port})`)\n return { scheme: p.https ? 'https' : 'http', host: p.host, port: p.port, basePath: '' }\n }\n\n let parsed: URL\n try {\n parsed = new URL(p.url)\n } catch {\n throw new Error(`host '${p.id}': unparseable url '${p.url}'`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')\n throw new Error(`host '${p.id}': url scheme must be http or https, got '${parsed.protocol}' in '${p.url}'`)\n if (parsed.search !== '' || parsed.hash !== '')\n throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`)\n const scheme = parsed.protocol === 'https:' ? 'https' : 'http'\n const port = parsed.port !== '' ? Number(parsed.port) : scheme === 'https' ? 443 : 80\n const basePath = parsed.pathname.replace(/\\/+$/, '')\n return { scheme, host: parsed.hostname, port, basePath }\n}\n\n/** http(s) base, port omitted when it is the scheme default */\nexport function renderHttpBase(p: ParsedHostBase): string {\n return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`\n}\n\n/** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless\n * transports (browser), where the ws client remaps X-API-Key to ?token= */\nexport function renderWsUrl(p: ParsedHostBase): string {\n const scheme = p.scheme === 'https' ? 'wss' : 'ws'\n return `${scheme}://${p.host}${renderPort(p)}${p.basePath}/ws`\n}\n\nfunction renderPort(p: ParsedHostBase): string {\n const schemeDefault = p.scheme === 'https' ? 443 : 80\n return p.port === schemeDefault ? '' : `:${p.port}`\n}\n","// transport-agnostic since 2026-07-31 (architecture item 13): node uses the\n// `ws` package (custom upgrade headers work), browsers the native WebSocket.\n// The `ws` import specifier is a VARIABLE so browser bundlers never chase it.\nimport type { Maybe } from 'src/types/index.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\nimport { logInfo } from 'src/utils/log.ts'\n\ntype Message = string | Uint8Array\n\n/** structural face of both transports (ws package AND browser WebSocket) */\nexport type WsLike = {\n binaryType: string\n onmessage: ((event: WsMessageEvent) => void) | null\n onopen: ((event: unknown) => void) | null\n onclose: ((event: WsCloseEvent) => void) | null\n onerror: ((event: unknown) => void) | null\n send(data: Message): void\n close(): void\n}\n\n/** what both transports deliver with binaryType 'arraybuffer': string or ArrayBuffer in `data` */\nexport type WsMessageEvent = { data: unknown }\nexport type WsCloseEvent = { code: number; reason: string }\n\ntype WsCtor = new (url: string, opts?: { headers?: Record<string, string> }) => WsLike\n\ntype WsTransport = { ctor: WsCtor; supportsHeaders: boolean }\n\nlet transportPromise: Promise<WsTransport> | null = null\n\n/** node: the ws package (headers on the upgrade). browser: native WebSocket. */\nfunction resolveWsTransport(): Promise<WsTransport> {\n transportPromise ??= (async (): Promise<WsTransport> => {\n const specifier = 'ws'\n try {\n // cast: the ws package ctor fits WsCtor structurally; a variable\n // specifier types the import as any, so the shape is stated here\n const mod = (await import(specifier)) as { default: WsCtor }\n return { ctor: mod.default, supportsHeaders: true }\n } catch {\n const native = (globalThis as { WebSocket?: WsCtor }).WebSocket\n if (native != null) return { ctor: native, supportsHeaders: false }\n throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`)\n }\n })()\n return transportPromise\n}\n\ntype WsDebugMessage = {\n type: 'info' | 'error'\n timestamp: number\n message: string\n}\n\nexport class ResilientWebSocketClient {\n private url: string\n private currentWS?: Maybe<WsLike>\n private messageBuffer: Message[] = []\n\n isOpen: boolean = false\n debugMessages: WsDebugMessage[] = []\n\n private addInfo(msg: string): void {\n this.debugMessages.push({ type: 'info', timestamp: Date.now(), message: msg })\n logInfo(`[🧦] WS: ${msg}`)\n }\n\n private addError(err: string): void {\n this.debugMessages.push({ type: 'error', timestamp: Date.now(), message: err })\n console.error('[🧦] WS:', err)\n }\n\n constructor(\n public options: {\n url: () => string\n /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect.\n * On a headerless transport (browser) X-API-Key rides `?token=` instead\n * (the probed Comfy Cloud contract); other headers throw loud. */\n headers?: () => Record<string, string>\n onMessage: (event: WsMessageEvent) => void\n onConnectOrReconnect: () => void\n onClose: () => void\n /** transport unrecoverable (no ws package AND no global WebSocket, or ctor threw):\n * reported here ONCE, the client goes permanently closed — never a retry storm */\n onTransportDead?: (error: unknown) => void\n /**\n * the socket closed WITHOUT ever opening: nothing is listening there.\n * That is a definitive answer, not a blip, so it is reported instead of\n * retried and the caller decides. The 2s retry loop exists to heal an\n * ESTABLISHED session; spending it on a refused connect only makes every\n * waiter sit for the full connect deadline. No callback = retry as before.\n */\n onFirstConnectFailed?: (error: unknown) => void\n },\n ) {\n this.url = options.url()\n void this.connect()\n }\n\n /** an established session heals by retrying; a first connect that never opened does not */\n private hasEverOpened: boolean = false\n\n private reconnectTimeout?: Maybe<ReturnType<typeof setTimeout>>\n private permanentlyClosed: boolean = false\n\n /** close and stop reconnecting (lets a script exit cleanly) */\n disconnectPermanently(): void {\n this.permanentlyClosed = true\n if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout)\n this.currentWS?.close()\n this.currentWS = null\n this.isOpen = false\n }\n\n /** headerless transports carry the api key as ?token= — everything else is refused loud */\n private headerlessUrl(headers: Record<string, string>): string {\n const rest = { ...headers }\n const apiKey = rest['X-API-Key']\n delete rest['X-API-Key']\n const extra = Object.keys(rest)\n if (extra.length > 0)\n throw new Error(\n `custom ws headers (${extra.join(', ')}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`,\n )\n if (apiKey == null) return this.url\n return this.url + (this.url.includes('?') ? '&' : '?') + 'token=' + encodeURIComponent(apiKey)\n }\n\n private async connect(): Promise<void> {\n this.isOpen = false\n const prevWS = this.currentWS\n\n // cleanup a possible re-connection timeout for an other url\n if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout)\n\n this.currentWS = null\n if (prevWS) {\n this.addInfo('Previous WebSocket discarded')\n prevWS.close()\n }\n\n let ws: WsLike\n try {\n const transport = await resolveWsTransport()\n if (this.permanentlyClosed) return // closed while the transport resolved\n const headers = this.options.headers?.() ?? {}\n ws = transport.supportsHeaders\n ? new transport.ctor(this.url, { headers })\n : new transport.ctor(this.headerlessUrl(headers))\n } catch (e) {\n // connect() runs void'd (ctor + reconnect timer): a rethrow here would be\n // an unhandled rejection, so the failure reports through onTransportDead\n this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`)\n this.permanentlyClosed = true\n this.options.onTransportDead?.(e)\n return\n }\n ws.binaryType = 'arraybuffer'\n\n this.currentWS = ws\n\n ws.onmessage = (event: WsMessageEvent): void => {\n this.options.onMessage(event)\n }\n\n ws.onopen = (): void => {\n if (ws !== this.currentWS) return\n this.addInfo('✅ WebSocket connected to ' + this.url)\n this.hasEverOpened = true\n this.isOpen = true\n this.options.onConnectOrReconnect()\n this.flushMessageBuffer()\n }\n\n ws.onclose = (event: WsCloseEvent): void => {\n if (ws !== this.currentWS) return\n this.isOpen = false\n this.options.onClose()\n if (this.permanentlyClosed) return\n this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`)\n // never opened = nothing is listening: report, do not retry (see the option)\n if (!this.hasEverOpened && this.options.onFirstConnectFailed != null) {\n this.permanentlyClosed = true\n this.options.onFirstConnectFailed(\n new Error(`connection refused (code=${event.code}${event.reason === '' ? '' : `, ${event.reason}`})`),\n )\n return\n }\n this.addInfo('⏱️ reconnecting in 2 seconds...')\n this.reconnectTimeout = setTimeout(() => void this.connect(), 2000)\n }\n\n ws.onerror = (event: unknown): void => {\n if (ws !== this.currentWS) return\n this.addError(`WebSocket ERROR` + JSON.stringify(event))\n console.error({ event })\n }\n }\n\n public send(message: Message): void {\n if (this.isOpen) {\n this.currentWS?.send(message)\n } else {\n this.messageBuffer.push(message)\n }\n }\n\n private flushMessageBuffer(): void {\n while (this.messageBuffer.length > 0) {\n const message = bang(this.messageBuffer.shift())\n this.currentWS?.send(message)\n }\n }\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\n/** when the file landed on the host (epoch seconds): the lora manager's own \"date added\" sort reads it */\nexport function lmModified(item: LmLoraItem): number | null {\n const raw = item['modified']\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : null\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/** asks the extension to (re)fetch civitai metadata for ONE lora file, trigger words included.\n * The reply says why when civitai has nothing for it (a private or deleted model) */\nexport async function fetchLoraCivitai(\n host: ComfyHost,\n filePath: string,\n): Promise<{ ok: true } | { ok: false; reason: string }> {\n try {\n const res = await host.fetch('/lm/loras/fetch-civitai', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ file_path: filePath }),\n })\n const raw: unknown = await res.json().catch(() => null)\n const error = isRecord(raw) && typeof raw['error'] === 'string' ? raw['error'] : null\n if (res.ok && isRecord(raw) && raw['success'] !== false) return { ok: true }\n return { ok: false, reason: error ?? `the lora manager answered ${res.status}` }\n } catch (e) {\n return { ok: false, reason: extractErrorMessage(e) }\n }\n}\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('&nbsp;', ' ')\n .replaceAll('&amp;', '&')\n .replaceAll('&lt;', '<')\n .replaceAll('&gt;', '>')\n .replaceAll('&quot;', '\"')\n .replaceAll('&#39;', \"'\")\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 lmModified,\n lmPreviewUrl,\n lmSha256,\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/** what the mirror knows about a lora's trigger words. The extension drops an EMPTY\n * `trainedWords` when it slims the civitai block (model_scanner.py `if trained_words:`), so a\n * block linked to civitai (an `id`) with no words means fetched and empty, while no block at\n * all means civitai was never asked. null = the lora is not in the mirror */\nexport type LoraTriggers =\n | { state: 'words'; words: string[] }\n | { state: 'none' }\n | { state: 'unfetched' }\n /** civitai was asked and has no version for this file (a private or local lora) */\n | { state: 'not-on-civitai' }\n\nexport function loraTriggersOf(item: LmLoraItem, p: { civitaiMiss?: boolean } = {}): LoraTriggers {\n const words = lmTrainedWords(item)\n if (words.length > 0) return { state: 'words', words }\n const civitai = item['civitai']\n if (isRecord(civitai) && (typeof civitai['id'] === 'number' || typeof civitai['modelId'] === 'number'))\n return { state: 'none' }\n return p.civitaiMiss === true ? { state: 'not-on-civitai' } : { state: 'unfetched' }\n}\n\nexport function getLoraTriggers(name: string, hostId?: string): LoraTriggers | null {\n const info = getLoraInfo(name, hostId)\n if (info == null) return null\n const sha = lmSha256(info)\n return loraTriggersOf(info, { civitaiMiss: hostId != null && sha != null && readCivitaiMisses(hostId)[sha] != null })\n}\n\n// the lora manager records nothing when civitai has no version for a file, so the answer is kept\n// here, keyed by content hash (a rename keeps it): without it such a lora would offer a fetch\n// that fails the same way forever\nfunction civitaiMissesPath(hostId: string): AbsolutePath {\n return comfyts.resolveFromHosts(join(hostId, 'lora-civitai-misses.json'))\n}\n\n/** sha256 → when civitai said it has no version for that file */\nexport function readCivitaiMisses(hostId: string): Record<string, string> {\n const text = getComfyStorage().readTextIfExists(civitaiMissesPath(hostId))\n if (text == null) return {}\n try {\n const raw: unknown = JSON.parse(text)\n const out: Record<string, string> = {}\n if (isRecord(raw)) for (const [sha, at] of Object.entries(raw)) if (typeof at === 'string') out[sha] = at\n return out\n } catch (e) {\n logError(`[loraInfoCache] unreadable ${civitaiMissesPath(hostId)}: ${String(e)}`)\n return {}\n }\n}\n\nexport function recordCivitaiMiss(p: { hostId: string; sha256: string; miss: boolean }): void {\n const misses = readCivitaiMisses(p.hostId)\n if (p.miss) misses[p.sha256] = new Date().toISOString()\n else delete misses[p.sha256]\n getComfyStorage().writeText(civitaiMissesPath(p.hostId), JSON.stringify(misses, null, 2))\n}\n\n/** when the lora file landed on the host (epoch seconds), null when unsynced/unknown */\nexport function getLoraAddedAt(name: string, hostId?: string): number | null {\n const info = getLoraInfo(name, hostId)\n return info == null ? null : lmModified(info)\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","import { isRecord } from 'src/utils/isRecord.ts'\n\n/**\n * what changed on a host since a schema was loaded: node types, and the model files each loader\n * lists. ComfyUI exposes no boot time, so staleness is decided by CONTENT: a restart that changed\n * nothing stays quiet, a new lora shows even when nobody knows when the box rebooted.\n * A light check asks only the loaders (`/object_info/<node>`, a few KB); a full one compares every\n * node type (`/object_info`, megabytes).\n */\n\n/** the loader inputs whose combo IS a model folder listing */\nexport const MODEL_LISTS = [\n { noun: 'lora', node: 'LoraLoader', input: 'lora_name' },\n { noun: 'checkpoint', node: 'CheckpointLoaderSimple', input: 'ckpt_name' },\n { noun: 'unet', node: 'UNETLoader', input: 'unet_name' },\n { noun: 'text encoder', node: 'CLIPLoader', input: 'clip_name' },\n { noun: 'vae', node: 'VAELoader', input: 'vae_name' },\n] as const\n\ntype Spec = Record<string, unknown>\ntype Delta = { added: string[]; removed: string[] }\n\nexport type SchemaDrift = {\n /** null on a light check: node types are only compared by a full one */\n nodes: Delta | null\n models: ({ noun: string } & Delta)[]\n}\n\n/** a combo's options in both object_info spellings: `[[...options]]` and `['COMBO', { options }]` */\nexport function comboOptions(spec: Spec, node: string, input: string): string[] | null {\n const def = spec[node]\n if (!isRecord(def) || !isRecord(def['input'])) return null\n const sections = def['input']\n for (const section of ['required', 'optional']) {\n const sec = sections[section]\n if (!isRecord(sec)) continue\n const slot = sec[input]\n if (!Array.isArray(slot)) continue\n const first: unknown = slot[0]\n if (Array.isArray(first)) return first.filter((x): x is string => typeof x === 'string')\n const opts: unknown = slot[1]\n if (first === 'COMBO' && isRecord(opts) && Array.isArray(opts['options']))\n return opts['options'].filter((x): x is string => typeof x === 'string')\n }\n return null\n}\n\nfunction delta(before: readonly string[], after: readonly string[]): Delta {\n const was = new Set(before)\n const now = new Set(after)\n return { added: after.filter((x) => !was.has(x)), removed: before.filter((x) => !now.has(x)) }\n}\n\n/** `live` may be PARTIAL (a light check holds only the loaders): a list is compared only where both\n * sides have the loader, and node types only when `full` */\nexport function diffSchemas(p: { loaded: Spec; live: Spec; full: boolean }): SchemaDrift {\n const models: SchemaDrift['models'] = []\n for (const m of MODEL_LISTS) {\n const before = comboOptions(p.loaded, m.node, m.input)\n const after = comboOptions(p.live, m.node, m.input)\n if (before == null || after == null) continue\n const d = delta(before, after)\n if (d.added.length > 0 || d.removed.length > 0) models.push({ noun: m.noun, ...d })\n }\n return { nodes: p.full ? delta(Object.keys(p.loaded), Object.keys(p.live)) : null, models }\n}\n\nexport function driftChanged(d: SchemaDrift): boolean {\n return d.models.length > 0 || (d.nodes != null && (d.nodes.added.length > 0 || d.nodes.removed.length > 0))\n}\n\n/** `+5 loras, -1 unet, +4 node types`, '' when nothing changed */\nexport function summarizeDrift(d: SchemaDrift): string {\n const parts: string[] = []\n const say = (n: number, sign: string, noun: string): void => {\n if (n > 0) parts.push(`${sign}${n} ${noun}${n === 1 ? '' : 's'}`)\n }\n for (const m of d.models) {\n say(m.added.length, '+', m.noun)\n say(m.removed.length, '-', m.noun)\n }\n if (d.nodes != null) {\n say(d.nodes.added.length, '+', 'node type')\n say(d.nodes.removed.length, '-', 'node type')\n }\n return parts.join(', ')\n}\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\nimport type { ComfyExecution } from 'src/runner/ComfyExecution.ts'\nimport type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'\nimport { parseWorkflowJson } from 'src/litegraph/normalizeWorkflow.ts'\nimport { parseBinaryWsFrame } from 'src/runner/wsBinaryFrame.ts'\nimport { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'\nimport { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport {\n type ComfyStatusData,\n type LogEntry,\n type PromptID,\n type PendingWsItem,\n type PromptRelated_WsMsg,\n type WsMsg,\n WsMsg_ark,\n WsMsgLogsData_ark,\n} from 'src/runner/ComfyWsApi.ts'\nimport { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport { type ComfySchemaJSON, ComfySchemaJSON_ark } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport type { EmbeddingName } from 'src/sdk-generator/comfyui-types.ts'\nimport { type AbsolutePath, type Maybe, type number_Timestamp, type Tagged } from 'src/types/index.ts'\nimport { exhaust } from 'src/utils/exhaust.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\nimport { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'\nimport { readableStringify } from 'src/utils/stringifyReadable.ts'\nimport { logError as toastError, logInfo } from 'src/utils/log.ts'\nimport type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'\nimport { ComfyManager } from 'src/host/ComfyManager.ts'\nimport { ComfyUploader } from 'src/host/ComfyUploader.ts'\nimport { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'\nimport type { Requirements } from 'src/host/Requirements.ts'\nimport { ResilientWebSocketClient, type WsMessageEvent } from 'src/host/ResilientWebsocket.ts'\nimport { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'\nimport type { VarsSpec } from 'src/vars/ComfyVars.ts'\nimport { diffSchemas, MODEL_LISTS, type SchemaDrift } from 'src/host/schemaDrift.ts'\n\nexport type ComfyHostID = Tagged<string, { HostID: true }>\nexport type ComfyHostData = {\n id: string\n\n /** full base url as pasted from a provider (https://cloud.comfy.org,\n * https://xxx.modal.run, http://192.168.1.5:8188/comfy).\n * Exactly ONE of url OR the legacy host+port (+https?) spelling. */\n url?: string\n host?: string\n port?: number\n https?: boolean\n\n /** sent as X-API-Key on every request AND the ws upgrade.\n * NEVER persist the value: read it from an env var (e.g. COMFY_CLOUD_API_KEY) */\n apiKey?: string\n /** default true. false = never write sdk.d.ts to .comfy-ts/hosts/<id>/ —\n * schema updates stay in-memory. The comfy-cloud example sets false: its sdk\n * home is the COMMITTED examples/comfy-cloud/sdk.d.ts (gen:sdk:cloud), and a\n * second copy under .comfy-ts/hosts/ would double-declare the globals. */\n sdkAutoWrite?: boolean\n /** extra headers merged into every request + the ws upgrade (Modal-style auth pairs) */\n headers?: Record<string, string>\n\n // for extra features using path manipulation\n installType?: ComfyInstallType\n\n // misc\n onWsMessageAny?: (e: WsMessageEvent) => void\n onWsMessageArrayBuffer?: (e: ArrayBuffer) => void\n onWsMessageJSON?: (e: WsMsg) => void\n}\n\nexport type ConnectOptions = {\n /** 'auto' (default): reuse cache when fresh · 'refresh': always fetch · 'cache': never fetch */\n schema?: 'auto' | 'refresh' | 'cache'\n /** max cache age for 'auto' (default 24h) */\n maxAgeMs?: number\n /**\n * deadline for the FIRST connect, default 30s. 0 or Infinity waits forever.\n * A refused TCP connection is a ws CLOSE, not a dead transport, so without a\n * deadline `connect()` sat in the 2s reconnect loop and never settled: scripts\n * hung with no error and `comfy-ts serve` wedged the module behind its mutex.\n * Reconnects AFTER a successful connect are untouched and still retry forever.\n */\n timeoutMs?: number\n}\n\n/** the host never came up within ConnectOptions.timeoutMs */\nexport class ComfyHostUnreachableError extends Error {\n /** name, not instanceof: the cli bundle and dist/index.js each define this class */\n override readonly name = 'ComfyHostUnreachableError'\n}\n\nconst DEFAULT_CONNECT_TIMEOUT_MS = 30_000\n\n// biome-ignore format: misc\ntype SchemaUpdateResult = Maybe<{ type: 'success' } | { type: 'error'; error: unknown }>\n\ntype ServerLog = {\n at: string\n content: string\n id: number\n}\n\n/** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):\n * 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive\n * (or plain rate limiting on non-cloud hosts). The key value never appears here. */\nexport class ComfyHostAuthError extends Error {\n constructor(\n public code: 401 | 402 | 429,\n public hostId: string,\n message: string,\n ) {\n super(message)\n this.name = 'ComfyHostAuthError'\n }\n}\n\nexport class ComfyHost<ID extends string = string> {\n // ----- misc paths where we'll store host-related files -----\n cacheFolder: AbsolutePath\n\n comfyJSONPath: AbsolutePath\n embeddingsPath: AbsolutePath\n sdkDTSPath: AbsolutePath\n\n /** the schema instance with all methods to interract with the host schema */\n schema: ComfySchema\n uploader = new ComfyUploader(this)\n\n /** parsed ONCE from data (url-first or legacy host/port/https) — the url ground truth */\n readonly base: ParsedHostBase\n\n constructor(public data: ComfyHostData & { id: ID }) {\n this.base = parseHostBase(this.data)\n\n /** folder where file related to the host config will be cached */\n this.cacheFolder = comfyts.resolveFromHosts(this.data.id)\n\n // create the folder if it does not exist\n const storage = getComfyStorage()\n if (!storage.exists(this.cacheFolder)) {\n console.log('🟢 creating folder', this.cacheFolder)\n storage.mkdirp(this.cacheFolder)\n }\n\n this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`)\n this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`)\n this.sdkDTSPath = comfyts.resolve(this.cacheFolder, `sdk.d.ts`)\n\n /** create a new schema */\n this.schema = new ComfySchema({ embeddings: [], spec: {} })\n }\n\n /** helper to check if your host have whatever it needs to run your workflow */\n matchRequirements = (requirements: Requirements[]): boolean => {\n const repo = comfyts.registry\n for (const req of requirements) {\n if (req.optional) continue\n if (req.type === 'customNodesByNodeKey') {\n const plugins: ComfyManagerPluginInfo[] = repo.plugins_byNodeKey.get(req.nodeName) ?? []\n if (!plugins.find((i) => this.manager.isPluginInstalled(i.title))) {\n // console.log(`[❌ A] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'customNodesByTitle') {\n const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byTitle.get(req.title)\n if (plugin == null) continue\n if (!this.manager.isPluginInstalled(plugin.title)) {\n // console.log(`[❌ B] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'customNodesByURI') {\n const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byFile.get(req.uri)\n if (plugin == null) continue\n if (!this.manager.isPluginInstalled(plugin.title)) {\n // console.log(`[❌ C] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else if (req.type === 'modelInManager') {\n if (!this.manager.isModelInstalled(req.modelName)) {\n // console.log(`[❌ D] ${JSON.stringify(req)} NOT MATCHED`)\n return false\n }\n } else {\n // exhaust(req.type)\n }\n }\n return true\n }\n\n // ----- Rotating srever logs -----\n\n /** server sent by the comfy-manager plugin */\n readonly serverLogs: ServerLog[] = []\n\n /** if true, request ComfyUI to forward logs */\n private wantLog: boolean = true\n\n /** maximum amount of logs to keep in memory */\n readonly maxLogs: number = 200\n\n /** last log id received */\n private logId: number = 0\n\n /** toggle server log forwarding so comfy-ts can */\n toggleServerLogs = (): Promise<unknown> => {\n this.wantLog = !this.wantLog\n return this.manager.configureLogging(this.wantLog)\n }\n\n addLog = (content: string): void => {\n if (this.serverLogs.length > this.maxLogs) this.serverLogs.shift()\n const d = new Date().toISOString().slice(11, 19)\n this.serverLogs.push({ content, id: this.logId++, at: d })\n }\n\n // ----- Misc helpers if you work with a local Comfy -----\n\n /** root install of ComfyUI on the host filesystem */\n get absolutePathToComfyUI(): Maybe<string> {\n return this.data.installType?.absolutePathToComfyRoot\n }\n\n // ----- Misc helpers if you work with a local Comfy -----\n\n get manager(): ComfyManager {\n const value = new ComfyManager(this)\n Object.defineProperty(this, 'manager', { value })\n return value\n }\n\n // INIT -----------------------------------------------------------------------------\n installCustomNodeByFile = async (customNodeFile: KnownComfyPluginURL): Promise<boolean> => {\n const manager = comfyts.registry\n const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byFile.get(customNodeFile)\n if (plugin == null) throw new Error(`Unknown custom node for file: \"${customNodeFile}\"`)\n return this.manager.installPlugin(plugin)\n }\n\n installCustomNodeByTitle = async (customNodeTitle: KnownComfyPluginTitle): Promise<boolean> => {\n const manager = comfyts.registry\n const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byTitle.get(customNodeTitle)\n if (plugin == null) throw new Error(`Unknown custom node for title: \"${customNodeTitle}\"`)\n return this.manager.installPlugin(plugin)\n }\n\n installCustomNode = async (customNode: ComfyManagerPluginInfo): Promise<boolean> => {\n return this.manager.installPlugin(customNode)\n }\n\n // URLS -----------------------------------------------------------------------------\n getServerHostHTTP(): string {\n return renderHttpBase(this.base)\n }\n\n getWSUrl = (): string => {\n return renderWsUrl(this.base)\n }\n\n // HTTP -----------------------------------------------------------------------------\n /** extra headers + X-API-Key, for every http request AND the ws upgrade */\n private authHeaders(): Record<string, string> {\n const out: Record<string, string> = {}\n if (this.data.headers != null) Object.assign(out, this.data.headers)\n if (this.data.apiKey != null) out['X-API-Key'] = this.data.apiKey\n return out\n }\n\n /** remembered /api-prefix verdict for this host; null until first probed */\n private _apiPrefix: boolean | null = null\n\n /**\n * the ONE http path to this host: joins basePath, injects X-API-Key + extra\n * headers, prefers `/api<route>` (required by Comfy Cloud, canonical since\n * custom nodes hijack bare routes) with a bare-route fallback on 404/405 for\n * old local servers (winner memoized; the other spelling is still retried\n * when the memo misses — mixed servers exist, e.g. /internal is bare-only).\n * Auth failures throw a typed ComfyHostAuthError instead of generic noise.\n * `p.apiPrefix: false` opts a route out of the prefix game entirely.\n */\n fetch = async (route: string, init: RequestInit = {}, p: { apiPrefix?: boolean } = {}): Promise<Response> => {\n const base = this.getServerHostHTTP()\n const headers = new Headers(init.headers)\n for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v)\n const send = (prefixed: boolean): Promise<Response> =>\n fetch(`${base}${prefixed ? '/api' : ''}${route}`, { ...init, headers })\n const missed = (res: Response): boolean => res.status === 404 || res.status === 405\n\n let res: Response\n if (p.apiPrefix === false) {\n res = await send(false)\n } else if (this._apiPrefix != null) {\n res = await send(this._apiPrefix)\n if (missed(res)) {\n const alt = await send(!this._apiPrefix)\n if (!missed(alt)) res = alt\n }\n } else {\n res = await send(true)\n if (missed(res)) {\n const bare = await send(false)\n if (!missed(bare)) {\n this._apiPrefix = false\n res = bare\n }\n } else {\n this._apiPrefix = true\n }\n }\n this.throwOnAuthError(res, route)\n return res\n }\n\n /**\n * binary download path: Comfy Cloud answers `/api/view` with a 302 to a\n * temporary signed URL. fetch only auto-strips Authorization/cookies on\n * cross-origin redirects — a custom X-API-Key WOULD be forwarded to the\n * storage host — so we follow the Location manually with a CLEAN fetch.\n */\n fetchFile = async (route: string): Promise<Response> => {\n const res = await this.fetch(route, { redirect: 'manual' })\n if (res.status >= 300 && res.status < 400) {\n const location = res.headers.get('location')\n if (location == null)\n throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`)\n void res.body?.cancel()\n return fetch(new URL(location, this.getServerHostHTTP()))\n }\n return res\n }\n\n private throwOnAuthError(res: Response, route: string): void {\n if (res.status === 401)\n throw new ComfyHostAuthError(\n 401,\n this.data.id,\n this.data.apiKey != null\n ? `host '${this.data.id}': 401 on ${route} — API key invalid or expired`\n : `host '${this.data.id}': 401 on ${route} — host requires authentication, no apiKey configured`,\n )\n if (res.status === 402)\n throw new ComfyHostAuthError(\n 402,\n this.data.id,\n `host '${this.data.id}': 402 on ${route} — insufficient credits`,\n )\n if (res.status === 429)\n throw new ComfyHostAuthError(\n 429,\n this.data.id,\n `host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`,\n )\n }\n\n // LOGS -----------------------------------------------------------------------------\n schemaRetrievalLogs: string[] = []\n\n resetLog = (): void => {\n this.schemaRetrievalLogs.splice(0, this.schemaRetrievalLogs.length)\n }\n\n // STARTING -----------------------------------------------------------------------------\n get isConnected(): boolean {\n return this.ws?.isOpen ?? false\n }\n\n workflow = (p: { id?: string } = {}): ComfyWorkflow<ID> => {\n return new ComfyWorkflow(this, {\n metadata: {},\n id: p.id ? asComfyWorkflowID(p.id) : undefined,\n })\n }\n\n /**\n * define a re-runnable workflow: `build` re-executes with the current var\n * values on every run(). The standard contract for tweak & re-run drivers\n * (scripts, the TUI).\n */\n defineWorkflow = <V extends VarsSpec>(spec: DefineWorkflowSpec<ID, V>): DefinedWorkflow<ID, V> => {\n return new DefinedWorkflow(this, spec)\n }\n\n /**\n * import a workflow.json (litegraph format) as a live, editable workflow.\n * Accepts unknown: the JSON is ark-validated + normalized (parseWorkflowJson)\n * before conversion — invalid documents throw WorkflowNormalizeError.\n */\n importWorkflowJson = (json: unknown, p: { id?: string } = {}): ComfyWorkflow<ID> => {\n const canonical = parseWorkflowJson(json)\n const apiJson = convertLiteGraphToPrompt(this.schema, canonical)\n return this.importApiJson(apiJson, p)\n }\n\n /** import an api.json (ComfyUI prompt format) as a live, editable workflow */\n importApiJson = (json: ComfyApiJson, p: { id?: string } = {}): ComfyWorkflow<ID> => {\n const wf = new ComfyWorkflow(this, {\n apiJson: json,\n metadata: {},\n id: p.id ? asComfyWorkflowID(p.id) : undefined,\n })\n wf.onUpdate(null, wf.data) // hydrate ComfyNode instances from the json\n return wf\n }\n\n private _ready: Promise<void> | null = null\n private _readyResolve: (() => void) | null = null\n private _readyReject: ((e: unknown) => void) | null = null\n private _schemaStrategy: NonNullable<ConnectOptions['schema']> = 'auto'\n private _schemaMaxAgeMs: number = 24 * 3600_000\n\n /**\n * open the websocket; resolves once connected AND the schema is loaded.\n * Schema strategy:\n * - 'auto' (default): reuse .comfy-ts/ cache when younger than maxAgeMs — fast starts\n * - 'refresh': always fetch object_info + regen the sdk\n * - 'cache': never fetch (throws when no cache exists)\n */\n connect = (p: ConnectOptions = {}): Promise<void> => {\n if (this._ready == null) {\n this._schemaStrategy = p.schema ?? 'auto'\n this._schemaMaxAgeMs = p.maxAgeMs ?? 24 * 3600_000\n this._ready = new Promise<void>((res, rej) => {\n this._readyResolve = res\n this._readyReject = rej\n })\n const timeoutMs = p.timeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS\n if (timeoutMs > 0 && Number.isFinite(timeoutMs)) {\n this._connectTimer = setTimeout(() => {\n this.markFailed(\n new ComfyHostUnreachableError(\n `host '${this.data.id}' did not come up within ${timeoutMs}ms at ${this.getWSUrl()} — is ComfyUI running there ?`,\n ),\n )\n }, timeoutMs)\n this._connectTimer.unref?.()\n }\n this.initWebsocket()\n }\n return this._ready\n }\n\n private _connectTimer: Maybe<ReturnType<typeof setTimeout>> = null\n private clearConnectTimer(): void {\n if (this._connectTimer != null) clearTimeout(this._connectTimer)\n this._connectTimer = null\n }\n\n /** close the websocket (e.g. to let a script exit) */\n disconnect = (): void => {\n this.clearConnectTimer()\n this.ws?.disconnectPermanently()\n this.ws = null\n this._ready = null\n this._readyResolve = null\n this._readyReject = null\n }\n\n private markReady(): void {\n this.clearConnectTimer()\n this._readyResolve?.()\n this._readyResolve = null\n this._readyReject = null\n }\n\n private markFailed(error: unknown): void {\n this.clearConnectTimer()\n const reject = this._readyReject\n // no pending connect = this is a RECONNECT failing on an already-live host.\n // Its retry loop is the resilience; never tear that down.\n if (reject == null) return\n this._readyResolve = null\n this._readyReject = null\n // a failed connect stays RETRYABLE: keeping the rejected promise on the\n // instance made every later connect() replay the same stale error, so a host\n // that came back was unreachable for the life of the process\n this._ready = null\n // nobody is waiting anymore: stop the 2s retry loop instead of leaking it\n this.ws?.disconnectPermanently()\n this.ws = null\n reject(error)\n }\n\n private async writeSDKToDisk(): Promise<void> {\n if (this.data.sdkAutoWrite === false) return\n const storage = getComfyStorage()\n const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })\n // skip the 4MB write when nothing changed (fast re-connects)\n if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return\n storage.writeText(this.sdkDTSPath, comfySchemaTs)\n }\n\n private shouldUseSchemaCache(): boolean {\n if (this._schemaStrategy === 'refresh') return false\n const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath)\n if (this._schemaStrategy === 'cache') {\n if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)\n return true\n }\n if (mtimeMs == null) return false\n return Date.now() - mtimeMs < this._schemaMaxAgeMs\n }\n\n // WEBSCKET -----------------------------------------------------------------------------\n /**\n * will be created only after we've loaded cnfig file\n * so we don't attempt to connect to some default server\n * */\n ws: Maybe<ResilientWebSocketClient> = null\n\n /** resolves once the server assigned us a session id (first ws 'status' message) */\n private _sessionResolve: (() => void) | null = null\n private waitForSession(timeoutMs: number = 5000): Promise<void> {\n if (this.comfySessionId !== 'temp') return Promise.resolve()\n return new Promise<void>((res) => {\n this._sessionResolve = res\n // some setups never send a sid — proceed after the timeout, loudly\n setTimeout(() => {\n if (this._sessionResolve != null) {\n console.error(\n `🔴 no session id from ${this.data.id} after ${timeoutMs}ms — executions may not route back`,\n )\n this._sessionResolve = null\n res()\n }\n }, timeoutMs).unref?.()\n })\n }\n\n private initWebsocket(): ResilientWebSocketClient {\n logInfo(`[👢] WEBSOCKET: starting client to ComfyUI host ${this.data.id}`)\n this.ws = new ResilientWebSocketClient({\n onConnectOrReconnect: async (): Promise<void> => {\n logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`)\n if (this.shouldUseSchemaCache()) {\n try {\n await this.loadSchemaFromCache()\n // the server routes execution events by client_id: without the\n // session id from the first 'status' message, prompts we POST\n // would report to nobody. The slow fetch path masked this race.\n await this.waitForSession()\n this.markReady()\n return\n } catch (error) {\n console.error(`🔴 schema cache load failed, falling back to fetch`, extractErrorMessage(error))\n }\n }\n await this.fetchAndUpdateSchema()\n await this.waitForSession()\n this.markReady()\n },\n onMessage: (e: WsMessageEvent): void => this.onMessage(e),\n url: () => this.getWSUrl(),\n // auth rides the upgrade headers; headerless transports (browser)\n // remap X-API-Key to ?token= inside the ws client\n headers: () => this.authHeaders(),\n onTransportDead: (e): void => this.markFailed(e),\n // nothing listening: answer NOW instead of making every caller wait out\n // the deadline. markFailed resets _ready, so the next connect() retries\n // and a host that comes back is reachable again\n onFirstConnectFailed: (e): void =>\n this.markFailed(\n new ComfyHostUnreachableError(\n `host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`,\n ),\n ),\n onClose: (): void => {\n logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)\n },\n })\n return this.ws\n }\n\n _isUpdatingSchema: boolean = false\n get isUpdatingSchema(): boolean {\n return this._isUpdatingSchema\n }\n set isUpdatingSchema(v: boolean) {\n this._isUpdatingSchema = v\n }\n\n schemaUpdateResult: SchemaUpdateResult = null\n\n private _schemaFromCache: Promise<void> | null = null\n\n /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).\n * idempotent like connect(): N co-imported modules parse the ~4MB cache once.\n * A MISSING cache degrades LOUDLY to the base types instead of failing the\n * module import (a fresh consumer project has no cache yet — the bundled\n * examples must still open in the TUI; run() fetches the real schema through\n * connect() anyway). Not memoized in that case, so a later gen/connect retries. */\n loadSchemaFromCache(): Promise<void> {\n if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {\n toastError(\n `no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \\`comfy-ts gen --id ${this.data.id} --host <url>\\` or connect() once to create it`,\n )\n return Promise.resolve()\n }\n this._schemaFromCache ??= (async (): Promise<void> => {\n const object_info_json = comfyts.readJSON_<ComfySchemaJSON>(this.comfyJSONPath)\n const embeddings_json = comfyts.readJSON_<string[]>(this.embeddingsPath, [])\n\n // update schema\n this.schema.update({ spec: object_info_json, embeddings: embeddings_json })\n this.schema.RUN_BASIC_CHECKS()\n\n // the on-disk sdk was generated from this same cache — only write when missing\n if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk()\n })().catch((e: unknown) => {\n this._schemaFromCache = null // a missing cache must stay retryable (e.g. after gen:sdk)\n throw e\n })\n return this._schemaFromCache\n }\n\n /** POST a JSON route through host.fetch (/api preferred, bare fallback) */\n private postJSON_ = async (route: string, body: unknown): Promise<void> => {\n const res = await this.fetch(route, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`)\n }\n\n /** drop every PENDING prompt from the server queue (the running one keeps going) */\n clearQueue = (): Promise<void> => {\n return this.postJSON_('/queue', { clear: true })\n }\n\n /** interrupt the CURRENTLY RUNNING prompt */\n interrupt = (): Promise<void> => {\n return this.postJSON_('/interrupt', {})\n }\n\n // HISTORY SCRUB (architecture.md item 14) -------------------------------------------\n // deletes the server-side history ENTRY (workflow JSON, prompts, output\n // filenames) — never files: the ephemeral tier creates none to begin with\n\n /** delete ONE prompt's server history entry */\n deleteHistory = (promptId: string): Promise<void> => {\n return this.postJSON_('/history', { delete: [promptId] })\n }\n\n /** wipe the server's WHOLE prompt history (every user of that server) */\n clearHistory = (): Promise<void> => {\n return this.postJSON_('/history', { clear: true })\n }\n\n // SERVER LOGS ----------------------------------------------------------------------\n // /internal routes are served bare (no /api prefix, no custom-node hijacks)\n\n /** the server's recent console buffer (entries are write CHUNKS, not lines) */\n fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {\n const res = await this.fetch('/internal/logs/raw', {}, { apiPrefix: false })\n if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`)\n const json: unknown = await res.json()\n // wire tolerance (agent/coding.md cast #4): soft-validate, log, still cast\n const checked = WsMsgLogsData_ark(json)\n if (checked instanceof type.errors) {\n console.log(`[🔴] /!\\\\ /internal/logs/raw payload does not match schema.`)\n printArkResultInConsole(checked)\n }\n return json as { entries: LogEntry[] }\n }\n\n /** (un)subscribe THIS session to ws 'logs' messages — per-sid server state,\n * must be re-sent after every reconnect (see onSession) */\n subscribeLogs = async (p: { enabled: boolean; clientId: string }): Promise<void> => {\n const res = await this.fetch(\n '/internal/logs/subscribe',\n {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ enabled: p.enabled, clientId: p.clientId }),\n },\n { apiPrefix: false },\n )\n if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`)\n }\n\n /** what changed on the host since this schema was loaded (src/host/schemaDrift.ts). `full: false`\n * asks only the loaders the schema has, a few KB, so it can run on a timer. Throws when the host\n * cannot be reached, which is itself the signal a caller watches for a restart */\n checkSchemaDrift = async (p: { full: boolean }): Promise<SchemaDrift> => {\n const loaded: Record<string, unknown> = this.schema.data.spec\n const live: Record<string, unknown> = {}\n if (p.full) Object.assign(live, await this.fetchJSON_<Record<string, unknown>>('/object_info'))\n else\n for (const m of MODEL_LISTS)\n if (loaded[m.node] != null)\n Object.assign(live, await this.fetchJSON_<Record<string, unknown>>(`/object_info/${m.node}`))\n return diffSchemas({ loaded, live, full: p.full })\n }\n\n /** GET a JSON route through host.fetch (/api preferred, bare fallback) */\n private fetchJSON_ = async <T>(route: string): Promise<T> => {\n const base = this.getServerHostHTTP()\n const res = await this.fetch(route)\n if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`)\n const contentType = res.headers.get('content-type') ?? ''\n if (!contentType.includes('json'))\n throw new Error(`GET ${route} on ${base} answered '${contentType || 'no content-type'}' instead of json`)\n return (await res.json()) as T\n }\n\n /** retrieve the comfy spec from the schema*/\n fetchAndUpdateSchema = async (): Promise<void> => {\n try {\n this.isUpdatingSchema = true\n // 1 ------------------------------------\n // download object_info (prefer /api/*: custom nodes hijack bare routes,\n // e.g. lora-manager serves HTML at /embeddings)\n const object_info_json = await this.fetchJSON_<{ [key: string]: ComfySchemaJSON[string] }>('/object_info')\n const object_info_str = readableStringify(object_info_json, 4)\n getComfyStorage().writeText(this.comfyJSONPath, object_info_str)\n // use ark to check if payload match the type, and display errors if not\n const res = ComfySchemaJSON_ark(object_info_json)\n if (res instanceof type.errors) {\n printArkResultInConsole(res)\n }\n\n // 2 ------------------------------------\n // download embeddings\n const embeddings_json = await this.fetchJSON_<EmbeddingName[]>('/embeddings').catch(\n () => [] as EmbeddingName[],\n )\n getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json))\n\n // 3 ------------------------------------\n // update schema\n this.schema.update({ spec: object_info_json, embeddings: embeddings_json })\n this.schema.RUN_BASIC_CHECKS()\n\n // 3 ------------------------------------\n // regen sdk\n await this.writeSDKToDisk()\n this.isUpdatingSchema = false\n this.schemaUpdateResult = { type: 'success' }\n } catch (error) {\n this.isUpdatingSchema = false\n this.schemaUpdateResult = { type: 'error', error: error }\n\n console.error(error)\n console.error('🔴 FAILURE TO GENERATE the typed sdk', extractErrorMessage(error))\n\n const schemaExists = getComfyStorage().exists(this.sdkDTSPath)\n if (!schemaExists) await this.writeSDKToDisk()\n this.markFailed(error)\n } finally {\n this.isUpdatingSchema = false\n }\n }\n\n /** executions we started */\n executions: Map<PromptID, ComfyExecution> = new Map()\n\n /** buffer in case we receive packets out of order */\n _pendingMsgs = new Map<PromptID, PendingWsItem[]>()\n\n /** the active prompt currently running on this host */\n private activePromptID: PromptID | null = null\n\n /** method to either execute or buffer the incoming message */\n routeOrBuffer(prompt_id: PromptID, msg: PromptRelated_WsMsg): void {\n this.activePromptID = prompt_id\n const prompt = this.executions.get(prompt_id)\n\n // case 1. no prompt yet => just store the messages\n if (prompt == null) {\n const msgs = this._pendingMsgs.get(prompt_id)\n if (msgs) msgs.push(msg)\n else this._pendingMsgs.set(prompt_id, [msg])\n return\n }\n // case 2. prompt exists => send the messages\n prompt.onPromptRelatedMessage(msg)\n }\n\n /** the latent image beeing generated, in case you want to display it */\n latentPreview: Maybe<{\n promptID: Maybe<PromptID>\n receivedAt: number_Timestamp\n blob: Blob\n url: string\n }> = null\n\n /** byte-level latent-preview hook (e.g. TUI live preview panel) */\n onLatentPreview: Maybe<(p: { bytes: Uint8Array; mime: string; promptID: Maybe<PromptID> }) => void> = null\n\n /** a node's live display text, as it produces it (`PromptServer.send_progress_text`) */\n onProgressText: Maybe<(p: { nodeId: string; text: string; promptID: Maybe<PromptID> }) => void> = null\n\n /** fires on every ws 'status' message (queue length lives there) */\n onStatus: Maybe<(p: { queueRemaining: number }) => void> = null\n\n /** fires when the server assigns a NEW session id (first connect AND every\n * reconnect — per-sid server state like log subscriptions must be redone) */\n onSession: Maybe<(sid: string) => void> = null\n\n /** fires on ws 'logs' messages (server console stream, see subscribeLogs) */\n onLogs: Maybe<(p: { entries: LogEntry[] }) => void> = null\n\n /** the session assigned to us by the server */\n comfySessionId: string = 'temp' /** send by ComfyUI server */\n\n /** binary frame types we already complained about (one log per type, no spam) */\n private _unknownBinaryFrameTypes = new Set<number>()\n\n /** handy to keep around */\n status: ComfyStatusData['status'] | null = null\n\n /** last time ANY ws message arrived — proof-of-life for the TUI probe: a\n * busy single-threaded ComfyUI stalls NEW connects while established\n * sockets keep streaming (a half-open socket receives nothing, so this\n * never revives one) */\n lastWsMessageAt: number | null = null\n\n onMessage(e: WsMessageEvent): void {\n this.lastWsMessageAt = Date.now()\n if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)\n if (e.data instanceof ArrayBuffer) {\n const frame = parseBinaryWsFrame(e.data)\n if (frame.kind === 'preview') {\n // OUTPUT, not preview: while a SaveImageWebsocket node executes,\n // each preview-kind frame IS one output image (frames follow their\n // 'executing' message on the same socket — architecture.md item 14)\n const activeExec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null\n if (activeExec?.wsOutputNodeExecuting) {\n activeExec.onWsImageOutput({ bytes: frame.bytes, mime: frame.mime })\n return\n }\n // pre-registration window: ws messages\n // can beat the POST /prompt response, and an ephemeral output frame\n // in that window would be the ONLY copy of the image — buffer it IN\n // ORDER with the json messages; ComfyExecution.onCreate replays the\n // queue and decides output-vs-latent from the state at replay time\n if (this.activePromptID != null) {\n const pending = this._pendingMsgs.get(this.activePromptID)\n if (pending != null) pending.push({ type: 'binary_preview_frame', bytes: frame.bytes, mime: frame.mime })\n }\n // type 1 AND the cloud's type 4 (preview + metadata) feed the same hook.\n // The object url REGISTRY holds a strong ref to its blob until it is\n // revoked (node and browsers alike), and a sampler emits one frame per\n // step: revoke the outgoing one or a long session retains every latent\n if (this.latentPreview != null) URL.revokeObjectURL(this.latentPreview.url)\n const imageBlob = new Blob([frame.bytes], { type: frame.mime })\n this.latentPreview = {\n blob: imageBlob,\n url: URL.createObjectURL(imageBlob),\n receivedAt: Date.now() as number_Timestamp,\n promptID: this.activePromptID,\n }\n this.onLatentPreview?.({ bytes: frame.bytes, mime: frame.mime, promptID: this.activePromptID })\n } else if (frame.kind === 'unknown' && !this._unknownBinaryFrameTypes.has(frame.eventType)) {\n // wire tolerance: log once per type, never throw (a throw per sampling\n // step is what the first live cloud run did on type 4)\n this._unknownBinaryFrameTypes.add(frame.eventType)\n console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`)\n }\n if (frame.kind === 'text') {\n // a node's live display text (`PromptServer.send_progress_text`), REPLACEMENT\n // semantics per node: each frame is that node's current text, not a delta. This is\n // the only channel on which text arrives DURING a node, so a streaming generator\n // reaches us here and nowhere else. An early frame lost to the pre-registration\n // window needs no buffering (unlike an output image): the next frame replaces it\n const exec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null\n exec?.onProgressText({ nodeId: frame.nodeId, text: frame.text })\n this.onProgressText?.({ nodeId: frame.nodeId, text: frame.text, promptID: this.activePromptID })\n }\n return\n }\n\n const msg_: unknown = JSON.parse(String(e.data))\n\n // ----- crystools silent fix -----\n if (typeof msg_ === 'object' && msg_ != null && 'type' in msg_) {\n if (msg_.type === 'crystools.monitor') return\n }\n\n // ----- soft-validate against the schema -----\n const res = WsMsg_ark(msg_)\n if (res instanceof type.errors) {\n console.log(`[🔴] /!\\\\ Websocket payload does not match schema.`)\n printArkResultInConsole(res)\n }\n // wire tolerance (agent/coding.md): ComfyUI drifts faster than our schema;\n // failures are logged above, then we still route best-effort\n const msg = msg_ as WsMsg\n\n if (msg.type === 'status') {\n if (msg.data.sid) {\n const sidChanged = msg.data.sid !== this.comfySessionId\n this.comfySessionId = msg.data.sid\n this._sessionResolve?.()\n this._sessionResolve = null\n if (sidChanged) this.onSession?.(msg.data.sid)\n }\n this.status = msg.data.status\n this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 })\n return\n }\n\n // defer accumulation to ScriptStep_prompt\n if (msg.type === 'progress') {\n const activePromptID = this.activePromptID\n if (activePromptID == null) {\n console.log(`❌ received a 'progress' msg, but activePromptID is not set`)\n return\n }\n this.routeOrBuffer(activePromptID, msg)\n return\n }\n if (\n msg.type === 'execution_start' ||\n msg.type === 'execution_cached' ||\n msg.type === 'execution_error' ||\n msg.type === 'execution_success' ||\n msg.type === 'executing' ||\n msg.type === 'executed' ||\n msg.type === 'progress_state'\n ) {\n this.routeOrBuffer(msg.data.prompt_id, msg)\n return\n }\n\n if (msg.type === 'manager-terminal-feedback') {\n this.addLog(msg.data.data)\n return\n }\n\n if (msg.type === 'logs') {\n this.onLogs?.(msg.data)\n return\n }\n exhaust(msg)\n console.log('❌', 'Unknown message:', msg)\n\n toastError('Unknown message type: ' + JSON.stringify(msg.type))\n // throw new Error('Unknown message type: ' + JSON.stringify(msg))\n }\n}\n","// fetch-based (node:https replaced 2026-07-31, architecture item 13): the\n// manager registry chain is in the web graph via ComfyRegistry, so this file\n// must stay portable — fetch follows redirects itself, storage owns the write\nimport { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport type { AbsolutePath } from 'src/types/index.ts'\n\nexport async function downloadFile(\n //\n url: string,\n outputPath: AbsolutePath | string,\n logPrefix = ' - ',\n): Promise<true> {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`)\n const bytes = new Uint8Array(await res.arrayBuffer())\n getComfyStorage().writeBytes(outputPath, bytes)\n console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`)\n return true\n}\n","import { ansi as chalk } from 'src/utils/ansi.ts'\nimport { downloadFile } from 'src/utils/downloadFile.ts'\n\n// canonical repo since the ltdrdata → Comfy-Org move; the old ltdrdata raw\n// urls still redirect here but that is goodwill, not contract (2026-07-30)\nconst MANAGER_RAW_BASE = 'https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main'\n\nconst MANAGER_MIRROR_FILES = [\n 'custom-node-list.json',\n 'model-list.json',\n 'extension-node-map.json',\n 'alter-list.json',\n 'github-stats.json',\n] as const\n\nexport async function DownloadComfyManagerJSONs(): Promise<void> {\n for (const file of MANAGER_MIRROR_FILES) {\n const dest = `src/manager/json/${file}`\n await downloadFile(`${MANAGER_RAW_BASE}/${file}`, dest, `- downloading ${file}...`)\n console.log(` saved at ${chalk.blue(dest)}`)\n }\n}\n","export const githubRegexpV1 = /https:\\/\\/github.com\\/(.+?)\\/(.+?)\\/?/\nexport const githubRegexpV2 = /https:\\/\\/github.com\\/(.+?)\\/([a-zA-Z0-9-_]+)?/\n","import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport const ComfyPluginExtra: ComfyManagerPluginInfo[] = [\n {\n id: 'TEMP_ComfyUI-BRIA_AI-RMBG',\n author: 'ZHO-ZHO-ZHO',\n title: 'TEMP_ComfyUI-BRIA_AI-RMBG',\n reference: 'https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG',\n files: ['https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG'],\n install_type: 'git-clone',\n description: 'better rembg ?',\n },\n]\n","import { ansi as chalk } from 'src/utils/ansi.ts'\n\n/** root shape of a manager mirror file is broken: nothing to salvage, fail loud */\nexport class ManagerParseError extends Error {\n constructor(\n public file: string,\n public detail: string,\n ) {\n super(`🔴 [manager] ${file} root shape invalid: ${detail}`)\n this.name = 'ManagerParseError'\n }\n}\n\nexport class FileParseCounter {\n total = 0\n accepted = 0\n skipped = new Map<string, { count: number; firstError: string }>()\n\n constructor(public file: string) {}\n\n ok(): void {\n this.total++\n this.accepted++\n }\n\n skip(reason: string, firstError: string): void {\n this.total++\n const prev = this.skipped.get(reason)\n if (prev == null) this.skipped.set(reason, { count: 1, firstError })\n else prev.count++\n }\n}\n\n/** per-file row accounting for the manager mirror parse; printed on every registry build so upstream drift stays visible */\nexport class ManagerParseReport {\n counters: FileParseCounter[] = []\n\n file(name: string): FileParseCounter {\n const counter = new FileParseCounter(name)\n this.counters.push(counter)\n return counter\n }\n\n print(): void {\n console.log(chalk.bold(`[📘 registry] parse report:`))\n for (const c of this.counters) {\n const skippedTotal = [...c.skipped.values()].reduce((acc, cur) => acc + cur.count, 0)\n const headline = ` ${c.file}: ${c.total} rows, ${c.accepted} accepted, ${skippedTotal} skipped`\n console.log(skippedTotal === 0 ? headline : chalk.red(headline))\n for (const [reason, info] of c.skipped) {\n console.log(chalk.red(` - ${reason} x${info.count}, first: ${info.firstError}`))\n }\n }\n }\n}\n","import { type } from 'arktype'\n\n/** root shape only: rows are validated ONE BY ONE against ComfyManagerRawPluginInfo_ark */\nexport type ComfyManagerFilePluginListRoot = typeof ComfyManagerFilePluginListRoot_ark.infer\nexport const ComfyManagerFilePluginListRoot_ark = type({ custom_nodes: 'unknown[]' })\n","import { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { ComfyManagerPluginID } from 'src/manager/types/ComfyManagerPluginEnums.ts'\n\n/**\n * loose INPUT schema: what Comfy-Org/ComfyUI-Manager custom-node-list.json\n * actually ships (surveyed 2026-07-30, 5882 rows)\n */\nexport type ComfyManagerRawPluginInfo = typeof ComfyManagerRawPluginInfo_ark.infer\nexport const ComfyManagerRawPluginInfo_ark = type({\n // always present upstream\n author: 'string',\n title: type.string.as<KnownComfyPluginTitle>(),\n reference: 'string',\n files: type.string.as<KnownComfyPluginURL>().array(),\n install_type: 'string', // 'git-clone' | 'copy' | 'unzip' | stray casings\n description: 'string',\n\n // absent on 4471/5882 rows (2026-07-30): recovered at normalization\n 'id?': type.string.as<ComfyManagerPluginID>(),\n\n // sparse optional tail\n 'preemptions?': 'string[]',\n 'pip?': 'string[]',\n 'nodename_pattern?': 'string',\n 'apt_dependency?': 'string[]',\n 'js_path?': 'string',\n 'version?': 'string',\n 'tags?': 'string[]',\n\n // 2025/2026 additions, unconsumed but declared so drift stays visible\n 'reference2?': 'string',\n 'category?': 'string',\n 'name?': 'string',\n 'license?': 'string',\n 'nickname?': 'string',\n 'stars?': 'number',\n 'last_update?': 'string',\n 'badges?': 'string[]',\n 'dependencies?': 'string[]',\n})\n\n/**\n * canonical plugin row: `id` ALWAYS present (normalization recovers it).\n * The optional tail stays optional ON PURPOSE: this object is also the\n * Manager v2 install POST body, where absent and null differ python-side.\n */\nexport type ComfyManagerPluginInfo = {\n id: ComfyManagerPluginID\n author: string\n title: KnownComfyPluginTitle\n reference: string\n files: KnownComfyPluginURL[]\n install_type: string\n description: string\n preemptions?: string[]\n pip?: string[]\n nodename_pattern?: string\n apt_dependency?: string[]\n js_path?: string\n version?: string\n tags?: string[]\n}\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { githubRegexpV1 } from 'src/utils/githubRegexes.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { ComfyPluginExtra } from 'src/manager/json/custom-node-list.extra.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport { ComfyManagerFilePluginListRoot_ark } from 'src/manager/types/ComfyManagerFilePluginList.ts'\nimport {\n type ComfyManagerRawPluginInfo,\n ComfyManagerRawPluginInfo_ark,\n type ComfyManagerPluginInfo,\n} from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport const _getKnownPlugins = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('custom-node-list.json')\n let totalFileSeen = 0\n\n // parse rows: loose raw schema per row, skip+report failures, normalize survivors\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/custom-node-list.json'))\n const root = ComfyManagerFilePluginListRoot_ark(raw)\n if (root instanceof type.errors) throw new ManagerParseError('custom-node-list.json', root.summary)\n\n const canonical: ComfyManagerPluginInfo[] = []\n for (const row of root.custom_nodes) {\n const res = ComfyManagerRawPluginInfo_ark(row)\n if (res instanceof type.errors) {\n counter.skip('schema', res.summary)\n continue\n }\n const plugin = normalizePluginInfo(res)\n if (plugin == null) {\n counter.skip('id-unrecoverable', res.reference)\n continue\n }\n canonical.push(plugin)\n counter.ok()\n }\n\n // hand-maintained extras are compile-checked canonical rows, not upstream data: no counting\n const knownPluginList: ComfyManagerPluginInfo[] = canonical.concat(ComfyPluginExtra)\n\n for (const plugin of knownPluginList) {\n if (DB.opts.check && DB.plugins_byTitle.has(plugin.title))\n console.log(` ❌ plugin.title: \"${plugin.title}\" is duplicated`)\n DB.plugins_byTitle.set(plugin.title, plugin)\n for (const pluginURI of plugin.files) {\n totalFileSeen++\n if (DB.opts.check && DB.plugins_byFile.has(pluginURI))\n console.log(` ❌ plugin.file: \"${pluginURI}\" is duplicated`)\n DB.plugins_byFile.set(pluginURI, plugin)\n }\n }\n\n // CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n let out1 = ''\n // TitleType\n const allPlugins = [...DB.plugins_byTitle.values()]\n const allPluginsSortedByTitles = allPlugins.sort((a, b) =>\n a.title.toLowerCase().localeCompare(b.title.toLowerCase()),\n )\n out1 += '// prettier-ignore\\n'\n out1 += 'export type KnownComfyPluginTitle =\\n'\n for (const plugin of allPluginsSortedByTitles) {\n out1 += ` /** ${plugin.id} - ${plugin.reference} */\\n`\n out1 += ` | ${JSON.stringify(plugin.title)}\\n`\n }\n out1 += '\\n'\n const out1Path = 'src/manager/generated/KnownComfyPluginTitle.ts'\n getComfyStorage().writeText(out1Path, out1 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out1Path)}`)\n\n // FileType\n let out2 = ''\n const allFileNames = [...DB.plugins_byFile.keys()]\n const sortedFileNames = allFileNames.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))\n out2 += '// prettier-ignore\\n'\n out2 += 'export type KnownComfyPluginURL =\\n'\n for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\\n`\n const out2Path = 'src/manager/generated/KnownComfyPluginURL.ts'\n getComfyStorage().writeText(out2Path, out2)\n console.log(` > generated: ${chalk.blue.underline(out2Path)}`)\n }\n\n // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n console.log(` - ${knownPluginList.length} CustomNodes in file`)\n console.log(` - ${DB.plugins_byTitle.size} CustomNodes registered in map`)\n console.log(` - ${totalFileSeen} CustomNodes-File Seen`)\n console.log(` - ${DB.plugins_byFile.size} CustomNodes-File registered in map`)\n }\n}\n\n/**\n * raw → canonical: recover the missing `id` (absent on ~76% of upstream rows)\n * from the title, else the github repo name. null = unrecoverable, caller\n * reports and skips the row.\n */\nfunction normalizePluginInfo(p: ComfyManagerRawPluginInfo): ComfyManagerPluginInfo | null {\n const id = p.id ?? p.title ?? p.reference.match(githubRegexpV1)?.[2]\n if (id == null) return null\n return { ...p, id }\n}\n","import { type } from 'arktype'\n\nexport type ComfyManagerPluginContentMetadata = typeof ComfyManagerPluginContentMetadata_ark.infer\nexport const ComfyManagerPluginContentMetadata_ark = type({\n // absent on 10/5573 upstream rows (2026-07-30), null on others\n 'title_aux?': type.string.or(type.null), // \"Jovimetrix Composition Nodes\",\n\n // optional\n 'author?': 'string', // \"amorano\",\n 'nickname?': 'string', // \"Comfy Deploy\",\n 'description?': 'string', // \"Webcams, GLSL shader, Media Streaming, Tick animation, Image manipulation,\",\n 'nodename_pattern?': 'string', // \" \\\\(jov\\\\)$\",\n 'title?': 'string', // \"Jovimetrix\",\n 'preemptions?': 'string[]', // ❓\n})\n","import { type } from 'arktype'\nimport type { Tagged } from 'src/types/index.ts'\n\nexport type ComfyManagerPluginContentNodeName = Tagged<string, 'ComfyManagerPluginContentNodeName'>\nexport const ComfyManagerPluginContentNodeName_ark = type.string.as<ComfyManagerPluginContentNodeName>()\n\nexport type ComfyManagerPluginID = string\nexport const ComfyManagerPluginID_ark = type('string')\n","import { type } from 'arktype'\nimport { ComfyManagerPluginContentMetadata_ark } from 'src/manager/types/ComfyManagerPluginContentMetadata.ts'\nimport { ComfyManagerPluginContentNodeName_ark } from 'src/manager/types/ComfyManagerPluginEnums.ts'\n\n/** ONE extension-node-map entry value: [nodeNames, meta]; the file root is a Record of these, validated row by row */\nexport type ComfyManagerExtensionNodeMapEntry = typeof ComfyManagerExtensionNodeMapEntry_ark.infer\nexport const ComfyManagerExtensionNodeMapEntry_ark = type([\n ComfyManagerPluginContentNodeName_ark.array(),\n ComfyManagerPluginContentMetadata_ark,\n])\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'\nimport { githubRegexpV2 } from 'src/utils/githubRegexes.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport type { KnownComfyCustomNodeName } from 'src/manager/generated/KnownComfyCustomNodeName.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport { ComfyManagerExtensionNodeMapEntry_ark } from 'src/manager/types/ComfyManagerFilePluginContent.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nexport const _getCustomNodeRegistry = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('extension-node-map.json')\n let totalCustomNodeSeen: number = 0\n\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/extension-node-map.json'))\n const root = type('Record<string, unknown>')(raw)\n if (root instanceof type.errors) throw new ManagerParseError('extension-node-map.json', root.summary)\n\n for (const [url, value] of Object.entries(root)) {\n // row shape: [nodeNames, meta]\n const res = ComfyManagerExtensionNodeMapEntry_ark(value)\n if (res instanceof type.errors) {\n counter.skip('schema', `${url}: ${res.summary}`)\n continue\n }\n // cross-reference: the url must be a file of a known plugin (upstream ships a few orphans)\n const plugin = DB.plugins_byFile.get(url as KnownComfyPluginURL)\n if (plugin == null) {\n counter.skip('unknown-plugin-url', url)\n continue\n }\n counter.ok()\n\n // meta (res[1]) is validated so drift stays visible, but consumed by nothing today\n const comfyNodeNames = res[0]\n totalCustomNodeSeen += comfyNodeNames.length\n const pythonModule = reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin)\n\n // ensure we have a list of nodes for this plugin\n const nodesInPlugin: KnownComfyCustomNodeName[] = DB.customNodes_byPluginName.get(plugin.title) ?? []\n DB.customNodes_byPluginName.set(plugin.title, nodesInPlugin)\n\n for (const nodeNameInComfy of comfyNodeNames) {\n const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy)\n const prevEntry = DB.plugins_byNodeKey.get(nodeKey)\n if (prevEntry == null) DB.plugins_byNodeKey.set(nodeKey, [plugin])\n else prevEntry.push(plugin)\n nodesInPlugin.push(nodeKey as KnownComfyCustomNodeName)\n }\n }\n\n // CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n let out = ''\n const allNodeKeys = [...DB.plugins_byNodeKey.keys()]\n const sortedNodeKeys = allNodeKeys.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))\n out += '// prettier-ignore\\n'\n out += 'export type KnownComfyCustomNodeName =\\n'\n for (const nodeName of sortedNodeKeys) {\n out += ` | ${JSON.stringify(nodeName)}\\n`\n }\n out += '\\n'\n\n const outPath = 'src/manager/generated/KnownComfyCustomNodeName.ts'\n getComfyStorage().writeText(outPath, out + '\\n')\n console.log(` > generated: ${chalk.blue.underline(outPath)}`)\n }\n\n // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n console.log(` - ${totalCustomNodeSeen} CustomNodes names processed`)\n console.log(` - ${DB.plugins_byNodeKey.size} unique node keys registered in map`)\n }\n}\n\nfunction reverseEngineerWhatComfyWillSendAsPythonModuleValueOnceInstalled(plugin: ComfyManagerPluginInfo): string {\n if (plugin.id === 'nodes' && plugin.reference === 'https://github.com/comfyanonymous/ComfyUI') return 'nodes'\n const repoName = plugin.reference.match(githubRegexpV2)?.[2]\n if (repoName) return `custom_nodes.${repoName}`\n return `custom_nodes.${plugin.id}`\n}\n","import type { ComfyManagerFileModelInfo } from 'src/manager/types/ComfyManagerFileModelInfo.ts'\n\nexport const extraModels: ComfyManagerFileModelInfo = {\n models: [\n {\n name: 'TEMP_briaai_RMBG-1.4',\n type: 'controlnet',\n base: 'SDXL',\n save_path: 'custom_nodes/ComfyUI-BRIA_AI-RMBG/RMBG-1.4',\n description: '<3 stuff',\n reference: 'https://huggingface.co/briaai/RMBG-1.4',\n filename: 'model.pth',\n url: 'https://huggingface.co/briaai/RMBG-1.4/resolve/main/model.pth?download=true',\n },\n {\n name: '4x_NMKD-Siax_200k',\n type: 'upscale',\n base: 'upscale',\n save_path: 'default',\n description: '4xRealWebPhoto_v4_dat2',\n reference: 'https://openmodeldb.info/models/4x-RealWebPhoto-v4-dat2',\n filename: '4xRealWebPhoto_v4_dat2.pth',\n url: 'https://huggingface.co/gemasai/4x_NMKD-Siax_200k/resolve/main/4xRealWebPhoto_v4_dat2.pth',\n },\n ],\n}\n","import { type } from 'arktype'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\n\n/** root shape only: rows are validated ONE BY ONE against ComfyManagerModelInfo_ark */\nexport type ComfyManagerFileModelInfoRoot = typeof ComfyManagerFileModelInfoRoot_ark.infer\nexport const ComfyManagerFileModelInfoRoot_ark = type({ models: 'unknown[]' })\n\n/** hand-maintained extras (model-list.extra.ts) still declare the full canonical shape */\nexport type ComfyManagerFileModelInfo = { models: ComfyManagerModelInfo[] }\n","import { type } from 'arktype'\nimport type { KnownModel_Base } from 'src/manager/generated/KnownModel_Base.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport type { KnownModel_SavePath } from 'src/manager/generated/KnownModel_SavePath.ts'\nimport type { KnownModel_Type } from 'src/manager/generated/KnownModel_Type.ts'\n\nexport type ComfyManagerModelInfo = typeof ComfyManagerModelInfo_ark.infer\nexport const ComfyManagerModelInfo_ark = type({\n name: type.string.as<KnownModel_Name>(), // e.g. \"ip-adapter_sd15_light.safetensors\",\n type: type.string.as<KnownModel_Type>(), // e.g. \"IP-Adapter\",\n base: type.string.as<KnownModel_Base>(), // e.g. \"SD1.5\",\n save_path: type.string.as<KnownModel_SavePath>(), // e.g. \"ipadapter\",\n description: 'string', // e.g. \"You can use this model in the [a/ComfyUI IPAdapter plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus) extension.\",\n reference: 'string', // e.g. \"https://huggingface.co/h94/IP-Adapter\",\n filename: 'string', // e.g. \"ip-adapter_sd15_light.safetensors\",\n url: 'string', // e.g. \"https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter_sd15_light.safetensors\"\n 'size?': 'string', // e.g. \"698.4MB\"\n})\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport { ansi as chalk } from 'src/utils/ansi.ts'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { extraModels } from 'src/manager/json/model-list.extra.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport { ComfyManagerFileModelInfoRoot_ark } from 'src/manager/types/ComfyManagerFileModelInfo.ts'\nimport { type ComfyManagerModelInfo, ComfyManagerModelInfo_ark } from 'src/manager/types/ComfyManagerModelInfo.ts'\n\nexport const _getKnownModels = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('model-list.json')\n\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/model-list.json'))\n const root = ComfyManagerFileModelInfoRoot_ark(raw)\n if (root instanceof type.errors) throw new ManagerParseError('model-list.json', root.summary)\n\n const canonical: ComfyManagerModelInfo[] = []\n for (const row of root.models) {\n const res = ComfyManagerModelInfo_ark(row)\n if (res instanceof type.errors) {\n counter.skip('schema', res.summary)\n continue\n }\n canonical.push(res)\n counter.ok()\n }\n\n // hand-maintained extras are compile-checked canonical rows, not upstream data: no counting\n const knownModelList = canonical.concat(extraModels.models)\n\n for (const modelInfo of knownModelList) {\n DB.knownModels.set(modelInfo.name, modelInfo)\n }\n\n // CODEGEN ------------------------------------------------------------\n if (DB.opts.genTypes) {\n // #region type\n let out1 = ''\n const uniqCategories: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.type] != null) acc[cur.type]! += 1\n else acc[cur.type] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out1 += `// prettier-ignore\\n`\n out1 += 'export type KnownModel_Type =\\n'\n for (const [cat, count] of Object.entries(uniqCategories))\n out1 += ` | ${JSON.stringify(cat).padEnd(20)} // x ${count.toString().padStart(3)}\\n`\n out1 += '\\n'\n out1 += 'export const knownModel_Type: KnownModel_Type[] = [\\n'\n for (const [cat, count] of Object.entries(uniqCategories))\n out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\\n`\n out1 += ']\\n'\n const out1Path = 'src/manager/generated/KnownModel_Type.ts'\n getComfyStorage().writeText(out1Path, out1 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out1Path)}`)\n\n // #region savepath\n let out4 = ''\n const uniqSavePath: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.save_path] != null) acc[cur.save_path]! += 1\n else acc[cur.save_path] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out4 += `// prettier-ignore\\n`\n out4 += 'export type KnownModel_SavePath =\\n'\n for (const [cat, count] of Object.entries(uniqSavePath))\n out4 += ` | ${JSON.stringify(cat).padEnd(50)} // x ${count.toString().padStart(3)}\\n`\n out4 += '\\n'\n out4 += 'export const knownModel_SavePath: KnownModel_SavePath[] = [\\n'\n for (const [cat, count] of Object.entries(uniqSavePath))\n out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\\n`\n out4 += ']\\n'\n const out4Path = 'src/manager/generated/KnownModel_SavePath.ts'\n getComfyStorage().writeText(out4Path, out4 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out4Path)}`)\n\n // #region base\n let out2 = ''\n const uniqBases: { [key: string]: number } = knownModelList.reduce(\n (acc, cur) => {\n if (acc[cur.base] != null) acc[cur.base]! += 1\n else acc[cur.base] = 1\n return acc\n },\n {} as { [key: string]: number },\n )\n out2 += `// prettier-ignore\\n`\n out2 += 'export type KnownModel_Base =\\n'\n for (const [cat, count] of Object.entries(uniqBases))\n out2 += ` | ${JSON.stringify(cat).padEnd(20)} // x ${count.toString().padStart(3)}\\n`\n out2 += '\\n'\n out2 += '// prettier-ignore\\n'\n out2 += 'export const knownModel_Base: KnownModel_Base[] = [\\n'\n for (const [cat, count] of Object.entries(uniqBases))\n out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\\n`\n out2 += ']\\n'\n const out2Path = 'src/manager/generated/KnownModel_Base.ts'\n getComfyStorage().writeText(out2Path, out2 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out2Path)}`)\n\n // #region KnownModel_Name\n let out3 = ''\n const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()))\n out3 += `// prettier-ignore\\n`\n out3 += 'export type KnownModel_Name =\\n'\n for (const mi of sortedModels) {\n out3 += ` /** ${mi.description}\\n`\n out3 += ` * ${mi.size} - ${mi.url}\\n`\n out3 += ` * see ${mi.reference}\\n`\n out3 += ` */\\n`\n out3 += ` | ${JSON.stringify(mi.name)}\\n`\n }\n out3 += '\\n'\n const out3Path = 'src/manager/generated/KnownModel_Name.ts'\n getComfyStorage().writeText(out3Path, out3 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out3Path)}`)\n\n // #region KnownModel_FileName\n let out99 = ''\n out99 += `// prettier-ignore\\n`\n out99 += 'export type KnownModel_FileName =\\n'\n for (const mi of sortedModels) {\n out99 += ` /** ${mi.description}\\n`\n out99 += ` * ${mi.size} - ${mi.url}\\n`\n out99 += ` * see ${mi.reference}\\n`\n out99 += ` */\\n`\n out99 += ` | ${JSON.stringify(mi.filename)}\\n`\n }\n out99 += '\\n'\n const out99Path = 'src/manager/generated/KnownModel_FileName.ts'\n getComfyStorage().writeText(out99Path, out99 + '\\n')\n console.log(` > generated: ${chalk.blue.underline(out99Path)}`)\n }\n\n // INDEXING CHECKS ------------------------------------------------------------\n if (DB.opts.check) {\n console.log(`${knownModelList.length} models found`)\n console.log(`${DB.knownModels.size} models registered map`)\n if (knownModelList.length !== DB.knownModels.size)\n console.log(`❌ some models are either duplicated or have overlapping indexing keys`)\n }\n}\n","import { type } from 'arktype'\n\n/** ONE alter-list.json row (a1111 extension → comfy alternative); `tags` is a comma-separated STRING upstream */\nexport type ComfyManagerAlterInfo = typeof ComfyManagerAlterInfo_ark.infer\nexport const ComfyManagerAlterInfo_ark = type({\n id: 'string', // \"https://github.com/comfyanonymous/ComfyUI\"\n tags: 'string', // \"SD1.x,SD2.x,SDXL\"\n description: 'string',\n})\n\n/** root shape only: rows are validated ONE BY ONE */\nexport type ComfyManagerFileAlterListRoot = typeof ComfyManagerFileAlterListRoot_ark.infer\nexport const ComfyManagerFileAlterListRoot_ark = type({ items: 'unknown[]' })\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport {\n type ComfyManagerAlterInfo,\n ComfyManagerAlterInfo_ark,\n ComfyManagerFileAlterListRoot_ark,\n} from 'src/manager/types/ComfyManagerAlterInfo.ts'\n\nexport const _getAlterList = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('alter-list.json')\n\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/alter-list.json'))\n const root = ComfyManagerFileAlterListRoot_ark(raw)\n if (root instanceof type.errors) throw new ManagerParseError('alter-list.json', root.summary)\n\n const canonical: ComfyManagerAlterInfo[] = []\n for (const row of root.items) {\n const res = ComfyManagerAlterInfo_ark(row)\n if (res instanceof type.errors) {\n counter.skip('schema', res.summary)\n continue\n }\n canonical.push(res)\n counter.ok()\n }\n DB.alterations = canonical\n}\n","import { type } from 'arktype'\n\n/** ONE github-stats.json entry, keyed by repo url in the file root (a Record, validated row by row) */\nexport type ComfyManagerGithubStatEntry = typeof ComfyManagerGithubStatEntry_ark.infer\nexport const ComfyManagerGithubStatEntry_ark = type({\n stars: 'number',\n last_update: 'string', // \"2026-07-28 03:14:59\"\n author_account_age_days: 'number',\n})\n","import { getComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type } from 'arktype'\nimport type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { ManagerParseError } from 'src/manager/loaders/parseReport.ts'\nimport { ComfyManagerGithubStatEntry_ark } from 'src/manager/types/ComfyManagerGithubStats.ts'\n\nexport const _getGithubStats = (DB: ComfyRegistry): void => {\n const counter = DB.report.file('github-stats.json')\n\n const raw: unknown = JSON.parse(getComfyStorage().readText('src/manager/json/github-stats.json'))\n const root = type('Record<string, unknown>')(raw)\n if (root instanceof type.errors) throw new ManagerParseError('github-stats.json', root.summary)\n\n for (const [url, value] of Object.entries(root)) {\n const res = ComfyManagerGithubStatEntry_ark(value)\n if (res instanceof type.errors) {\n counter.skip('schema', `${url}: ${res.summary}`)\n continue\n }\n DB.githubStats.set(url, res)\n counter.ok()\n }\n}\n","import { ansi as chalk } from 'src/utils/ansi.ts'\nimport type { NodeNameInComfy, QualifiedNodeKey } from 'src/sdk-generator/comfyui-types.ts'\nimport type { KnownComfyCustomNodeName } from 'src/manager/generated/KnownComfyCustomNodeName.ts'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'\nimport type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'\nimport { DownloadComfyManagerJSONs } from 'src/manager/loaders/step1_downloadComfyManagerJSONs.ts'\nimport { _getKnownPlugins } from 'src/manager/loaders/step2_custom-node-list-loader.ts'\nimport { _getCustomNodeRegistry } from 'src/manager/loaders/step3_extension-node-map-loader.ts'\nimport { _getKnownModels } from 'src/manager/loaders/step4_model-list-loader.ts'\nimport { _getAlterList } from 'src/manager/loaders/step5_alter-list-loader.ts'\nimport { _getGithubStats } from 'src/manager/loaders/step6_github-stats-loader.ts'\nimport { ManagerParseReport } from 'src/manager/loaders/parseReport.ts'\nimport type { ComfyManagerAlterInfo } from 'src/manager/types/ComfyManagerAlterInfo.ts'\nimport type { ComfyManagerGithubStatEntry } from 'src/manager/types/ComfyManagerGithubStats.ts'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\nconst log = (...args: unknown[]) => console.log(`[📘 registry]`, ...args)\n\n// core ComfyUI as a pseudo-plugin: extension-node-map keys the builtin nodes under this url\nconst BUILTIN_URL: KnownComfyPluginURL = 'https://github.com/comfyanonymous/ComfyUI'\nconst BUILTIN_PLUGIN: ComfyManagerPluginInfo = {\n id: 'nodes',\n author: 'comfyanonymous',\n description: 'built-in',\n title: 'built-in',\n files: [BUILTIN_URL],\n reference: 'https://github.com/comfyanonymous/ComfyUI',\n install_type: '',\n}\n\nexport class ComfyRegistry {\n // plugins, indexed\n plugins_byTitle = new Map<KnownComfyPluginTitle, ComfyManagerPluginInfo>()\n plugins_byFile = new Map<KnownComfyPluginURL, ComfyManagerPluginInfo>()\n plugins_byNodeNameInComfy = new Map<NodeNameInComfy, ComfyManagerPluginInfo[]>()\n plugins_byNodeKey = new Map<QualifiedNodeKey, ComfyManagerPluginInfo[]>()\n\n // custom nodes\n customNodes_byPluginName = new Map<KnownComfyPluginTitle, KnownComfyCustomNodeName[]>()\n\n // Models\n knownModels = new Map<KnownModel_Name, ComfyManagerModelInfo>()\n\n // a1111 → comfy alternatives (alter-list.json)\n alterations: ComfyManagerAlterInfo[] = []\n\n // repo url → stars / last_update (github-stats.json)\n githubStats = new Map<string, ComfyManagerGithubStatEntry>()\n\n // per-file row accounting of the last load, printed on every build\n report = new ManagerParseReport()\n\n static async DownloadAndUpdate(download: boolean): Promise<ComfyRegistry> {\n if (download) {\n log(chalk.bold(`1. Downloading comfy-manager JSONs...`))\n await DownloadComfyManagerJSONs()\n } else {\n log(`1. Downloading comfy-manager JSONs... ${chalk.bold('[SKIPPED]')}`)\n }\n // should take care of the code generation\n return new ComfyRegistry({\n check: true,\n genTypes: true,\n })\n }\n\n constructor(\n public opts: {\n check?: boolean\n genTypes?: boolean\n } = {},\n ) {\n // seeded BEFORE codegen so 'built-in' and the core repo url are legitimate union members\n this.plugins_byTitle.set(BUILTIN_PLUGIN.title, BUILTIN_PLUGIN)\n this.plugins_byFile.set(BUILTIN_URL, BUILTIN_PLUGIN)\n\n log(`loading src/manager/json/${chalk.yellow('custom-node-list.json')}...`)\n _getKnownPlugins(this)\n\n log(`loading src/manager/json/${chalk.yellow('extension-node-map.json')}...`)\n _getCustomNodeRegistry(this)\n\n log(`loading src/manager/json/${chalk.yellow('model-list.json')}...`)\n _getKnownModels(this)\n\n log(`loading src/manager/json/${chalk.yellow('alter-list.json')}...`)\n _getAlterList(this)\n\n log(`loading src/manager/json/${chalk.yellow('github-stats.json')}...`)\n _getGithubStats(this)\n\n this.report.print()\n }\n\n getKnownCheckpoints = (): ComfyManagerModelInfo[] => {\n const allKnownModels = [...this.knownModels.values()]\n const allKnownCheckpoints = allKnownModels.filter((i) => i.type === 'checkpoint')\n // console.log(`[🤠] allKnownCheckpoints`, allKnownCheckpoints)\n // for (const mi of knownModels.values()) {\n // console.log(`[🧐] `, mi.type === 'checkpoint' ? '✅' : '❌', mi.name)\n // }\n return allKnownCheckpoints\n }\n\n /**\n * try to replicate the logic of ComfyUIManager to extract the final\n * file path of a downloaded managed model\n */\n getModelInfoFinalFilePath = (mi: ComfyManagerModelInfo): string => {\n /**\n * the wide data-lt once told:\n *\n * | if save_path is 'default'\n * | models/type'/filename\n *\n * | if type is \"checkpoint\"\n * | models/checkpoints/filename\n *\n * | if save_path not starting with custom node\n * | base path is models\n * | e.g. save_path is \"checkpoints/SD1.5\"\n * | models/checkpoints/SD1.5/filename\n * | save_path is \"custom_nodes/AAA/models\"\n * | custom_nodes/AAA/models/filename\n *\n */\n if (mi.save_path === 'default') return `models/${mi.type}/${mi.filename}`\n if (mi.type === 'checkpoint') return `models/checkpoints/${mi.filename}`\n if (mi.save_path.startsWith('custom_nodes')) return `${mi.save_path}/${mi.filename}`\n else return `models/${mi.save_path}/${mi.filename}`\n }\n\n getModelInfoEnumName = (mi: ComfyManagerModelInfo, prefix: string = ''): { win: string; nix: string } => {\n const relPath = this.getModelInfoFinalFilePath(mi)\n\n const winPath = relPath.replace(/\\//g, '\\\\')\n const winPrefix = prefix?.replace(/\\//g, '\\\\')\n const isUnderPrefixWin = winPath.startsWith(winPrefix)\n\n const nixPath = relPath.replace(/\\\\/g, '/')\n const nixPrefix = prefix?.replace(/\\//g, '\\\\')\n const isUnderPrefixNix = nixPath.startsWith(nixPrefix)\n\n const isUnderPrefix = isUnderPrefixNix || isUnderPrefixWin\n return {\n win: isUnderPrefix ? winPath.slice(winPrefix.length) : mi.filename /* winRel */,\n nix: isUnderPrefix ? nixPath.slice(nixPrefix.length) : mi.filename /* nixRel */,\n }\n }\n}\n","import { join } from 'pathe'\nimport pkgJson from '../package.json' with { type: 'json' }\nimport { ComfyHost, type ComfyHostData } from 'src/host/ComfyHost.ts'\nimport { parseHostBase, renderHttpBase } from 'src/host/hostUrl.ts'\nimport { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'\nimport { type ComfyStorage, resolveComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { type AbsolutePath, asAbsolutePath, type RelativePath } from 'src/types/index.ts'\n\n/** the ONE settings-file location rule — run-tui reads it BEFORE any module\n * import creates the comfyts global, so the path logic cannot live on the instance only */\nexport function settingsPathFor(root: string): AbsolutePath {\n return asAbsolutePath(join(root, '.comfy-ts', 'settings.json'))\n}\n\n/** singleton */\nexport class ComfyTS {\n version = pkgJson.version\n\n /** the storage seam (architecture item 13): node fs by default, in-memory on web */\n storage: ComfyStorage\n\n constructor(p: { rootPath?: string; storage?: ComfyStorage } = {}) {\n // global registration: the rest of the lib resolves paths through `comfyts`\n const globalHack = globalThis as { comfyts?: ComfyTS }\n if (globalHack.comfyts != null) throw new Error('ComfyTS instance already created')\n globalHack.comfyts = this\n // storage FIRST: the default rootPath comes from it (browser has no process.cwd)\n this.storage = resolveComfyStorage(p.storage)\n this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd())\n this.baseFolder = asAbsolutePath(join(this.rootPath, '.comfy-ts'))\n this.hostsFolder = asAbsolutePath(join(this.baseFolder, 'hosts'))\n this.outputPath = asAbsolutePath(join(this.baseFolder, 'outputs'))\n }\n\n /**\n * multi-module entrypoint: returns the existing global instance or creates\n * it. Workflow modules MUST use this (the TUI imports many of them into one\n * process); `new ComfyTS()` still throws on a second instance.\n */\n static create(p: { rootPath?: string; storage?: ComfyStorage } = {}): ComfyTS {\n const globalHack = globalThis as { comfyts?: ComfyTS }\n const existing = globalHack.comfyts\n if (existing == null) return new ComfyTS(p)\n if (p.rootPath != null && asAbsolutePath(p.rootPath) !== existing.rootPath)\n throw new Error(\n `ComfyTS.create({rootPath: '${p.rootPath}'}) conflicts with the existing instance rooted at '${existing.rootPath}'`,\n )\n return existing\n }\n\n /** every host created through host(), keyed by id — one instance (and one ws) per id */\n hosts: Map<string, ComfyHost> = new Map()\n\n host<const ID extends string>(data: ComfyHostData & { id: ID }): ComfyHost<ID> {\n const existing = this.hosts.get(data.id)\n if (existing != null) {\n // identity = the parsed base quad + apiKey PRESENCE (equivalent url and\n // host/port spellings unify; the key VALUE never appears in the error)\n const incoming = parseHostBase(data)\n const cur = existing.base\n const sameBase =\n cur.scheme === incoming.scheme &&\n cur.host === incoming.host &&\n cur.port === incoming.port &&\n cur.basePath === incoming.basePath\n const sameAuth = (existing.data.apiKey == null) === (data.apiKey == null)\n if (!sameBase || !sameAuth)\n throw new Error(\n `host id '${data.id}' already registered at ${renderHttpBase(cur)}${existing.data.apiKey != null ? ' (authed)' : ''} — refusing ${renderHttpBase(incoming)}${data.apiKey != null ? ' (authed)' : ''}`,\n )\n // cast: whitelist item 7 (agent/coding.md) — id equality checked just above\n return existing as ComfyHost<ID>\n }\n const created = new ComfyHost(data)\n this.hosts.set(data.id, created)\n return created\n }\n\n /**\n * A ComfyRegistry instance that provides access to all\n * known Comfy nodes, models, plugins, ...\n * lazy: constructing it parses ~3MB of ComfyUI-Manager JSON, only pay when used\n */\n private _registry: ComfyRegistry | null = null\n get registry(): ComfyRegistry {\n if (this._registry == null) this._registry = new ComfyRegistry({ check: false, genTypes: false })\n return this._registry\n }\n\n /** root path used to resolve things (set in the constructor, storage.cwd() default) */\n rootPath: AbsolutePath\n\n /**\n * every repo using comfy-ts gets ONE `.comfy-ts/` folder:\n * .comfy-ts/hosts/<id>/{object_info.json, embeddings.json, sdk.d.ts}\n * .comfy-ts/outputs/... generated images & workflows\n * .comfy-ts/drafts/<workflow-id>/<draft>.json TUI var snapshots (local, gitignored)\n * .comfy-ts/prompt-enhancers/<name>.md serve web ui master prompts (local, gitignored)\n */\n baseFolder: AbsolutePath\n hostsFolder: AbsolutePath\n outputPath: AbsolutePath\n\n resolveFromDrafts(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'drafts', relativePath))\n }\n\n /** master prompts of the serve web ui's prompt enhancer — hand-editable markdown */\n resolveFromPromptEnhancers(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'prompt-enhancers', relativePath))\n }\n\n resolveFromCache(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'cache', relativePath))\n }\n\n /** local TUI settings (preview mode, last draft per workflow) — gitignored */\n get settingsPath(): AbsolutePath {\n return settingsPathFor(this.rootPath)\n }\n\n resolveFromHosts(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.hostsFolder, relativePath))\n }\n\n /**\n * Resolves a relative path against an absolute path.\n * @param from - The absolute path to resolve from.\n * @param relativePath - The relative path to resolve.\n * @returns The resolved absolute path.\n */\n resolve(from: AbsolutePath, relativePath: RelativePath): AbsolutePath {\n return asAbsolutePath(join(from, relativePath))\n }\n resolveFromOutput(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.outputPath, relativePath))\n }\n\n readJSON_ = <T>(absPath: AbsolutePath, def?: T): T => {\n const str = this.storage.readTextIfExists(absPath)\n if (str == null) {\n if (def != null) return def\n throw new Error(`file does not exist ${absPath}`)\n }\n const json = JSON.parse(str)\n return json\n }\n\n // for automatic formating of produced ComfyUI workflow\n autolayoutOpts: {\n node_hsep: number\n node_vsep: number\n forceLeft: boolean\n } = {\n node_hsep: 50,\n node_vsep: 50,\n forceLeft: false,\n }\n}\n\ndeclare global {\n var comfyts: ComfyTS\n}\n","/**\n * build a LoraManager-style lora tag: `<lora:name:strength>` or\n * `<lora:name:strength:clipStrength>`. Pin the name to a host union for\n * autocomplete + validation:\n *\n * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)\n */\nexport function loraTag<N extends string = string>(name: N, strength: number = 1, clipStrength?: number): string {\n return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`\n}\n","/**\n * comfy-ts/web — the BROWSER entry (architecture item 13): same library,\n * in-memory storage, native WebSocket, no sharp. Types still come from a\n * generated sdk.d.ts included in the consumer's tsconfig.\n * Importing both entries in one process: the LAST import wins the default\n * backend — pass ComfyTS.create({ storage }) to be explicit (SSR setups).\n * @packageDocumentation\n */\nimport { createMemoryStorage, setDefaultComfyStorage } from 'src/storage/ComfyStorage.ts'\n\nsetDefaultComfyStorage(createMemoryStorage())\n\nexport * from 'src/coreExports.ts'\n\n// the serve web panel's postMessage host protocol, TYPES ONLY: a page embedding the panel in an\n// <iframe> types what it sends and receives, and no runtime enters the browser graph\nexport type {\n HostToPanel,\n PanelError,\n PanelHostAction,\n PanelRequest,\n PanelResultAction,\n PanelState,\n PanelToHost,\n} from 'src/cli/serve/hostProtocol.ts'\n"],"mappings":";;;;;;AAmCA,SAAS,UAAU,MAAsB;CACtC,MAAM,KAAK,KAAK,YAAY,GAAG;CAC/B,OAAO,MAAM,IAAI,MAAM,KAAK,MAAM,GAAG,EAAE;AAC1C;;;AAIA,SAAgB,sBAAsB,IAAgB,IAA8B;CACjF,OAAO;EACJ,MAAM;EACN,WAAW,MAAM,GAAG,aAAa,GAAG,MAAM;EAC1C,mBAAmB,MAAO,GAAG,WAAW,CAAC,IAAK,GAAG,aAAa,GAAG,MAAM,IAAe;EACtF,YAAY,MAAM,IAAI,WAAW,GAAG,aAAa,CAAC,CAAe;EACjE,YAAY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