comfy-ts 2.18.0 → 2.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["g","fs","os","type","type","type","type","type","type","type","type","type","isRecord","isRecord","type","type","types","chalk","type","isRecord","type","type","type","type","type","type","observable","observable","action","type","chalk","chalk","type","type","chalk","type","type","type","chalk","type","type","chalk","type","type","chalk","pkgJson.version","globalHack"],"sources":["../src/storage/ComfyStorage.ts","../src/storage/nodeStorage.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/host/previewMethod.ts","../src/runner/wsBinaryFrame.ts","../src/sdk-generator/Primitives.ts","../src/utils/exhaust.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/sha1.ts","../src/utils/hashArrayBuffer.ts","../src/graph/ComfyNodeID.ts","../src/runner/ComfyWsApi.ts","../src/runner/MediaImage.ts","../src/runner/mediaKinds.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/installedView.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/loraEntry.ts","../src/vars/lanes.ts","../src/vars/promptSyntax.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/exampleAssets.ts","../src/utils/safeName.ts","../src/promptEnhancers.ts","../src/cli/tui-env.ts","../src/index.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","// the ONLY core-path module allowed to import node:fs statically\n// (architecture item 13) — index.ts installs it; the web graph never sees it\nimport * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport { type ComfyStorage, createNodeStorageFrom } from 'src/storage/ComfyStorage.ts'\n\nexport function createNodeStorage(): ComfyStorage {\n return createNodeStorageFrom(fs, os)\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 widgetSource: i.widgetSource,\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 // 8. a subgraph input with no outer link resolves to its promoted widget (frontend\n // ExecutableNodeDTO.resolveInput): its slot targets read that widget's value\n for (const [slot, targets] of boundaryTargetsByInSlot) {\n if (outerLinkIntoDefSlot.has(slot)) continue\n const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null)\n const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null\n if (source == null || sourceInput == null) continue\n for (const t of targets) {\n const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot]\n if (input == null || input.widgetName != null || input.link != null) continue\n input.widgetSource = { nodeId: source.nodeId, inputName: sourceInput.name }\n }\n }\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 | null // | 'select' (null in the official fibo2 templates)\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?': type.string.or(type.null),\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 | null // the official fibo2 templates write null\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_.or(type.null),\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 | string // v0.4 (recomputable, absent in v1), a NodeId: the official blueprints write a string\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 | string',\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 widgetSource: 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","// ComfyUI sends live preview frames only when launched with `--preview-method` set to\n// something other than its default `none`. The launch flags reach a client through\n// `GET /system_stats` (`system.argv`), the one place a client can read them.\n\nexport type PreviewMethod = 'none' | 'auto' | 'latent2rgb' | 'taesd'\n\nfunction isPreviewMethod(x: unknown): x is PreviewMethod {\n return x === 'none' || x === 'auto' || x === 'latent2rgb' || x === 'taesd'\n}\n\n/** the preview method a host was launched with, from its /system_stats payload. `'none'` when\n * the flag is absent (ComfyUI's default), null when the payload carries no argv to read (a cloud\n * host) or the flag holds a value this parser does not know */\nexport function previewMethodFromSystemStats(stats: unknown): PreviewMethod | null {\n if (stats == null || typeof stats !== 'object' || !('system' in stats)) return null\n const system = stats.system\n if (system == null || typeof system !== 'object' || !('argv' in system)) return null\n const argv = system.argv\n if (!Array.isArray(argv)) return null\n for (let i = 0; i < argv.length; i++) {\n const arg: unknown = argv[i]\n if (typeof arg !== 'string') continue\n const value =\n arg === '--preview-method' ? argv[i + 1] : arg.startsWith('--preview-method=') ? arg.slice(17) : undefined\n if (value === undefined) continue\n return isPreviewMethod(value) ? value : null\n }\n return 'none'\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 const BINARY_FRAME_PREVIEW_IMAGE = 1\nexport const BINARY_FRAME_TEXT = 3\nexport const BINARY_FRAME_PREVIEW_IMAGE_WITH_METADATA = 4\n\nexport type ParsedPreviewFrame = { kind: 'preview'; bytes: Uint8Array<ArrayBuffer>; mime: string; metadata: unknown }\n\nexport type ParsedBinaryWsFrame =\n | ParsedPreviewFrame\n | { kind: 'text'; nodeId: string; text: string }\n | { kind: 'unknown'; eventType: number }\n\n/** the frame's event type, read in place: deciding whether anyone wants a frame costs no copy */\nexport function binaryFrameType(data: ArrayBuffer): number {\n if (data.byteLength < 4) return -1\n return new DataView(data).getUint32(0)\n}\n\nexport function isPreviewFrameType(eventType: number): boolean {\n return eventType === BINARY_FRAME_PREVIEW_IMAGE || eventType === BINARY_FRAME_PREVIEW_IMAGE_WITH_METADATA\n}\n\nexport function parseBinaryWsFrame(data: ArrayBuffer): ParsedBinaryWsFrame {\n const eventType = binaryFrameType(data)\n if (isPreviewFrameType(eventType)) return parsePreviewFrame(data)\n\n if (eventType === BINARY_FRAME_TEXT) {\n const nodeIdLen = new DataView(data).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 return { kind: 'unknown', eventType }\n}\n\n/** a type 1 or type 4 frame; the caller checked the type with `isPreviewFrameType` */\nexport function parsePreviewFrame(data: ArrayBuffer): ParsedPreviewFrame {\n const view = new DataView(data)\n if (view.getUint32(0) === BINARY_FRAME_PREVIEW_IMAGE) {\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 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/** the node a type 4 frame names (`node_id` in its metadata), null when absent or malformed */\nexport function previewMetadataNodeId(metadata: unknown): string | null {\n if (metadata == null || typeof metadata !== 'object' || !('node_id' in metadata)) return null\n return typeof metadata.node_id === 'string' && metadata.node_id !== '' ? metadata.node_id : null\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","/* 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","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 /** widget rows: prompt keys `<decl>.<row>.<field>`, saved run `[count, …row field runs]` (architecture.md, dynamic group) */\n | { kind: 'dynamic-group'; fields: RawInputSpecEntry[]; min: number; max: 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/** dynamic group (`template` holding `required`/`optional` sections itself): fields in the\n * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */\nconst parseGroup = (o: Record<string, unknown>, template: Record<string, unknown>): InputWidgetKind => ({\n kind: 'dynamic-group',\n fields: flattenInputSections(template),\n min: typeof o['min'] === 'number' ? o['min'] : 0,\n max: typeof o['max'] === 'number' ? o['max'] : 20,\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; WITH its own required/optional\n // sections = dynamic group; with neither = matchtype slot typing\n const template = o?.['template']\n if (o != null && isRecord(template)) {\n if (isRecord(template['input'])) return parseContainer(template)\n if (isRecord(template['required']) || isRecord(template['optional'])) return parseGroup(o, template)\n return { kind: 'slot' }\n }\n // 7. a socketless KEY, true or false: only a backend WidgetInput emits it (true = no socket,\n // IMAGECOMPARE, COLOR; false = a socket too, BOUNDING_BOXES, COLORS); value domain unknown\n if (typeof o?.['socketless'] === 'boolean')\n 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 { exhaust } from 'src/utils/exhaust.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 /** the row count first (named, else positional, else `min`), then every row's fields in\n * template order: the frontend's saved run (architecture.md, dynamic group) */\n const consumeDynamicGroup = (p: {\n path: string\n fields: RawInputSpecEntry[]\n min: number\n max: number\n }): void => {\n const r = resolveWidgetValue({ promptName: p.path, consumes: 1, prefixLen: 0 })\n const saved = r.filled ? p.min : r.value\n if (typeof saved !== 'number' || !Number.isInteger(saved) || saved < 0 || saved > p.max)\n throw new WorkflowConvertError(\n 'invalid-widget-value',\n `node ${node.id}(${node.type}): dynamic group \"${p.path}\" row count is not an integer in [0, ${p.max}]: ${JSON.stringify(saved)}`,\n node,\n )\n // the frontend clamps a short count UP to min (dynamicGroupWidget: Math.max(min, requested))\n const rows = Math.max(p.min, saved)\n if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`)\n for (let row = 0; row < rows; row++)\n for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field)\n }\n\n const consumeBranchInput = (subPath: string, sub: RawInputSpecEntry): void => {\n // the frontend names a branch or row widget by its full dotted path, and the seed\n // heuristic of the control phantom reads that name (architecture.md, rule 9)\n const kind = classifyWidgetInput({ name: subPath, type: sub.type, opts: sub.opts })\n switch (kind.kind) {\n // slots and containers materialize as dotted serialized inputs, resolved as links in 2.b\n case 'slot':\n case 'dynamic-container':\n return\n case 'dynamic-combo':\n return consumeDynamicCombo({ path: subPath, options: kind.options, defaultKey: kind.defaultKey })\n case 'dynamic-group':\n return consumeDynamicGroup({ path: subPath, fields: kind.fields, min: kind.min, max: kind.max })\n case 'widget':\n break\n default:\n return exhaust(kind)\n }\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 switch (kind.kind) {\n case '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 break\n case 'dynamic-combo':\n consumeDynamicCombo({ path: field.nameInComfy, options: kind.options, defaultKey: kind.defaultKey })\n break\n case 'dynamic-group':\n consumeDynamicGroup({ path: field.nameInComfy, fields: kind.fields, min: kind.min, max: kind.max })\n break\n case '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 break\n case 'slot':\n // a value promoted onto a slot (io-widget era subgraph): the frontend sends the literal\n if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {\n inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {\n promptName: field.nameInComfy,\n strict: false,\n })\n break\n }\n if (!fieldNamesPresent.has(field.nameInComfy) && 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 break\n default:\n exhaust(kind)\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 // 3. unlinked slots a subgraph input fed with no outer link take that input's promoted widget\n // value, read from the sibling widget it also fed, once every node is converted\n for (const node of workflow.nodes) {\n const own = prompt[String(node.id)]\n if (own == null) continue\n for (const ipt of node.inputs) {\n if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue\n const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName]\n if (value !== undefined) own.inputs[ipt.name] = value\n }\n }\n\n // 4. a required plain input absent from the prompt. ComfyUI validates per OUTPUT node\n // (execution.py validate_prompt): it runs the outputs whose upstream nodes are complete and\n // rejects the prompt only when none is. Same here: a typed error when no output survives, a\n // loud warning naming what ComfyUI will drop otherwise; never silent\n const missing = new Map<string, { node: CanonicalNode; message: string }>()\n for (const node of workflow.nodes) {\n const own = prompt[String(node.id)]\n const nodeSchema = schema.nodesByNameInComfy[node.type]\n if (own == null || nodeSchema == null) continue\n for (const field of nodeSchema.inputs) {\n if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue\n const kind = classifySchemaInput(field).kind\n if (kind !== 'slot' && kind !== 'widget') continue\n missing.set(String(node.id), {\n node,\n message: `node ${node.id}(${node.type}): required input \"${field.nameInComfy}\" (${field.typeName}) is unlinked and no value covers it`,\n })\n break\n }\n }\n if (missing.size > 0) {\n const complete = (id: string, seen: Set<string>): boolean => {\n if (seen.has(id)) return true\n seen.add(id)\n if (missing.has(id)) return false\n for (const value of Object.values(prompt[id]?.inputs ?? {}))\n if (Array.isArray(value) && typeof value[0] === 'string' && !complete(value[0], seen)) return false\n return true\n }\n const outputs = Object.keys(prompt).filter(\n (id) => schema.data.spec[prompt[id]?.class_type ?? '']?.output_node === true,\n )\n const dropped = outputs.filter((id) => !complete(id, new Set()))\n const first = missing.values().next().value\n if (first != null && outputs.length > 0 && dropped.length === outputs.length)\n throw new WorkflowConvertError('missing-required-input', first.message, first.node)\n if (dropped.length > 0 || outputs.length === 0)\n console.warn(\n `🟡 [workflow] ComfyUI will skip output node(s) ${dropped.join(', ') || '(none in this graph)'}: ${[...missing.values()].map((m) => m.message).join('; ')}`,\n )\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, RawInputSpecEntry } 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'\nimport { exhaust } from 'src/utils/exhaust.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 a dynamic input wrote or dropped on purpose: the rest loop skips them */\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 switch (kind.kind) {\n case '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 case 'dynamic-group':\n this._writeDynamicGroup({\n name: i.nameInComfy,\n fields: kind.fields,\n min: kind.min,\n max: kind.max,\n provided: promptExt.inputs,\n out: inputs,\n claimed: _comboBranchKeys,\n })\n continue\n case 'widget':\n case 'slot':\n case 'dynamic-container':\n break\n default:\n exhaust(kind)\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 /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled\n * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted\n * keys are already the rows: they pass through the rest loop untouched */\n private _writeDynamicGroup(p: {\n name: string\n fields: RawInputSpecEntry[]\n min: number\n max: number\n provided: { [k: string]: unknown }\n out: { [k: string]: any }\n claimed: Set<string>\n }): void {\n const where = `${this.$schema.nodeKey}#${this.uid}`\n const raw = p.provided[p.name]\n const prefix = `${p.name}.`\n if (raw == null) {\n const hasRows = Object.keys(p.provided).some((k) => k.startsWith(prefix))\n if (!hasRows && p.min > 0)\n this.graph.recordProblem(`🔴 \"${p.name}\" on ${where} needs at least ${p.min} row(s)`)\n return\n }\n // the array wins over stray dotted keys of the same group\n for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k)\n if (!Array.isArray(raw)) {\n this.graph.recordProblem(`🔴 \"${p.name}\" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`)\n return\n }\n if (raw.length < p.min || raw.length > p.max)\n this.graph.recordProblem(\n `🔴 \"${p.name}\" on ${where} has ${raw.length} row(s), the host takes ${p.min} to ${p.max}`,\n )\n raw.forEach((row: unknown, ix) => {\n if (typeof row !== 'object' || row == null || Array.isArray(row)) {\n this.graph.recordProblem(`🔴 \"${p.name}\" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`)\n return\n }\n const given = new Map(Object.entries(row))\n for (const field of p.fields) {\n const dotted = `${p.name}.${ix}.${field.name}`\n const value = given.get(field.name)\n p.out[dotted] =\n value == null\n ? defaultValueForWidget({\n type: typeof field.type === 'string' ? field.type : 'COMBO',\n opts: field.opts,\n enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : undefined,\n })\n : this.serializeValue(dotted, value)\n given.delete(field.name)\n }\n for (const extra of given.keys())\n this.graph.recordProblem(`🔴 \"${p.name}\" row ${ix} on ${where} has no field \"${extra}\"`)\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 // dynamic group row field `decl.<row>.<field>`: the template field carries the type\n if (kind.kind === 'dynamic-group') {\n const rest = name.slice(dot + 1)\n const fieldName = rest.slice(rest.indexOf('.') + 1)\n const field = kind.fields.find((f) => f.name === fieldName)\n if (rest.includes('.') && typeof field?.type === 'string') return field.type\n }\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 {\n classifySchemaInput,\n classifyWidgetInput,\n containerInstanceSlotType,\n defaultValueForWidget,\n type InputWidgetKind,\n type RawInputSpecEntry,\n} from 'src/sdk-generator/inputWidgetKind.ts'\nimport { exhaust } from 'src/utils/exhaust.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 // target_slot = index within THIS node's litegraph inputs array,\n // not the schema input index (widget inputs are not litegraph slots)\n const pushLinked = (\n name: string,\n type: string,\n link: [string, number],\n extra: { shape?: number; widget?: boolean } = {},\n ): void => {\n const nodeUidNumber = bang(\n ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber,\n `link target node \"${link[0]}\" not found in graph`,\n )\n const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)\n const input: LiteGraphNodeInput = { name, type, link: linkId }\n if (extra.shape != null) input.shape = extra.shape\n if (extra.widget === true) input.widget = { name }\n inputs.push(input)\n }\n /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate\n * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven\n * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can\n * never disagree on the run length */\n const pushWidgetRun = (kind: Extract<InputWidgetKind, { kind: 'widget' }>, raw: unknown, opts: unknown): void => {\n widgets_values.push(...kind.prefixValues, raw)\n const phantoms = kind.consumes - 1 - kind.prefixValues.length\n for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts))\n }\n /** one input, the way the editor saves it: a widget writes its run (a linked one too, with\n * its widget socket, since the editor serializes every widget), a dynamic combo its key then\n * the selected branch inline, a group its row count then the rows, a slot its socket */\n const writeInput = (p: {\n name: string\n kind: InputWidgetKind\n typeName: string\n opts: unknown\n value: unknown\n }): void => {\n const where = `${node.$schema.nameInComfy}#${node.uid} \"${p.name}\"`\n switch (p.kind.kind) {\n case 'widget':\n if (_isLink(p.value)) {\n pushLinked(p.name, p.typeName, p.value, { widget: true })\n pushWidgetRun(p.kind, defaultValueForWidget({ type: p.typeName, opts: p.opts }), p.opts)\n } else pushWidgetRun(p.kind, p.value, p.opts)\n return\n case 'slot':\n // an unconnected slot is a litegraph socket with no link, NEVER a widget value\n if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value)\n else inputs.push({ name: p.name, type: p.typeName, link: null })\n return\n case 'dynamic-combo': {\n const kind = p.kind\n const key = typeof p.value === 'string' ? p.value : kind.defaultKey\n const option = kind.options.find((o) => o.key === key)\n if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: \"${key}\" is not one of its options`)\n widgets_values.push(key)\n for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub)\n return\n }\n case 'dynamic-container': {\n // the declaration is never a slot: each grown instance is its own\n // optional slot `decl.<instance>` (shape 7), as the editor stores it\n const type = containerInstanceSlotType(p.opts) ?? '*'\n for (const instance of p.kind.instanceNames) {\n const name = `${p.name}.${instance}`\n const value = node.json.inputs[name]\n if (value == null) continue\n const raw = node.serializeValue(name, value)\n if (!_isLink(raw))\n throw new Error(\n `🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`,\n )\n pushLinked(name, type, raw, { shape: 7 })\n }\n return\n }\n case 'dynamic-group': {\n // the editor's run: the row count, then each row's field runs (dynamicGroupWidget.ts)\n const prefix = `${p.name}.`\n let rows = 0\n for (const key of Object.keys(node.json.inputs)) {\n if (!key.startsWith(prefix)) continue\n const row = Number(key.slice(prefix.length).split('.')[0])\n if (Number.isInteger(row) && row >= rows) rows = row + 1\n }\n widgets_values.push(rows)\n for (let row = 0; row < rows; row++)\n for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field)\n return\n }\n default:\n exhaust(p.kind)\n }\n }\n /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent\n * value is the widget's schema default rather than serializeValue's */\n const writeSub = (name: string, sub: RawInputSpecEntry): void => {\n const typeName = typeof sub.type === 'string' ? sub.type : 'COMBO'\n const raw: unknown = node.json.inputs[name]\n writeInput({\n name,\n kind: classifyWidgetInput({ name, type: sub.type, opts: sub.opts }),\n typeName,\n opts: sub.opts,\n value: raw === undefined ? defaultValueForWidget({ type: typeName, opts: sub.opts }) : raw,\n })\n }\n for (const ipt of node.$schema.inputs) {\n const kind = classifySchemaInput(ipt)\n // a dynamic input's own key is never a schema-default value: read it raw\n const raw = node.json.inputs[ipt.nameInComfy]\n const value = kind.kind === 'widget' || kind.kind === 'slot' ? node.serializeValue(ipt.nameInComfy, raw) : raw\n writeInput({ name: ipt.nameInComfy, kind, typeName: ipt.typeName, opts: ipt.opts, value })\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\n/** the editor's control widget is a combo (fixed, increment, decrement, randomize):\n * a config naming a mode keeps it, anything else is `fixed`, the seed the code pinned */\nconst controlMode = (opts: unknown): string => {\n const mode = typeof opts === 'object' && opts != null ? Reflect.get(opts, 'control_after_generate') : null\n return typeof mode === 'string' ? mode : 'fixed'\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","// 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 { IsEqual, 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 // null for a cached node whose cache entry holds no ui payload (asset_enrichment.emit_cached_output)\n output: '_WsMsgExecutedOutput | null',\n prompt_id: 'PromptID',\n },\n _WsMsgExecutedOutput: {\n 'previews?': [{ filepath: 'string' }, '[]'],\n 'images?': 'ComfyImageInfo[]',\n // SaveAudio*, PreviewAudio: same file triple as an image\n 'audio?': 'ComfyImageInfo[]',\n // VideoHelperSuite's VHS_VideoCombine, and savers that name their list `video`\n 'video?': 'ComfyImageInfo[]',\n 'gifs?': '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 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 // execution.py sends list(current_outputs): the ids of the nodes that already have outputs\n current_outputs: 'ComfyNodeID[]',\n },\n WsMsgExecutionError: {\n type: \"'execution_error'\",\n data: '_WsMsgExecutionErrorData',\n },\n\n // an interrupt (POST /interrupt) ends the prompt with this and no execution_success\n _WsMsgExecutionInterruptedData: {\n prompt_id: 'PromptID',\n node_id: 'ComfyNodeID',\n node_type: 'string',\n executed: 'ComfyNodeID[]',\n },\n WsMsgExecutionInterrupted: {\n type: \"'execution_interrupted'\",\n data: '_WsMsgExecutionInterruptedData',\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 | WsMsgExecutionInterrupted | 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; metadata: unknown }\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 WsMsgExecutionInterrupted = typeof types.WsMsgExecutionInterrupted.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\n\n/** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */\nexport const ROUTED_WS_EVENT_TYPES = [\n 'status',\n 'manager-terminal-feedback',\n 'logs',\n 'execution_start',\n 'execution_cached',\n 'executing',\n 'progress',\n 'progress_state',\n 'executed',\n 'execution_error',\n 'execution_interrupted',\n 'execution_success',\n] as const\ntrue satisfies IsEqual<(typeof ROUTED_WS_EVENT_TYPES)[number], WsMsg['type']>\n\n/** events a server or a custom node sends by design that comfy-ts has no use for: dropped\n * before validation, never logged (architecture.md, ws events) */\nexport const IGNORED_WS_EVENT_TYPES = [\n // ComfyUI server.py: only the reply to a client that opens with its own feature_flags\n 'feature_flags',\n // ComfyUI app/agent_host.py: the local agent host's state, broadcast\n 'agent_status',\n // ComfyUI app/asset_export.py: an export task's progress, broadcast\n 'asset_export',\n // ComfyUI app/assets/seeder.py: the asset index scan, broadcast while the assets system is on\n 'assets.seed.started',\n 'assets.seed.progress',\n 'assets.seed.fast_complete',\n 'assets.seed.enrich_complete',\n 'assets.seed.completed',\n 'assets.seed.cancelled',\n 'assets.seed.error',\n 'assets.seed.paused',\n 'assets.seed.resumed',\n // ComfyUI-Manager (V3.x legacy and 4.x): install queue progress, broadcast\n 'cm-queue-status',\n 'cm-api-try-install-customnode',\n // ComfyUI-Manager 4.x glob/manager_server.py: one task of the install queue\n 'cm-task-started',\n 'cm-task-completed',\n // ComfyUI-Crystools: the resource monitor, about once a second\n 'crystools.monitor',\n] as const\n\nconst ROUTED_SET: ReadonlySet<string> = new Set(ROUTED_WS_EVENT_TYPES)\nconst IGNORED_SET: ReadonlySet<string> = new Set(IGNORED_WS_EVENT_TYPES)\nexport const isRoutedWsEventType = (t: string): boolean => ROUTED_SET.has(t)\nexport const isIgnoredWsEventType = (t: string): boolean => IGNORED_SET.has(t)\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 = workflow.dry ? this.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 = workflow.dry ? this.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","// the three media a var can take and an output can be. PURE + dependency-free: the web bundle\n// imports it to decide which var a dropped output may land on\n\nexport type MediaKind = 'image' | 'audio' | 'video'\n\nexport const MEDIA_KINDS: readonly MediaKind[] = ['image', 'audio', 'video']\n\n/** picker defaults per kind, lowercase without dots */\nexport const DEFAULT_MEDIA_EXTENSIONS: Record<MediaKind, readonly string[]> = {\n image: ['png', 'jpg', 'jpeg', 'webp', 'gif'],\n audio: ['wav', 'flac', 'mp3', 'ogg', 'opus', 'm4a'],\n video: ['mp4', 'webm', 'mov', 'mkv', 'm4v'],\n}\n\nconst MIMES: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n flac: 'audio/flac',\n mp3: 'audio/mpeg',\n opus: 'audio/ogg',\n ogg: 'audio/ogg',\n wav: 'audio/wav',\n m4a: 'audio/mp4',\n aac: 'audio/aac',\n mp4: 'video/mp4',\n m4v: 'video/mp4',\n webm: 'video/webm',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n avi: 'video/x-msvideo',\n}\n\n/** video containers an output node can name. An animated webp or gif is an IMAGE: the\n * extension decides, never the `animated` flag */\nconst VIDEO_EXTENSIONS = new Set(['mp4', 'm4v', 'webm', 'mov', 'mkv', 'avi'])\n\nexport function extensionOf(filename: string): string {\n const dot = filename.lastIndexOf('.')\n return dot < 0 ? '' : filename.slice(dot + 1).toLowerCase()\n}\n\nexport function isVideoFilename(filename: string): boolean {\n return VIDEO_EXTENSIONS.has(extensionOf(filename))\n}\n\nexport function mediaMime(filename: string): string {\n return MIMES[extensionOf(filename)] ?? 'application/octet-stream'\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 WsMsgExecutionInterrupted,\n WsMsgExecutionSuccess,\n} from 'src/runner/ComfyWsApi.ts'\nimport { MediaImage } from 'src/runner/MediaImage.ts'\nimport { isVideoFilename, mediaMime } from 'src/runner/mediaKinds.ts'\nimport { previewMetadataNodeId } from 'src/runner/wsBinaryFrame.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 | WsMsgExecutionInterrupted | null\n status?: ComfyExecutionStatus | null\n}\n\n/** one audio file an output node published, downloaded as the server wrote it.\n * `absPath` is null when saving is off: `bytes` is then the only copy */\nexport type ComfyAudioOutput = {\n nodeId: ComfyNodeId\n filename: string\n mime: string\n bytes: Uint8Array\n absPath: AbsolutePath | null\n}\n\n/** one video file an output node published (SaveVideo, SaveWEBM, VHS_VideoCombine), same\n * shape and same retrieval as an audio file */\nexport type ComfyVideoOutput = ComfyAudioOutput\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\n/** one live preview frame of a run: the image a sampler is forming, once per step */\nexport type ExecutionPreview = {\n promptId: PromptID\n /** the image as ComfyUI encoded it, jpeg or png */\n bytes: Uint8Array\n mime: string\n /** the node that sent the frame: the frame's own metadata when it names one (type 4 frames),\n * else the node executing when it arrived. Null when neither is known */\n nodeId: ComfyNodeId | null\n /** that node's class name in the sent prompt (`KSampler`), null when unknown */\n nodeName: string | null\n /** that node's own counter when the frame arrived (sampler step of total), null when unknown */\n step: { value: number; max: number } | null\n /** the raw metadata json of a type 4 frame (`node_id`, `prompt_id`, …), null on a type 1 frame */\n metadata: unknown\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 onPreview?: Maybe<(p: ExecutionPreview) => 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.onPreview = init.onPreview ?? 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 /** called on every live preview frame of this run. Null = frames are never decoded for it */\n onPreview: Maybe<(p: ExecutionPreview) => 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.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`)\n if (this.videos.length > 0) outputs.push(`${this.videos.length} video(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, else a preview\n if (msg.type === 'binary_preview_frame') {\n if (this.wsOutputNodeExecuting) this.onWsImageOutput({ bytes: msg.bytes, mime: msg.mime })\n else this.onPreviewFrame(msg)\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 // the server sends no execution_success after an interrupt: this message ends the run\n else if (msg.type === 'execution_interrupted') return void this._finish({ status: 'Failure', error: 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 // a video file rides `images` (SaveVideo), `video` or `gifs` (VideoHelperSuite): the\n // extension decides, so an animated webp or gif stays an image\n const out = msg.data.output\n // a loader (LoadVideo) echoes the file it READ, typed 'input': a preview, never an output\n const listed = [...(out?.images ?? []), ...(out?.video ?? []), ...(out?.gifs ?? [])].filter(\n (f) => f.type !== 'input',\n )\n for (const video of listed.filter((f) => isVideoFilename(f.filename))) {\n this.pendingPromises.push(\n this.retrieveFile('video', video, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to retrieve ${video.filename}:`, e)\n this.videoErrors.push({ video, error: e })\n }),\n )\n }\n const images = listed.filter((f) => !isVideoFilename(f.filename))\n if (images.length > 0) {\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 for (const audio of msg.data.output?.audio ?? []) {\n this.pendingPromises.push(\n this.retrieveFile('audio', audio, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to retrieve ${audio.filename}:`, e)\n this.audioErrors.push({ audio, error: e })\n }),\n )\n }\n }\n private pendingPromises: Promise<void>[] = []\n\n /** audio retrievals that failed (their files are missing from `audios`) */\n audioErrors: { audio: ComfyImageInfo; error: unknown }[] = []\n\n /** audio files retrieved for this execution, in arrival order (final once `done` resolves) */\n audios: ComfyAudioOutput[] = []\n\n /** video retrievals that failed (their files are missing from `videos`) */\n videoErrors: { video: ComfyImageInfo; error: unknown }[] = []\n\n /** video files retrieved for this execution, in arrival order (final once `done` resolves) */\n videos: ComfyVideoOutput[] = []\n\n private retrieveFile = async (\n kind: 'audio' | 'video',\n info: ComfyImageInfo,\n promptNodeID: ComfyNodeId,\n ): Promise<void> => {\n const response = await this.host.fetchFile('/view?' + new URLSearchParams(info).toString())\n const bytes = new Uint8Array(await response.arrayBuffer())\n const mime = mediaMime(info.filename)\n const list = kind === 'audio' ? this.audios : this.videos\n const sf = this.save\n if (sf == null) {\n list.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: null })\n return\n }\n const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs['filename_prefix']\n const written = await this.encodeAndWrite({\n bytes,\n // never re-encoded: `save.format` is an image setting\n sf: { ...sf, format: 'raw' },\n filenamePrefix: typeof promptPrefix === 'string' ? promptPrefix : undefined,\n subfolder: info.subfolder,\n filename: info.filename,\n })\n list.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: written.path })\n }\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 /** @internal a live preview frame of this run; never an output (the host routes ws saver frames\n * to onWsImageOutput before they get here) */\n onPreviewFrame(p: { bytes: Uint8Array; mime: string; metadata: unknown }): void {\n const listener = this.onPreview\n if (listener == null) return\n const current = this.workflow.currentExecutingNode\n const named = previewMetadataNodeId(p.metadata)\n const nodeId: ComfyNodeId | null = named ?? current?.uid ?? null\n const apiJson = this.snapshot?.apiJson ?? this.workflow.apiJson\n const counter = current != null && current.uid === nodeId ? current.progress : null\n listener({\n promptId: this.data.id,\n bytes: p.bytes,\n mime: p.mime,\n nodeId,\n nodeName: nodeId != null ? (apiJson[nodeId]?.class_type ?? null) : null,\n step: counter != null ? { value: counter.value, max: counter.max } : null,\n metadata: p.metadata,\n })\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 ExecutionPreview, 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 /** called on every live preview frame of this run (the image a sampler is forming). Opt in:\n * without it no frame is decoded for the run. ComfyUI sends frames only when launched with\n * `--preview-method`, see `host.fetchPreviewMethod()` */\n onPreview?: (p: ExecutionPreview) => 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 /** a dry build: media loads name the local file by its hash and upload nothing, so a graph\n * can be built only to be read (serve derives workflow tags this way) */\n dry = false\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 onPreview: p.onPreview,\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 { exhaust } from 'src/utils/exhaust.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/** one dynamic-group row as an object type: a field is optional when it has a default or sits in\n * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */\nconst dynamicGroupRow = (fields: RawInputSpecEntry[]): string => {\n const members = fields.map((e) => {\n const opts = isRecord(e.opts) ? e.opts : null\n const optional = !e.required || opts?.['default'] !== undefined\n return `${escapeJSKey(e.name)}${optional ? '?' : ''}: ${branchInputType(e)}`\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 /** one row type per dynamic group, named once so a long COMBO union is not printed twice */\n const groupRows: [key: string, row: string][] = []\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 switch (kind.kind) {\n case '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 case '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 case 'dynamic-group': {\n // an array of row objects, the backend's own list[dict] value; ComfyNode\n // expands it to the dotted `<decl>.<row>.<field>` prompt keys\n const rowKey = `${n.nodeKey}.${i.nameInComfy}`\n groupRows.push([rowKey, dynamicGroupRow(kind.fields)])\n const row = `GroupRow[${JSON.stringify(rowKey)}]`\n p(` /** min=${kind.min} max=${kind.max} rows */`)\n if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`)\n else p(` ${i.nameInComfyEscaped}?: ${row}[]`)\n continue\n }\n case 'widget':\n case 'slot':\n break\n default:\n exhaust(kind)\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 if (groupRows.length > 0) {\n p(`/** one row of each dynamic group input, keyed \\`<node>.<input>\\` */`)\n p(`interface GroupRow {`)\n b.indent()\n for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`)\n b.deindent()\n p('}')\n p('')\n }\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 ?? n.nameInComfy}\" 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 // dynamic group: row fields are typed by their own slot types, and the group is\n // required exactly when it needs rows (upstream counts min even on an optional input)\n if (widgetKind?.kind === 'dynamic-group') {\n for (const entry of widgetKind.fields) {\n if (typeof entry.type === 'string') this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type))\n }\n }\n const required =\n widgetKind?.kind === 'dynamic-group' ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer\n\n node.inputs.push({\n slotName: inputSlotName,\n required,\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 | null)[]',\n output_name: 'string[]',\n name: 'string',\n display_name: 'string | null',\n description: 'string',\n /** */\n python_module: 'string',\n category: 'string',\n output_node: 'boolean',\n 'output_tooltips?': '(string | null)[]',\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 // a trailing extra entry (kjnodes EndRecordCUDAMemoryHistory: a description string); ComfyUI\n // and its frontend read [0] and [1] only, so do we\n ComfyInputSpecAlt4: ['ComfyInputType', 'ComfyInputOpts', 'unknown'],\n ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,\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 // number[] and object: widget defaults like a size pair, a curve, a trim window\n 'default?': 'boolean | number | string | null | number[] | object',\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","/**\n * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),\n * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).\n * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.\n */\nimport { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { ComfyManagerAPIModelList } from 'src/manager/types/ComfyManagerAPIModelList.ts'\nimport type { ComfyManagerAPIPluginList } from 'src/manager/types/ComfyManagerAPIPluginList.ts'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\n/** the part of the registry the views read */\nexport type ManagerMirror = {\n plugins_byTitle: ReadonlyMap<KnownComfyPluginTitle, ComfyManagerPluginInfo>\n /** every model row: upstream ships a few names twice, with different files */\n modelRows: readonly ComfyManagerModelInfo[]\n}\n\n/** `GET customnode/installed`: a disk scan, keyed by directory */\nexport const InstalledPacks_ark = type.Record(\n 'string',\n type({ 'cnr_id?': 'string | null', 'aux_id?': 'string | null', enabled: 'boolean' }),\n)\nexport type InstalledPacks = typeof InstalledPacks_ark.infer\n\n/** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */\nexport const PackMappings_ark = type.Record('string', type(['string[]', { 'title_aux?': 'string' }]))\nexport type PackMappings = typeof PackMappings_ark.infer\n\n/** `https://github.com/Owner/Repo.git/` → `owner/repo` */\nexport const repoPath = (url: string): string =>\n url\n .toLowerCase()\n .replace(/\\/+$/, '')\n .replace(/\\.git$/, '')\n .split('/')\n .slice(-2)\n .join('/')\n\n/** one installed pack, joined to the mirror when the data allows it */\nexport type AttributedPack = { enabled: boolean; repo: string | null; title: string | null; id: string }\n\n/** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */\nexport const attributePacks = (installed: InstalledPacks, mappings: PackMappings): AttributedPack[] => {\n // registry ids are case insensitive: the mappings keep the registry's casing, the scan lowercases\n const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]))\n return Object.entries(installed).map(([dir, p]) => {\n const aux = p.aux_id ?? null\n const cnr = p.cnr_id != null && p.cnr_id !== '' ? p.cnr_id : null\n const repo = aux != null && aux.includes('/') ? repoPath(aux) : null\n const title = cnr != null ? (titleById.get(cnr.toLowerCase()) ?? null) : null\n return { enabled: p.enabled, repo, title, id: cnr ?? aux ?? dir }\n })\n}\n\n/** is this mirror row among the attributed packs, enabled? */\nexport const packIsInstalled = (\n packs: AttributedPack[],\n plugin: { title: string; files: string[]; reference: string },\n): boolean => {\n const repo = repoPath(plugin.files[0] ?? plugin.reference)\n return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title))\n}\n\nexport const buildPluginView = (p: {\n mirror: ManagerMirror\n installed: InstalledPacks\n mappings: PackMappings\n}): { list: ComfyManagerAPIPluginList; unattributed: string[] } => {\n const packs = attributePacks(p.installed, p.mappings)\n const plugins = [...p.mirror.plugins_byTitle.values()]\n const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)))\n const mirrorTitles = new Set<string>(plugins.map((x) => x.title))\n const joins = (x: AttributedPack): boolean =>\n (x.repo != null && mirrorRepos.has(x.repo)) || (x.title != null && mirrorTitles.has(x.title))\n // a git clone whose repo the mirror lacks is no mirror row; an enabled pack known by no repo that joins\n // nothing could be one (a disabled one reads `False` whichever row it is, like a missing one)\n const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x))\n const serverTitles = new Set(\n Object.values(p.mappings).flatMap((v) => (v[1].title_aux != null ? [v[1].title_aux] : [])),\n )\n const custom_nodes: ComfyManagerAPIPluginList['custom_nodes'] = []\n for (const plugin of plugins) {\n const repo = repoPath(plugin.files[0] ?? plugin.reference)\n const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title)\n if (joined.some((x) => x.enabled)) custom_nodes.push({ title: plugin.title, installed: 'True' })\n // an unattributed registry install can only be a row the server's mappings do not name\n else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue\n else custom_nodes.push({ title: plugin.title, installed: 'False' })\n }\n return { list: { chanel: 'default', custom_nodes }, unattributed: unattributed.map((x) => x.id) }\n}\n\n/** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */\nconst DEFAULT_FOLDER_BY_TYPE: Record<string, string> = {\n checkpoints: 'checkpoints',\n checkpoint: 'checkpoints',\n unclip: 'checkpoints',\n text_encoders: 'text_encoders',\n clip: 'text_encoders',\n vae: 'vae',\n lora: 'loras',\n 't2i-adapter': 'controlnet',\n 't2i-style': 'controlnet',\n controlnet: 'controlnet',\n clip_vision: 'clip_vision',\n gligen: 'gligen',\n upscale: 'upscale_models',\n embedding: 'embeddings',\n embeddings: 'embeddings',\n unet: 'diffusion_models',\n diffusion_model: 'diffusion_models',\n}\n\n/** what core `get_filename_list` lists in the standard folders */\nconst LISTED_EXTENSIONS = ['.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft']\n\n/**\n * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.\n * The Manager's own check accepts the folder root as well as the `save_path` sub folder.\n */\nexport const modelLocation = (m: ComfyManagerModelInfo): { folder: string; files: string[] } | null => {\n if (m.filename === '<huggingface>' || /[\\\\/:]/.test(m.filename)) return null\n if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null\n if (m.save_path === 'default') {\n const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()]\n return folder == null ? null : { folder, files: [m.filename] }\n }\n const parts = m.save_path\n .replaceAll('\\\\', '/')\n .split('/')\n .filter((s) => s !== '')\n const folder = parts[0]\n if (folder == null || folder === 'custom_nodes' || parts.includes('..')) return null\n const sub = [...parts.slice(1), m.filename].join('/')\n return { folder, files: sub === m.filename ? [m.filename] : [m.filename, sub] }\n}\n\nexport const buildModelView = (p: {\n models: readonly ComfyManagerModelInfo[]\n /** registered folder → its relative file paths, for the folders core lists */\n files: ReadonlyMap<string, readonly string[]>\n}): ComfyManagerAPIModelList => {\n const listed = new Map(\n [...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll('\\\\', '/')))]),\n )\n const statusOf = (m: ComfyManagerModelInfo): 'True' | 'False' | null => {\n const at = modelLocation(m)\n const files = at == null ? null : listed.get(at.folder)\n if (at == null || files == null) return null\n return at.files.some((f) => files.has(f)) ? 'True' : 'False'\n }\n const byName = new Map<string, ComfyManagerModelInfo[]>()\n for (const m of p.models) byName.set(m.name, [...(byName.get(m.name) ?? []), m])\n const models: ComfyManagerAPIModelList['models'] = []\n for (const rows of byName.values()) {\n // a name shipped twice with different files is decided only when every row agrees\n const statuses = new Set(rows.map(statusOf))\n const first = rows[0]\n const installed = statuses.size === 1 ? [...statuses][0] : null\n if (first == null || installed == null) continue\n models.push({\n name: first.name,\n installed,\n filename: first.filename,\n save_path: first.save_path,\n base: first.base,\n })\n }\n return { models }\n}\n\n/** the folders the views need listed */\nexport const modelFolders = (models: Iterable<ComfyManagerModelInfo>): Set<string> =>\n new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []))\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 'filename?': 'string',\n 'save_path?': 'string',\n 'base?': 'string',\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\n/** one pack as `GET customnode/getlist` serves it (Manager V3 and 4.x legacy UI); the install body is this row */\nexport type ComfyManagerAPIPack = typeof ComfyManagerAPIPack_ark.infer\nexport const ComfyManagerAPIPack_ark = type({\n title: type.string.as<KnownComfyPluginTitle>(),\n 'id?': 'string',\n 'files?': 'string[]',\n 'repository?': 'string',\n 'version?': 'string',\n 'state?': 'string',\n 'update-state?': 'string',\n})\n\n/** the getlist wire shape since Manager V3: packs keyed by their install key */\nexport type ComfyManagerAPIPackList = typeof ComfyManagerAPIPackList_ark.infer\nexport const ComfyManagerAPIPackList_ark = type({\n channel: 'string',\n node_packs: type.Record('string', ComfyManagerAPIPack_ark),\n})\n","/** 🔶 NAMING DISCLAIMER: I call a \"custom node package\" => \"PLUGIN\" */\n\nimport { type ArkErrors, type Type, type } from 'arktype'\nimport { nanoid } from 'nanoid'\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 {\n attributePacks,\n buildModelView,\n buildPluginView,\n type InstalledPacks,\n InstalledPacks_ark,\n type ManagerMirror,\n modelFolders,\n type PackMappings,\n PackMappings_ark,\n packIsInstalled,\n repoPath,\n} from 'src/manager/installedView.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 ComfyManagerAPIPackList,\n ComfyManagerAPIPackList_ark,\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, logSuccess } from 'src/utils/log.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport type { PluginInstallStatus } from 'src/host/Requirements.ts'\n\n/**\n * the three ComfyUI-Manager servers in the field (agent/architecture.md, Manager HTTP client):\n * `v3` the legacy custom node (bare routes), `v4-legacy-ui` the pip package under\n * `--enable-manager-legacy-ui` (/v2), `v4` the pip package with its default ui (/v2, no lists)\n */\nexport type ManagerGeneration = 'v3' | 'v4-legacy-ui' | 'v4'\nexport type ManagerApi = { generation: ManagerGeneration; version: string }\n\n/** install waits poll the queue; tests pass milliseconds */\nexport type ManagerTiming = { pollMs: number; installTimeoutMs: number }\nexport const MANAGER_TIMING: ManagerTiming = { pollMs: 1000, installTimeoutMs: 60 * 60_000 }\n\ntype ManagerRoute =\n | '/manager/version'\n | '/manager/reboot'\n | '/manager/terminal'\n | '/customnode/getlist'\n | '/externalmodel/getlist'\n | '/customnode/installed'\n | '/customnode/getmappings'\n | '/manager/queue/install'\n | '/manager/queue/batch'\n | '/manager/queue/task'\n | '/manager/queue/install_model'\n | '/manager/queue/start'\n | '/manager/queue/status'\n | '/manager/queue/history'\n\n/** what each generation does NOT serve (history means the `?ui_id=` form) */\nconst NOT_SERVED: Record<ManagerGeneration, ManagerRoute[]> = {\n v3: ['/manager/queue/batch', '/manager/queue/task', '/manager/queue/history'],\n 'v4-legacy-ui': ['/manager/queue/install', '/manager/queue/task', '/manager/queue/history', '/manager/terminal'],\n v4: [\n '/customnode/getlist',\n '/externalmodel/getlist',\n '/manager/queue/install',\n '/manager/queue/batch',\n '/manager/terminal',\n ],\n}\n\n/** everything that differs between generations beyond a route's spelling */\ntype ManagerStrategy = {\n fetchPlugins: (mode: ComfyManagerAPIFetchPolicy, skipUpdate: boolean) => Promise<ComfyManagerAPIPluginList>\n fetchModels: () => Promise<ComfyManagerAPIModelList>\n enqueuePlugin: (plugin: ComfyManagerPluginInfo, uiId: string) => Promise<void>\n /** wait until the queued task ran: resolves when it succeeded, throws with why when not */\n settle: (what: string, uiId: string, landed: () => Promise<boolean>) => Promise<void>\n}\n\nconst QueueStatus_ark = type({\n is_processing: 'boolean',\n 'pending_count?': 'number',\n 'total_count?': 'number',\n 'done_count?': 'number',\n})\nconst TaskHistory_ark = type({\n history: { 'status?': { status_str: 'string', 'messages?': 'string[]' }, 'result?': 'string' },\n})\nconst ModelFolders_ark = type('string[]')\n\nconst errorText = (e: unknown): string => (e instanceof Error ? e.message : String(e))\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 public timing: ManagerTiming = { ...MANAGER_TIMING },\n /** the mirror the lists are joined to; the registry by default */\n public mirror: () => ManagerMirror = () => comfyts.registry,\n ) {}\n\n get registry(): ComfyRegistry {\n return comfyts.registry\n }\n\n /** identifies install tasks of this client in the Manager queue (4.x requires one) */\n readonly clientId: string = `comfy-ts-${nanoid(8)}`\n\n // generation ------------------------------------------------------------------------\n private _api: Promise<ManagerApi> | null = null\n\n /** which Manager answers: probed once, remembered, forgotten on failure and on reboot */\n api = (): Promise<ManagerApi> => {\n if (this._api == null) {\n const probe = this.probeApi()\n this._api = probe\n probe.catch(() => {\n if (this._api === probe) this._api = null\n })\n }\n return this._api\n }\n\n private probeApi = async (): Promise<ManagerApi> => {\n const v4 = await this.host.fetch('/v2/manager/version')\n if (v4.ok) {\n const version = (await v4.text()).trim()\n const ui = await this.host.fetch('/v2/manager/is_legacy_manager_ui')\n if (!ui.ok) {\n logError(\n `ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`,\n )\n return { generation: 'v4', version }\n }\n const flag: unknown = await ui.json()\n const legacy =\n typeof flag === 'object' &&\n flag != null &&\n 'is_legacy_manager_ui' in flag &&\n flag.is_legacy_manager_ui === true\n return { generation: legacy ? 'v4-legacy-ui' : 'v4', version }\n }\n const v3 = await this.host.fetch('/manager/version')\n if (v3.ok) return { generation: 'v3', version: (await v3.text()).trim() }\n throw new Error(\n `🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} ` +\n `(GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`,\n )\n }\n\n /** the one place a Manager route gets its generation's spelling */\n private route = (api: ManagerApi, route: ManagerRoute, query: string = ''): string => {\n if (NOT_SERVED[api.generation].includes(route))\n throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`)\n return `${api.generation === 'v3' ? '' : '/v2'}${route}${query}`\n }\n\n /** the one place the generations differ beyond a route's spelling */\n private strategy = (api: ManagerApi): ManagerStrategy => {\n switch (api.generation) {\n case 'v3':\n return {\n fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),\n fetchModels: () => this.listedModels(api),\n enqueuePlugin: (plugin, uiId) =>\n this.enqueueListedPlugin(api, plugin, uiId, (body) =>\n this.post(this.route(api, '/manager/queue/install'), body),\n ),\n settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed),\n }\n case 'v4-legacy-ui':\n return {\n fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),\n fetchModels: () => this.listedModels(api),\n enqueuePlugin: (plugin, uiId) =>\n this.enqueueListedPlugin(api, plugin, uiId, async (body) => {\n const route = this.route(api, '/manager/queue/batch')\n const res = await this.post(route, { install: [body] })\n const failed = typeof res === 'object' && res != null && 'failed' in res ? res.failed : null\n if (Array.isArray(failed) && failed.length > 0)\n throw new Error(\n `POST ${route} refused ${JSON.stringify(failed)}: the batch reply carries ids only, ` +\n `the ComfyUI console says why (a 4.x security policy refusal is the usual one)`,\n )\n }),\n settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed),\n }\n case 'v4':\n return {\n fetchPlugins: () => this.installedPluginView(api),\n fetchModels: () => this.installedModelView(),\n enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),\n settle: (what, uiId) => this.settleByHistory(api, what, uiId),\n }\n }\n }\n\n // -----------\n configureLogging = async (mi: boolean): Promise<string> => {\n const api = await this.api()\n const route = this.route(api, '/manager/terminal', `?mode=${mi}`)\n const response = await this.host.fetch(route)\n const text = await response.text()\n if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`)\n return text\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, and a GET\n * there answers 404 while the process keeps running. Both verbs are tried so a pre-V3\n * Manager still reboots, and anything that is neither a disconnect nor a 404 throws with\n * what the host actually said. The process may come back with another Manager, so the\n * remembered generation is dropped.\n */\n restartComfyUI = async (): Promise<void> => {\n const api = await this.api()\n this._api = null\n const route = this.route(api, '/manager/reboot')\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(route, { 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 (${route}: ${refusals.join(', ')}) — ` +\n `ComfyUI-Manager ${api.version} is not there any more, or its reboot route moved again`,\n )\n }\n\n // LISTS ----------------------------------------------------------------------------\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 modelList: Maybe<ComfyManagerAPIModelList> = null\n\n /** what the host has of our model mirror; a model absent from the list reads `unknown` */\n fetchModels = async (): Promise<ComfyManagerAPIModelList> => {\n return this.strategy(await this.api()).fetchModels()\n }\n\n fetchLogs = (): Promise<any> => {\n return this.getJSON<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 /** queue the install, wait until the Manager ran it; true only once the model is verified installed */\n installModel = async (model: ComfyManagerModelInfo): Promise<boolean> => {\n this.modelsBeeingInstalled.add(model.name)\n try {\n return await this.runInstall(`model \"${model.name}\"`, {\n enqueue: async (api, uiId) => {\n const body = { ...model, ui_id: uiId, client_id: this.clientId }\n await this.post(this.route(api, '/manager/queue/install_model'), body)\n },\n landed: async (s) => {\n // the triple the Manager's own install whitelist matches on\n const row = (await s.fetchModels()).models.find(\n (x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base,\n )\n return row?.installed === 'True'\n },\n })\n } finally {\n this.modelsBeeingInstalled.delete(model.name)\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 /** the host's plugin list in the public `custom_nodes` shape, titled like our mirror; absent = `unknown` */\n fetchPlugins = async (\n /** @default: 'cache' */\n mode: ComfyManagerAPIFetchPolicy = 'cache',\n /** @default: true */\n skipUpdate: boolean = true,\n ): Promise<ComfyManagerAPIPluginList> => {\n return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate)\n }\n\n /** queue the install, wait until the Manager ran it; true only once the pack is verified installed */\n installPlugin = async (plugin: ComfyManagerPluginInfo): Promise<boolean> => {\n return this.runInstall(`plugin \"${plugin.title}\"`, {\n enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),\n landed: async (_s, api) => {\n const data = await this.installedData(api)\n return packIsInstalled(attributePacks(data.installed, data.mappings), plugin)\n },\n })\n }\n\n // LIST BUILDERS: one per source, picked by the strategy -------------------------------\n /** the Manager's own getlist (v3, v4 legacy ui), normalized */\n private listedPlugins = async (\n api: ManagerApi,\n mode: ComfyManagerAPIFetchPolicy,\n skipUpdate: boolean,\n ): Promise<ComfyManagerAPIPluginList> => {\n const raw = await this.fetchPluginWire(api, mode, skipUpdate)\n if (!('node_packs' in raw)) return raw\n const titleByRepo = new Map<string, KnownComfyPluginTitle>()\n for (const p of this.mirror().plugins_byTitle.values())\n for (const f of p.files) titleByRepo.set(repoPath(f), p.title)\n return {\n chanel: raw.channel,\n custom_nodes: Object.values(raw.node_packs).map((p) => {\n const repo = p.files?.[0]\n return {\n title: (repo != null ? titleByRepo.get(repoPath(repo)) : undefined) ?? p.title,\n installed: p.state !== 'enabled' ? 'False' : p['update-state'] === 'true' ? 'Update' : 'True',\n }\n }),\n }\n }\n\n private fetchPluginWire = async (\n api: ManagerApi,\n mode: ComfyManagerAPIFetchPolicy,\n skipUpdate: boolean,\n ): Promise<ComfyManagerAPIPackList | ComfyManagerAPIPluginList> => {\n const query = `?mode=${mode}${skipUpdate ? '&skip_update=true' : ''}`\n const json: unknown = await this.getJSON(this.route(api, '/customnode/getlist', query))\n if (typeof json === 'object' && json != null && 'custom_nodes' in json)\n return softValidate(ComfyManagerAPIPluginList_ark, json)\n return softValidate(ComfyManagerAPIPackList_ark, json)\n }\n\n private listedModels = async (api: ManagerApi): Promise<ComfyManagerAPIModelList> => {\n return this.getJSON(this.route(api, '/externalmodel/getlist', '?mode=cache'), ComfyManagerAPIModelList_ark)\n }\n\n /** what is installed, as the Manager scans it, joined through its own registry id mappings */\n private installedData = async (api: ManagerApi): Promise<{ installed: InstalledPacks; mappings: PackMappings }> => {\n const [installed, mappings] = await Promise.all([\n this.getValid(this.route(api, '/customnode/installed'), InstalledPacks_ark),\n this.getValid(this.route(api, '/customnode/getmappings', '?mode=cache'), PackMappings_ark),\n ])\n return { installed, mappings }\n }\n\n /** v4 serves no list: our mirror against what is installed */\n private installedPluginView = async (api: ManagerApi): Promise<ComfyManagerAPIPluginList> => {\n const view = buildPluginView({ mirror: this.mirror(), ...(await this.installedData(api)) })\n if (view.unattributed.length > 0)\n logError(\n `ComfyUI-Manager ${api.version} reports installed packs no mirror row can be tied to ` +\n `(${view.unattributed.join(', ')}): the mirror rows they could be read unknown`,\n )\n return view.list\n }\n\n /** v4 serves no model list: core ComfyUI's model folders against our mirror */\n private installedModelView = async (): Promise<ComfyManagerAPIModelList> => {\n const models = this.mirror().modelRows\n const registered = new Set(await this.getValid('/models', ModelFolders_ark))\n const folders = [...modelFolders(models)].filter((f) => registered.has(f))\n const lists = await Promise.all(\n folders.map(\n async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)] as const,\n ),\n )\n return buildModelView({ models, files: new Map(lists) })\n }\n\n // INSTALL FLOW: enqueue → start → settle -------------------------------------------\n /** v3 and v4 legacy ui: the Manager's own list row for the pack, sent like its own ui does */\n private enqueueListedPlugin = async (\n api: ManagerApi,\n plugin: ComfyManagerPluginInfo,\n uiId: string,\n send: (body: Record<string, unknown>) => Promise<unknown>,\n ): Promise<void> => {\n const url = plugin.files[0] ?? plugin.reference\n const list = await this.fetchPluginWire(api, 'cache', true)\n if (!('node_packs' in list))\n throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`)\n const found = Object.entries(list.node_packs).find(([, p]) =>\n (p.files ?? []).some((f) => repoPath(f) === repoPath(url)),\n )\n if (found == null)\n throw new Error(\n `${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`,\n )\n const [key, row] = found\n await send({\n ...row,\n id: row.id ?? key,\n channel: list.channel,\n mode: 'cache',\n ui_id: uiId,\n skip_post_install: false,\n })\n }\n\n /** v4: no list to take a row from, so the pack goes by repo name at nightly */\n private enqueuePluginTask = async (api: ManagerApi, plugin: ComfyManagerPluginInfo, uiId: string): Promise<void> => {\n const url = plugin.files[0] ?? plugin.reference\n const id = repoPath(url).split('/').pop() ?? url\n const params = {\n id,\n version: 'nightly',\n selected_version: 'nightly',\n repository: url,\n mode: 'cache',\n channel: 'default',\n }\n await this.post(this.route(api, '/manager/queue/task'), {\n ui_id: uiId,\n client_id: this.clientId,\n kind: 'install',\n params,\n })\n }\n\n /** v4: the task's own history entry says how it ended */\n private settleByHistory = async (api: ManagerApi, what: string, uiId: string): Promise<void> => {\n const route = this.route(api, '/manager/queue/history', `?ui_id=${encodeURIComponent(uiId)}`)\n const entry = await this.waitFor(what, async () => {\n const status = (await this.getValid(route, TaskHistory_ark)).history.status\n if (status == null) await this.restartIdleQueue(api)\n return status ?? null\n })\n if (entry.status_str === 'success' || entry.status_str === 'skip') return\n const messages = entry.messages ?? []\n // the 4.x worker answers a bare `failed` from its security gate only (4.2.2 and 4.4 source)\n const gate =\n messages.length === 1 && messages[0] === 'failed'\n ? ': refused by its security policy, which allows installs only with security_level normal or below ' +\n 'AND either ComfyUI listening on localhost or network_mode personal_cloud (the ComfyUI console names the rule)'\n : ''\n throw new Error(`the Manager reports ${entry.status_str}: ${messages.join(' | ')}${gate}`)\n }\n\n /**\n * a worker lingers a few seconds after a drain, then exits; a start in that window answers 201\n * \"already running\" and leaves the new task pending with no worker (seen live on 4.2.2, same loop\n * in V3 and 4.4). So an idle queue that still holds work is started again.\n */\n private restartIdleQueue = async (api: ManagerApi): Promise<'running' | 'restarted' | 'drained'> => {\n const status = await this.getValid(this.route(api, '/manager/queue/status'), QueueStatus_ark)\n if (status.is_processing) return 'running'\n const waiting = status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)\n if (waiting <= 0) return 'drained'\n await this.post(this.route(api, '/manager/queue/start'))\n return 'restarted'\n }\n\n /** v3, v4 legacy ui: no per item result over http, so wait for the drain and look at the end state */\n private settleByDrain = async (api: ManagerApi, what: string, landed: () => Promise<boolean>): Promise<void> => {\n await this.waitFor(what, async () => ((await this.restartIdleQueue(api)) === 'drained' ? true : null))\n if (!(await landed()))\n throw new Error(\n `the Manager queue drained but it is not installed; ComfyUI-Manager ${api.version} ` +\n `reports why only over its websocket (cm-queue-status) and in the ComfyUI console`,\n )\n }\n\n private runInstall = async (\n what: string,\n p: {\n enqueue: (api: ManagerApi, uiId: string) => Promise<void>\n /** the end state, read when the generation reports no per item result */\n landed: (s: ManagerStrategy, api: ManagerApi) => Promise<boolean>\n },\n ): Promise<boolean> => {\n try {\n const api = await this.api()\n const s = this.strategy(api)\n const uiId = nanoid()\n await p.enqueue(api, uiId)\n await this.post(this.route(api, '/manager/queue/start'))\n await s.settle(what, uiId, () => p.landed(s, api))\n logSuccess(`${what} installed`)\n return true\n } catch (exception) {\n logError(`${what}: install failed on ${this.host.getServerHostHTTP()}: ${errorText(exception)}`)\n return false\n }\n }\n\n /** poll until `check` gives a value, never past `timing.installTimeoutMs` */\n private waitFor = async <T>(what: string, check: () => Promise<T | null>): Promise<T> => {\n const deadline = Date.now() + this.timing.installTimeoutMs\n for (;;) {\n const value = await check()\n if (value != null) return value\n if (Date.now() >= deadline)\n throw new Error(\n `${what} still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`,\n )\n await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs))\n }\n }\n\n // --------------------------------------------------------------\n /** json POST (the Manager's csrf guard refuses simple form types); the reply json, or null when empty */\n private post = async (route: string, body?: unknown): Promise<unknown> => {\n const response = await this.host.fetch(route, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: body === undefined ? undefined : JSON.stringify(body),\n })\n const text = await response.text()\n if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim())\n if (text === '') return null\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n }\n\n private getJSON = async <OUT = unknown>(route: string, validator?: Type<OUT>): Promise<OUT> => {\n const response = await this.host.fetch(route)\n if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim())\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 /** a GET whose shape the decision depends on: a mismatch throws instead of lying */\n private getValid = async <OUT>(route: string, schema: (json: unknown) => OUT | ArkErrors): Promise<OUT> => {\n const res = schema(await this.getJSON(route))\n if (res instanceof type.errors) throw new Error(`GET ${route}: ${res.summary}`)\n return res\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 /** names this process already uploaded to this host: a LoadAudio or LoadVideo list is not\n * reloaded after an upload, so without it every run re-sent the same file */\n private uploaded = new Set<string>()\n\n /** upload an image (hash-named, deduped against the host's LoadImage list) */\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 name = await this.uploadInput({ blob: img.getAsBlob(), name: img.enumName, ...p, slot: 'LoadImage.image' })\n return name as ComfyImageName\n }\n\n /**\n * THE upload path: any file a loader node reads from the host's input folder. ComfyUI routes\n * audio and video through `/upload/image` too. `slot` is the loader input whose value list\n * says the file is already there (`LoadImage.image`, `LoadAudio.audio`, `LoadVideo.file`)\n */\n uploadInput = async (p: {\n blob: Blob\n /** the name the file should get on the host, hash-derived by callers so reruns dedupe */\n name: string\n slot: string\n type?: Maybe<'input' | 'temp' | 'output'>\n override?: Maybe<boolean>\n subfolder?: string\n }): Promise<string> => {\n const expectedFinalName = p.subfolder ? `${p.subfolder}/${p.name}` : p.name\n if (this.uploaded.has(expectedFinalName) || this.host.schema.stringValues(p.slot).includes(expectedFinalName)) {\n console.log(`[🌁] UPLOAD: 🩶 \"${expectedFinalName}\" already exists on current ComfyUI instance`)\n return expectedFinalName\n }\n\n const form = new FormData()\n form.set('image', p.blob, p.name)\n if (p.type) form.set('type', p.type)\n if (p.override ?? true) form.set('override', 'true')\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 console.log('[🌁] UPLOAD: ✅ got', result)\n if (result.name == null) throw new Error(`upload of '${p.name}' failed: the host answered no name`)\n\n const finalName = result.subfolder ? `${result.subfolder}/${result.name}` : result.name\n if (finalName !== expectedFinalName)\n console.warn(`[🌁] UPLOAD: ⚠️ expected \"${expectedFinalName}\" but got \"${finalName}\"`)\n\n // the image list IS a known union: patch it so the next LoadImage typechecks against it\n if (p.slot === 'LoadImage.image')\n this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName as ComfyImageName)\n this.uploaded.add(finalName)\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 /** the `ws` package only (a browser answers pings by itself and exposes none of these) */\n ping?(): void\n on?(event: 'pong', cb: () => void): void\n terminate?(): 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\nexport type 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 /** tests only: a fake socket instead of the ws package / browser WebSocket */\n transport?: WsTransport\n /** a host that vanishes (power loss, hard reboot) never sends a close frame, so the\n * socket would look open forever: every `heartbeatMs` it is pinged, and one without a\n * pong since the last ping is dropped, which starts the reconnect. Default 15s */\n heartbeatMs?: number\n /** pause before a reconnect. Default 2s */\n reconnectMs?: number\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 heartbeat: ReturnType<typeof setInterval> | null = null\n private permanentlyClosed: boolean = false\n\n private stopHeartbeat(): void {\n if (this.heartbeat != null) clearInterval(this.heartbeat)\n this.heartbeat = null\n }\n\n /** ping on a timer; no pong since the previous ping = the peer is gone, drop the socket */\n private startHeartbeat(ws: WsLike): void {\n this.stopHeartbeat()\n if (typeof ws.ping !== 'function' || typeof ws.on !== 'function') return\n let awaitingPong = false\n ws.on('pong', () => {\n awaitingPong = false\n })\n const ms = this.options.heartbeatMs ?? 15_000\n this.heartbeat = setInterval(() => {\n if (ws !== this.currentWS) return this.stopHeartbeat()\n if (awaitingPong) {\n this.addError(`no pong within ${ms}ms: the host is gone, dropping the socket to reconnect`)\n this.stopHeartbeat()\n if (typeof ws.terminate === 'function') ws.terminate()\n else ws.close()\n return\n }\n awaitingPong = true\n try {\n ws.ping?.()\n } catch (e) {\n this.addError(`ping failed: ${extractErrorMessage(e)}`)\n }\n }, ms)\n }\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.stopHeartbeat()\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 this.stopHeartbeat()\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 = this.options.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 this.startHeartbeat(ws)\n }\n\n ws.onclose = (event: WsCloseEvent): void => {\n if (ws !== this.currentWS) return\n this.isOpen = false\n this.stopHeartbeat()\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 const wait = this.options.reconnectMs ?? 2000\n this.addInfo(`⏱️ reconnecting in ${wait / 1000} seconds...`)\n this.reconnectTimeout = setTimeout(() => void this.connect(), wait)\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\n/** the loras a host lists that the local copy of its lora manager list does not know yet:\n * downloaded after the last sync, so they have no name, preview or trigger words here */\nexport function lorasMissingFromMirror(hostLoras: readonly string[], inMirror: (name: string) => boolean): string[] {\n return hostLoras.filter((n) => !inMirror(n))\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","// one lora's stored setting, read the same way by LorasVar, serve and the web panel. PURE and\n// dependency-free, so the browser bundle imports it without pulling ComfyVars in.\n// absent not in the palette\n// false off, not in the palette (what an untick in the TUI writes)\n// true | n on, both strengths 1 | n\n// [m, c] on, each strength\n// { strength: [m, c], off?: true, mute?: string[] }\n// the palette form: `off` pauses it without forgetting it or its strengths,\n// `mute` the parts of its prompt keyword (split at commas) left out of the\n// prompt. Grouping loras into lanes is the VAR's shape, src/vars/lanes.ts\n\nexport type LoraEntry = {\n strength: [strengthModel: number, strengthClip: number]\n off?: boolean\n mute?: string[]\n}\n\nexport type LoraStrength = boolean | number | [strengthModel: number, strengthClip: number] | LoraEntry\n\nexport function isLoraEntry(s: unknown): s is LoraEntry {\n if (typeof s !== 'object' || s == null || Array.isArray(s)) return false\n const o = s as Record<string, unknown>\n const st = o.strength\n return (\n Array.isArray(st) &&\n st.length === 2 &&\n typeof st[0] === 'number' &&\n Number.isFinite(st[0]) &&\n typeof st[1] === 'number' &&\n Number.isFinite(st[1]) &&\n (o.off == null || typeof o.off === 'boolean') &&\n (o.mute == null || (Array.isArray(o.mute) && o.mute.every((w) => typeof w === 'string')))\n )\n}\n\nexport function isLoraStrength(s: unknown): s is LoraStrength {\n if (typeof s === 'boolean') return true\n if (typeof s === 'number') return Number.isFinite(s)\n if (Array.isArray(s)) return s.length === 2 && s.every((n) => typeof n === 'number' && Number.isFinite(n))\n return isLoraEntry(s)\n}\n\n/** on = it runs */\nexport function loraIsOn(s: unknown): boolean {\n if (s == null || s === false) return false\n if (isLoraEntry(s)) return s.off !== true\n return true\n}\n\n/** in the palette = on, or paused in the palette form */\nexport function loraInPalette(s: unknown): boolean {\n return loraIsOn(s) || (isLoraEntry(s) && s.off === true)\n}\n\n/** the strengths, whatever the spelling (1/1 when there is nothing to read) */\nexport function loraStrengths(s: unknown): [number, number] {\n if (typeof s === 'number' && Number.isFinite(s)) return [s, s]\n if (Array.isArray(s) && typeof s[0] === 'number' && typeof s[1] === 'number') return [s[0], s[1]]\n if (isLoraEntry(s)) return [s.strength[0], s.strength[1]]\n return [1, 1]\n}\n\nexport function loraMuted(s: unknown): string[] {\n return isLoraEntry(s) && s.mute != null ? s.mute : []\n}\n\n/** a prompt keyword's parts, split at commas: each one can be left out on its own */\nexport function keywordParts(keyword: string): string[] {\n return [\n ...new Set(\n keyword\n .split(',')\n .map((w) => w.trim())\n .filter((w) => w !== ''),\n ),\n ]\n}\n\n/** the keyword a lora adds to the prompt once its muted parts are left out ('' = nothing) */\nexport function keptKeyword(keyword: string, muted: readonly string[]): string {\n return keywordParts(keyword)\n .filter((w) => !muted.includes(w))\n .join(', ')\n}\n\n/** rewrite one setting, keeping what the patch does not name. The result stays in the short\n * spellings while nothing needs the palette form, so a plain draft reads as it always did */\nexport function withLora(\n s: unknown,\n patch: { on?: boolean; strength?: [number, number]; mute?: readonly string[] },\n): LoraStrength {\n const strength = patch.strength ?? loraStrengths(s)\n const off = patch.on == null ? !loraIsOn(s) : !patch.on\n const mute = [...(patch.mute ?? loraMuted(s))]\n if (!off && mute.length === 0) return [strength[0], strength[1]]\n return {\n strength: [strength[0], strength[1]],\n ...(off ? { off: true } : {}),\n ...(mute.length === 0 ? {} : { mute }),\n }\n}\n","// lanes: the second value shape of a prompt or loras var. A var holds EITHER its plain value OR\n// `{ lanes: [...] }`; the build merges the active lanes in listed order. PURE and dependency-free\n// (the browser bundle imports it), every shape runtime-checked like loraEntry.ts.\nimport { isLoraStrength, loraIsOn, type LoraStrength } from 'src/vars/loraEntry.ts'\n\nexport type PromptLane = { name: string; prompt: string; active: boolean }\nexport type PromptLanes = { lanes: PromptLane[] }\nexport type PromptInput = string | PromptLanes\n\nexport type LoraRecord<T extends string = string> = Partial<Record<T, LoraStrength>>\nexport type LoraLane<T extends string = string> = { name: string; active: boolean; loras: LoraRecord<T> }\nexport type LoraLanes<T extends string = string> = { lanes: LoraLane<T>[] }\n/** a lora file is never named `lanes` (options end in .safetensors), so the plain record and the\n * lanes object can never be mistaken for each other */\nexport type LorasInput<T extends string = string> = LoraRecord<T> | LoraLanes<T>\n\nexport const FIRST_LANE = 'main'\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v != null && !Array.isArray(v)\n}\n\n// ---- prompt ----\n\nexport function isPromptLane(v: unknown): v is PromptLane {\n return isObject(v) && typeof v.name === 'string' && typeof v.prompt === 'string' && typeof v.active === 'boolean'\n}\n\nexport function isPromptLanes(v: unknown): v is PromptLanes {\n return isObject(v) && Array.isArray(v.lanes) && v.lanes.every(isPromptLane)\n}\n\nexport function isPromptInput(v: unknown): v is PromptInput {\n return typeof v === 'string' || isPromptLanes(v)\n}\n\n/** the text the build reads: the active lanes joined in order, one line break between them, so\n * `//` and `- ` lines keep working inside every lane */\nexport function promptText(v: PromptInput): string {\n if (typeof v === 'string') return v\n return v.lanes\n .filter((l) => l.active)\n .map((l) => l.prompt)\n .join('\\n')\n}\n\nexport function toPromptLanes(v: PromptInput): PromptLanes {\n return typeof v === 'string' ? { lanes: [{ name: FIRST_LANE, prompt: v, active: true }] } : v\n}\n\n/** back to one string: only when it loses nothing (a single active lane) */\nexport function promptFromLanes(v: PromptLanes): string | null {\n const only = v.lanes[0]\n return v.lanes.length === 1 && only != null && only.active ? only.prompt : null\n}\n\n// the TUI edits a prompt as text: lanes round-trip through header lines, so it never flattens\n// them. `# name` starts a lane, `# name (off)` an inactive one\nconst HEADER = /^# (.+?)( \\(off\\))?$/\n\nexport function promptLanesToText(v: PromptLanes): string {\n return v.lanes.map((l) => `# ${l.name}${l.active ? '' : ' (off)'}\\n${l.prompt}`).join('\\n')\n}\n\n/** text before the first header lands in a lane named FIRST_LANE, so no typed line is lost */\nexport function promptLanesFromText(text: string): PromptLanes {\n const lanes: PromptLane[] = []\n let current: PromptLane | null = null\n const body: string[] = []\n const close = (): void => {\n if (current != null) lanes.push({ ...current, prompt: body.join('\\n') })\n else if (body.some((l) => l.trim() !== ''))\n lanes.push({ name: FIRST_LANE, prompt: body.join('\\n'), active: true })\n body.length = 0\n }\n for (const line of text.split('\\n')) {\n const m = HEADER.exec(line)\n if (m == null) {\n body.push(line)\n continue\n }\n close()\n current = { name: (m[1] ?? '').trim(), prompt: '', active: m[2] == null }\n }\n close()\n return { lanes: lanes.length > 0 ? lanes : [{ name: FIRST_LANE, prompt: '', active: true }] }\n}\n\n// ---- loras ----\n\nfunction isLoraRecord(v: unknown): v is LoraRecord {\n return isObject(v) && !('lanes' in v) && Object.values(v).every((s) => s == null || isLoraStrength(s))\n}\n\nexport function isLoraLane(v: unknown): v is LoraLane {\n return isObject(v) && typeof v.name === 'string' && typeof v.active === 'boolean' && isLoraRecord(v.loras)\n}\n\nexport function isLoraLanes<T extends string>(v: LorasInput<T>): v is LoraLanes<T>\nexport function isLoraLanes(v: unknown): v is LoraLanes\nexport function isLoraLanes(v: unknown): v is LoraLanes {\n return isObject(v) && Array.isArray(v.lanes) && v.lanes.every(isLoraLane)\n}\n\nexport function isLorasInput(v: unknown): v is LorasInput {\n return isLoraRecord(v) || isLoraLanes(v)\n}\n\n/** one record for the build: the active lanes in order. A lora in two active lanes keeps its\n * FIRST setting, and `duplicates` names it so the caller can say so */\nexport function flattenLoras<T extends string>(v: LorasInput<T>): { record: LoraRecord<T>; duplicates: T[] } {\n if (!isLoraLanes(v)) return { record: v, duplicates: [] }\n const record: LoraRecord<T> = {}\n const duplicates: T[] = []\n for (const lane of v.lanes) {\n if (!lane.active) continue\n for (const [name, st] of Object.entries(lane.loras) as [T, LoraStrength | undefined][]) {\n if (st == null) continue\n if (name in record) duplicates.push(name)\n else record[name] = st\n }\n }\n return { record, duplicates }\n}\n\nexport function toLoraLanes<T extends string>(v: LorasInput<T>): LoraLanes<T> {\n return isLoraLanes(v) ? v : { lanes: [{ name: FIRST_LANE, active: true, loras: v }] }\n}\n\nexport function lorasFromLanes<T extends string>(v: LoraLanes<T>): LoraRecord<T> | null {\n const only = v.lanes[0]\n return v.lanes.length === 1 && only != null && only.active ? only.loras : null\n}\n\n/** where a lora lives, so an edit lands in the lane that holds it: the first ACTIVE lane that\n * has it (the one the build reads), else any lane, else -1 */\nexport function laneIndexOf<T extends string>(v: LoraLanes<T>, name: T): number {\n const active = v.lanes.findIndex((l) => l.active && l.loras[name] != null)\n return active !== -1 ? active : v.lanes.findIndex((l) => l.loras[name] != null)\n}\n\n/** rewrite one lora's setting wherever it lives (plain record, or its lane). `null` removes it.\n * A lora in no lane yet lands in the first lane */\nexport function updateLora<T extends string>(v: LorasInput<T>, name: T, next: LoraStrength | null): LorasInput<T> {\n const write = (rec: LoraRecord<T>): LoraRecord<T> => {\n const out = { ...rec }\n if (next == null) delete out[name]\n else out[name] = next\n return out\n }\n if (!isLoraLanes(v)) return write(v)\n if (v.lanes.length === 0) return { lanes: [{ name: FIRST_LANE, active: true, loras: write({}) }] }\n const found = laneIndexOf(v, name)\n const ix = found === -1 ? 0 : found\n return { lanes: v.lanes.map((l, i) => (i === ix ? { ...l, loras: write(l.loras) } : l)) }\n}\n\n// ---- lane list edits, the same for prompt and lora lanes ----\n\ntype NamedLane = { name: string; active: boolean }\n\n/** a name no other lane has: `lane 2`, `lane 3`… */\nexport function newLaneName(lanes: readonly NamedLane[]): string {\n const taken = new Set(lanes.map((l) => l.name))\n let n = lanes.length + 1\n while (taken.has(`lane ${n}`)) n++\n return `lane ${n}`\n}\n\nexport function patchLane<L extends NamedLane>(lanes: readonly L[], ix: number, patch: Partial<L>): L[] {\n return lanes.map((l, i) => (i === ix ? { ...l, ...patch } : l))\n}\n\n/** move a lane up (-1) or down (+1); out of range changes nothing */\nexport function moveLane<L>(lanes: readonly L[], ix: number, delta: number): L[] {\n const to = ix + delta\n if (ix < 0 || ix >= lanes.length || to < 0 || to >= lanes.length) return [...lanes]\n const out = [...lanes]\n const [moved] = out.splice(ix, 1)\n if (moved != null) out.splice(to, 0, moved)\n return out\n}\n\nexport function removeLane<L>(lanes: readonly L[], ix: number): L[] {\n return lanes.filter((_, i) => i !== ix)\n}\n\n/** move one lora to another lane (or another slot of its own), before `beforeName` or last */\nexport function moveLoraToLane<T extends string>(\n v: LoraLanes<T>,\n p: { from: number; name: T; to: number; beforeName?: T },\n): LoraLanes<T> {\n const src = v.lanes[p.from]\n const setting = src?.loras[p.name]\n if (src == null || setting == null || v.lanes[p.to] == null) return v\n const lanes = v.lanes.map((l) => ({ ...l, loras: { ...l.loras } }))\n const from = lanes[p.from]\n const to = lanes[p.to]\n if (from == null || to == null) return v\n delete from.loras[p.name]\n const out: LoraRecord<T> = {}\n let placed = false\n for (const [k, st] of Object.entries(to.loras) as [T, LoraStrength | undefined][]) {\n if (k === p.beforeName && !placed) {\n out[p.name] = setting\n placed = true\n }\n out[k] = st\n }\n if (!placed) out[p.name] = setting\n to.loras = out\n return { lanes }\n}\n\n/** one lora's stored setting wherever it lives, inactive lanes included (the lane an edit\n * would write to, `updateLora`), or undefined */\nexport function loraSetting<T extends string>(v: LorasInput<T>, name: T): LoraStrength | undefined {\n if (!isLoraLanes(v)) return v[name]\n return v.lanes[laneIndexOf(v, name)]?.loras[name]\n}\n\n/** every lora in the palette of either shape, each once, with whether the build runs it: a lora\n * in an inactive lane, or paused, is there but not running */\nexport function paletteLoras<T extends string>(\n v: LorasInput<T>,\n): { name: T; setting: LoraStrength; running: boolean }[] {\n const out = new Map<T, { name: T; setting: LoraStrength; running: boolean }>()\n const lanes = isLoraLanes(v) ? v.lanes : [{ name: '', active: true, loras: v }]\n for (const lane of lanes)\n for (const [name, setting] of Object.entries(lane.loras) as [T, LoraStrength | undefined][]) {\n if (setting == null || setting === false) continue\n const running = lane.active && loraIsOn(setting)\n const seen = out.get(name)\n // a running copy wins over a stopped one, as it does in the build\n if (seen == null || (!seen.running && running)) out.set(name, { name, setting, running })\n }\n return [...out.values()]\n}\n","// prompt text rules shared by the build (PromptVar.outValue) and the web editor, so the editor's\n// colors can never disagree with what a run sends. PURE and import-free: the browser bundle takes it\n\n/** a whole line that is a comment (the TUI colors these) */\nexport const COMMENT_LINE_RE = /^\\s*\\/\\//\n/** a negative prompt line: `- ` then its text */\nexport const NEGATIVE_LINE_RE = /^\\s*- (.*)$/\nconst NEGATIVE_PREFIX_RE = /^(\\s*)- /\n\n/** where a `//` comment starts on this line, -1 when none. Only at line start or after\n * whitespace, so `http://host` is never cut */\nexport function commentStart(line: string): number {\n const m = /(?:^|\\s)\\/\\//.exec(line)\n if (m == null) return -1\n return m.index + m[0].length - 2\n}\n\n/** the line without its comment, trailing whitespace dropped with it */\nfunction withoutComment(line: string): { text: string; hadComment: boolean } {\n const c = commentStart(line)\n return c < 0 ? { text: line, hadComment: false } : { text: line.slice(0, c).trimEnd(), hadComment: true }\n}\n\n/** the build's reading of a prompt: comments out, `- ` lines comma-joined into the negative */\nexport function parsePromptText(text: string): { positive: string; negative: string } {\n const pos: string[] = []\n const neg: string[] = []\n for (const raw of text.split('\\n')) {\n const cut = withoutComment(raw)\n if (cut.hadComment && cut.text.trim() === '') continue\n const m = NEGATIVE_PREFIX_RE.exec(raw)\n if (m != null && m[0].length <= cut.text.length + 1) {\n const body = cut.text.slice(m[0].length).trim()\n if (body !== '') neg.push(body)\n } else pos.push(cut.text)\n }\n return { positive: pos.join('\\n').trim(), negative: neg.join(', ') }\n}\n\n// #region lines ---------------------------------------------------------------\n\ntype Line = { from: number; text: string }\n\nfunction linesOf(text: string): Line[] {\n const out: Line[] = []\n let from = 0\n for (const t of text.split('\\n')) {\n out.push({ from, text: t })\n from += t.length + 1\n }\n return out\n}\n\n// #region weights --------------------------------------------------------------\n\n/** one `(text:1.2)` group on a line, offsets local to that line */\nexport type WeightGroup = {\n from: number\n to: number\n innerFrom: number\n innerTo: number\n numFrom: number\n numTo: number\n weight: number\n}\n\n/** ComfyUI weight groups, innermost only (no nested parens inside), `\\(` `\\)` skipped as literal */\nexport function findWeights(line: string): WeightGroup[] {\n const out: WeightGroup[] = []\n const re = /(?<!\\\\)\\(((?:\\\\[()]|[^()])*?):\\s*(-?\\d*\\.?\\d+)\\s*(?<!\\\\)\\)/g\n for (let m = re.exec(line); m != null; m = re.exec(line)) {\n const inner = m[1] ?? ''\n const num = m[2] ?? '1'\n const from = m.index\n const to = from + m[0].length\n const numFrom = from + m[0].lastIndexOf(num)\n out.push({\n from,\n to,\n innerFrom: from + 1,\n innerTo: from + 1 + inner.length,\n numFrom,\n numTo: numFrom + num.length,\n weight: Number(num),\n })\n }\n return out\n}\n\nconst round2 = (n: number): number => Math.round(n * 100) / 100\nexport const formatWeight = (w: number): string => String(round2(w))\n\nexport type TextChange = { from: number; to: number; insert: string }\nexport type EditResult = { changes: TextChange[]; selection: { anchor: number; head: number } }\n\n/** the comma-separated chunk around `col`, trimmed, never reaching into a comment */\nfunction tagAround(line: string, col: number): { from: number; to: number } | null {\n const c = commentStart(line)\n const end = c < 0 ? line.length : c\n if (col > end) return null\n let from = col\n while (from > 0 && line[from - 1] !== ',') from--\n let to = col\n while (to < end && line[to] !== ',') to++\n const neg = NEGATIVE_PREFIX_RE.exec(line)\n if (neg != null && from < neg[0].length) from = neg[0].length\n while (from < to && /\\s/.test(line[from] ?? '')) from++\n while (to > from && /\\s/.test(line[to - 1] ?? '')) to--\n return from < to ? { from, to } : null\n}\n\n/** weight ± delta on the selection, or on the tag under the cursor when nothing is selected.\n * Inside a group its number moves, and reaching 1 unwraps it; plain text gets wrapped. null when\n * there is nothing to weigh (an empty chunk, a comment, a selection over several lines) */\nexport function adjustWeight(text: string, from: number, to: number, delta: number): EditResult | null {\n const line = linesOf(text).find((l) => from >= l.from && from <= l.from + l.text.length)\n if (line == null || to > line.from + line.text.length) return null\n const f = from - line.from\n const t = to - line.from\n const c = commentStart(line.text)\n if (c >= 0 && f >= c) return null\n const enclosing = findWeights(line.text)\n .filter((g) => f >= g.from && t <= g.to)\n .sort((a, b) => a.to - a.from - (b.to - b.from))[0]\n if (enclosing != null) {\n const w = round2(enclosing.weight + delta)\n const inner = line.text.slice(enclosing.innerFrom, enclosing.innerTo)\n if (w === 1) {\n const at = line.from + enclosing.from\n return {\n changes: [{ from: at, to: line.from + enclosing.to, insert: inner }],\n selection: { anchor: at, head: at + inner.length },\n }\n }\n return {\n changes: [{ from: line.from + enclosing.numFrom, to: line.from + enclosing.numTo, insert: formatWeight(w) }],\n selection: { anchor: line.from + enclosing.innerFrom, head: line.from + enclosing.innerTo },\n }\n }\n let span: { from: number; to: number } | null\n if (f === t) span = tagAround(line.text, f)\n else {\n let a = f\n let b = t\n while (a < b && /\\s/.test(line.text[a] ?? '')) a++\n while (b > a && /\\s/.test(line.text[b - 1] ?? '')) b--\n span = a < b ? { from: a, to: b } : null\n }\n if (span == null) return null\n const w = round2(1 + delta)\n const at = line.from + span.from\n const end = line.from + span.to\n return {\n changes: [\n { from: at, to: at, insert: '(' },\n { from: end, to: end, insert: `:${formatWeight(w)})` },\n ],\n selection: { anchor: at + 1, head: end + 1 },\n }\n}\n\n// #region line toggles -------------------------------------------------------\n\n/** the lines a selection touches; a selection ending at column 0 leaves that last line out */\nfunction touchedLines(text: string, from: number, to: number): Line[] {\n const all = linesOf(text)\n const endAt = to > from && all.some((l) => l.from === to) ? to - 1 : to\n return all.filter((l) => l.from + l.text.length >= from && l.from <= endAt)\n}\n\n/** ⌘/ — comment the touched lines, or uncomment them when every non-empty one already is */\nexport function toggleComment(text: string, from: number, to: number): TextChange[] {\n const lines = touchedLines(text, from, to).filter((l) => l.text.trim() !== '')\n if (lines.length === 0) return []\n if (lines.every((l) => COMMENT_LINE_RE.test(l.text)))\n return lines.map((l) => {\n const at = l.text.indexOf('//')\n const len = l.text[at + 2] === ' ' ? 3 : 2\n return { from: l.from + at, to: l.from + at + len, insert: '' }\n })\n return lines\n .filter((l) => !COMMENT_LINE_RE.test(l.text))\n .map((l) => {\n const at = l.from + (/^\\s*/.exec(l.text)?.[0].length ?? 0)\n return { from: at, to: at, insert: '// ' }\n })\n}\n\n/** ⌘⇧- — move the touched lines into the negative prompt, or back out when all already are.\n * Comment lines are left alone */\nexport function toggleNegative(text: string, from: number, to: number): TextChange[] {\n const lines = touchedLines(text, from, to).filter((l) => l.text.trim() !== '' && !COMMENT_LINE_RE.test(l.text))\n if (lines.length === 0) return []\n if (lines.every((l) => NEGATIVE_PREFIX_RE.test(l.text)))\n return lines.map((l) => {\n const indent = NEGATIVE_PREFIX_RE.exec(l.text)?.[1]?.length ?? 0\n return { from: l.from + indent, to: l.from + indent + 2, insert: '' }\n })\n return lines\n .filter((l) => !NEGATIVE_PREFIX_RE.test(l.text))\n .map((l) => {\n const at = l.from + (/^\\s*/.exec(l.text)?.[0].length ?? 0)\n return { from: at, to: at, insert: '- ' }\n })\n}\n\n// #region highlighting -------------------------------------------------------\n\nexport type PromptMarkKind = 'comment' | 'negative' | 'negative-dash' | 'weight-paren' | 'weight-num'\nexport type PromptMark = { from: number; to: number; kind: PromptMarkKind }\n\n/** what the editor colors, in document order */\nexport function promptMarks(text: string): PromptMark[] {\n const out: PromptMark[] = []\n for (const l of linesOf(text)) {\n const c = commentStart(l.text)\n const end = c < 0 ? l.text.length : c\n const neg = NEGATIVE_PREFIX_RE.exec(l.text)\n if (neg != null && neg[0].length <= end + 1) {\n const dash = l.from + neg[0].length - 2\n out.push({ from: dash, to: dash + 1, kind: 'negative-dash' })\n if (l.from + neg[0].length < l.from + end)\n out.push({ from: l.from + neg[0].length, to: l.from + end, kind: 'negative' })\n }\n for (const g of findWeights(l.text.slice(0, end))) {\n out.push({ from: l.from + g.from, to: l.from + g.innerFrom, kind: 'weight-paren' })\n out.push({ from: l.from + g.innerTo, to: l.from + g.numFrom, kind: 'weight-paren' })\n out.push({ from: l.from + g.numFrom, to: l.from + g.numTo, kind: 'weight-num' })\n out.push({ from: l.from + g.numTo, to: l.from + g.to, kind: 'weight-paren' })\n }\n if (c >= 0) out.push({ from: l.from + c, to: l.from + l.text.length, kind: 'comment' })\n }\n return out.sort((a, b) => a.from - b.from || a.to - b.to)\n}\n\n// #region tag issues ---------------------------------------------------------\n\n/** the form two tags are compared in: weight wrapper off, literal parens unescaped, lowercase,\n * underscores as spaces */\nexport function normalizeTag(chunk: string): string {\n let s = chunk.trim()\n const whole = findWeights(s)[0]\n if (whole != null && whole.from === 0 && whole.to === s.length) s = s.slice(whole.innerFrom, whole.innerTo)\n return s\n .replace(/\\\\([()])/g, '$1')\n .toLowerCase()\n .replace(/_/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\nexport type TagIssue = { from: number; to: number; message: string }\n\ntype Chunk = { from: number; to: number; tag: string }\n\nfunction chunksOf(line: string, offset: number, start: number): Chunk[] {\n const out: Chunk[] = []\n let from = start\n for (let i = start; i <= line.length; i++) {\n if (i < line.length && line[i] !== ',') continue\n const raw = line.slice(from, i)\n const lead = raw.length - raw.trimStart().length\n const tag = normalizeTag(raw)\n if (tag !== '') out.push({ from: offset + from + lead, to: offset + from + raw.trimEnd().length, tag })\n from = i + 1\n }\n return out\n}\n\n/** a tag written twice, a tag a lora already adds, a tag in both prompts, and every weight when\n * the model ignores weights. Each issue carries the sentence the editor shows on hover */\nexport function tagIssues(\n text: string,\n p: { injected?: readonly { tag: string; source: string }[]; weights?: boolean } = {},\n): TagIssue[] {\n const out: TagIssue[] = []\n const positive: Chunk[] = []\n const negative: Chunk[] = []\n for (const l of linesOf(text)) {\n if (COMMENT_LINE_RE.test(l.text)) continue\n const body = withoutComment(l.text).text\n const neg = NEGATIVE_PREFIX_RE.exec(l.text)\n const isNeg = neg != null && neg[0].length <= body.length + 1\n const chunks = chunksOf(body, l.from, isNeg ? neg[0].length : 0)\n ;(isNeg ? negative : positive).push(...chunks)\n if (p.weights === false)\n for (const g of findWeights(body))\n out.push({\n from: l.from + g.from,\n to: l.from + g.to,\n message: 'this model ignores weights: the text inside is read, the number is not',\n })\n }\n const injected = new Map<string, string>()\n for (const i of p.injected ?? []) {\n const tag = normalizeTag(i.tag)\n if (tag !== '' && !injected.has(tag)) injected.set(tag, i.source)\n }\n const scan = (side: Chunk[], sideName: string): void => {\n const seen = new Set<string>()\n for (const ch of side) {\n if (seen.has(ch.tag))\n out.push({ from: ch.from, to: ch.to, message: `'${ch.tag}' is already in the ${sideName}` })\n seen.add(ch.tag)\n }\n }\n scan(positive, 'prompt')\n scan(negative, 'negative prompt')\n const negTags = new Set(negative.map((c) => c.tag))\n for (const ch of positive) {\n const source = injected.get(ch.tag)\n if (source != null)\n out.push({ from: ch.from, to: ch.to, message: `'${ch.tag}' is already added by the lora ${source}` })\n if (negTags.has(ch.tag))\n out.push({ from: ch.from, to: ch.to, message: `'${ch.tag}' is also in the negative prompt` })\n }\n return out.sort((a, b) => a.from - b.from)\n}\n\n// #region token estimate ------------------------------------------------------\n\n/** a rough CLIP token count of what the build sends as positive: one per short word, long words\n * split, one per punctuation mark. An ESTIMATE, the editor shows it with ≈ */\nexport function estimateTokens(text: string): number {\n const body = parsePromptText(text).positive\n let n = 0\n for (const m of body.matchAll(/\\p{L}+|\\p{N}|[^\\s\\p{L}\\p{N}]/gu)) {\n const w = m[0]\n n += /^\\p{L}/u.test(w) && w.length > 8 ? Math.ceil(w.length / 5) : 1\n }\n return n\n}\n\n// #region completion ------------------------------------------------------------\n\n/** the partial tag being typed at `col`: from the last `,` `(` or line start, leading spaces\n * and a negative `- ` skipped. null inside a comment */\nexport function completionWord(line: string, col: number): { from: number; text: string } | null {\n const c = commentStart(line)\n if (c >= 0 && col > c) return null\n let from = col\n while (from > 0 && !/[,(]/.test(line[from - 1] ?? '')) from--\n const neg = NEGATIVE_PREFIX_RE.exec(line)\n if (neg != null && from < neg[0].length) from = neg[0].length\n while (from < col && /\\s/.test(line[from] ?? '')) from++\n return { from, text: line.slice(from, col) }\n}\n\n/** what to search for at `col`: the whole chunk first, then its last words, longest first, so a\n * tag typed after prose or another tag with no comma between (`a girl with long ha`) still\n * completes. At most the last four word starts, an empty tail never */\nexport function completionCandidates(line: string, col: number): { from: number; text: string }[] {\n const word = completionWord(line, col)\n if (word == null) return []\n const out = [word]\n const starts: number[] = []\n for (let i = word.from + 1; i < col; i++)\n if (/\\s/.test(line[i - 1] ?? '') && !/\\s/.test(line[i] ?? '')) starts.push(i)\n for (const from of starts.slice(-4)) out.push({ from, text: line.slice(from, col) })\n return out\n}\n\nexport type TagFormat = { underscores?: boolean; weights?: boolean; artistPrefix?: string }\n\n/** a tag list name as the prompt wants it. Underscores between letters become spaces (`>_<`\n * keeps its own), parens get escaped where ComfyUI would read them as emphasis */\nexport function formatTag(name: string, category: number | null, p: TagFormat): string {\n let s = p.underscores === true ? name : name.replace(/(?<=[\\p{L}\\p{N})])_(?=[\\p{L}\\p{N}(])/gu, ' ')\n if (p.weights !== false) s = s.replace(/(?<!\\\\)([()])/g, '\\\\$1')\n if (category === TAG_CATEGORY_ARTIST && p.artistPrefix != null) s = `${p.artistPrefix}${s}`\n return s\n}\n\n/** danbooru categories as the a1111 tagcomplete csv numbers them */\nexport const TAG_CATEGORY_ARTIST = 1\nexport const TAG_CATEGORY_NAMES: Record<number, string> = {\n 0: 'general',\n 1: 'artist',\n 3: 'copyright',\n 4: 'character',\n 5: 'meta',\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 {\n flattenLoras,\n isLorasInput,\n isPromptLanes,\n promptLanesFromText,\n promptLanesToText,\n promptText,\n updateLora,\n type LoraRecord,\n type LorasInput,\n type PromptInput,\n} from 'src/vars/lanes.ts'\nimport { keptKeyword, loraIsOn, loraMuted, loraStrengths, withLora, type LoraStrength } from 'src/vars/loraEntry.ts'\nimport { logError } from 'src/utils/log.ts'\nimport { COMMENT_LINE_RE, NEGATIVE_LINE_RE, parsePromptText } from 'src/vars/promptSyntax.ts'\nimport { toPresetList, type VarPreset, type VarPresetSpec } from 'src/vars/presets.ts'\nimport { DEFAULT_MEDIA_EXTENSIONS, extensionOf, mediaMime, type MediaKind } from 'src/runner/mediaKinds.ts'\nimport { hashArrayBuffer } from 'src/utils/hashArrayBuffer.ts'\nimport { statelessRegex } from 'src/utils/matchesRegex.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport type { NodeOf } from 'src/types/comfy-sdk.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' | MediaKind\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 */\n/** how a var LOOKS in the panel, set by the workflow: `v.int(8).ui({ icon, color, description })`.\n * Every slot is optional, a color is any css color */\nexport type VarUi = {\n /** shown as a (?) after the label, the text is its tooltip */\n description?: string\n /** a 24×24 svg path drawn in the icon color, or a whole `<svg …>` string */\n icon?: string\n /** the icon's color */\n color?: string\n labelColor?: string\n /** the whole row, drawn without moving anything in it */\n background?: string\n /** vars that go together: consecutive vars with the same group share one tinted block */\n group?: string\n /** the block's tint, read from the first var of the group that sets it */\n groupColor?: string\n border?: string\n /** choice vars: a look per option, keyed by the option value. The lit option is filled\n * with its own color */\n options?: Record<string, { icon?: string; color?: string }>\n /** the field is shown but disabled unless every named var holds one of the listed values:\n * `{ model: ['aesthetic', 'base'] }`. Checked against the var names when the workflow loads.\n * Display only: a disabled var's value still reaches the build */\n activeWhen?: Record<string, readonly (string | number | boolean)[]>\n}\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 /** panel looks, see VarUi. Never part of the value, never in a draft */\n uiOpts: VarUi = {}\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 /** chainable: `v.choice([...], 'a').ui({ icon: 'M4 12h16', color: '#e0af68' })` */\n ui(p: VarUi): this {\n this.uiOpts = { ...this.uiOpts, ...p }\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\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 = {\n activeNames(): string[]\n hostId?: string\n /** the parts of a lora's keyword left out of the prompt (LorasVar: the `mute` list) */\n mutedWords?(name: string): string[]\n}\n\n/** where a prompt's tag completion comes from (the serve web editor). The list is never shipped:\n * `url` is a local path (relative to the workflow file, `~/`, `file://`) or an http(s) url */\nexport type PromptTagsOpts = {\n url: string\n /** insert `long_hair` as written in the list; default inserts `long hair` */\n underscores?: boolean\n /** put in front of an artist tag on insert (Anima: `@`) */\n artistPrefix?: string\n}\n\nexport type PromptVarOpts = {\n label?: string\n loraKeywordsFrom?: ActiveLoraSource\n presets?: VarPresetSpec\n /** booru tag completion for this prompt: a tag list url, or the url with its insert rules */\n tags?: string | PromptTagsOpts\n /** false when the model's encoder ignores `(text:1.2)`: the editor then flags every weight */\n weights?: boolean\n}\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 * - `//` starts a COMMENT to the end of the line (src/vars/promptSyntax.ts) — 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<PromptInput, 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: PromptInput,\n public promptOpts: PromptVarOpts = {},\n ) {\n super(defaultValue, promptOpts.label)\n this.presets = toPresetList(promptOpts.presets)\n }\n /** in lanes mode the text carries `# name` headers, so a lane survives a round trip */\n parse(raw: string): boolean {\n this.set(isPromptLanes(this.value) ? promptLanesFromText(raw) : raw)\n return true\n }\n override toEditBuffer(): string {\n return isPromptLanes(this.value) ? promptLanesToText(this.value) : this.value\n }\n /** a var list shows the lanes by name, the inactive ones in parentheses */\n override display(): string {\n if (!isPromptLanes(this.value)) return super.display()\n return `${this.value.lanes.length} lanes: ${this.value.lanes.map((l) => (l.active ? l.name : `(${l.name})`)).join(', ')}`\n }\n /** the text the build reads: the plain string, or the active lanes joined in order */\n get text(): string {\n return promptText(this.value)\n }\n /** the tag list options in their one object form, null when this prompt has no completion */\n get tags(): PromptTagsOpts | null {\n const t = this.promptOpts.tags\n if (t == null) return null\n return typeof t === 'string' ? { url: t } : t\n }\n static isCommentLine(line: string): boolean {\n return COMMENT_LINE_RE.test(line)\n }\n static isNegativeLine(line: string): boolean {\n return NEGATIVE_LINE_RE.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) => keptKeyword(getLoraKeyword(name, src.hostId), src.mutedWords?.(name) ?? []))\n .filter((k) => k !== ''),\n ),\n ]\n }\n outValue(): PromptValue {\n const parsed = parsePromptText(this.text)\n const body = parsed.positive\n const keywords = this.injectedKeywords()\n const positive =\n keywords.length === 0 ? body : body === '' ? keywords.join(', ') : `${keywords.join(', ')}, ${body}`\n return { positive, negative: parsed.negative }\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\n/** how many options a choice holds: exactly one (the default), one or none, or any number */\nexport type ChoiceSelect = 'one' | 'zero-or-one' | 'many'\n\n/** where a host-bound choice reads its options: one loader input of the host's live schema,\n * optionally narrowed (`v.model`) */\nexport type HostSlotSource = { slot: string; filter?: RegExp }\n\n/** a fixed list, or the host's list for one slot once bindHost ran */\nclass ChoiceList<T extends string> {\n private resolved: readonly T[] | null = null\n constructor(readonly source: readonly T[] | HostSlotSource) {}\n get slot(): HostSlotSource | null {\n return isChoiceList(this.source) ? null : this.source\n }\n get choices(): readonly T[] {\n if (isChoiceList(this.source)) return this.source\n if (this.resolved == null)\n throw new Error(\n `v.model('${this.source.slot}') is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list to v.choice otherwise)`,\n )\n return this.resolved\n }\n /** cast: whitelist family 1 (agent/coding.md) — stringValues() returns the runtime values of\n * the SAME object_info enum the generated slot union comes from */\n bind(host: LorasHost): void {\n const src = this.slot\n if (src == null) return\n const all = host.schema.stringValues(src.slot)\n const filter = src.filter == null ? null : statelessRegex(src.filter)\n this.resolved = (filter == null ? all : all.filter((n) => filter.test(n))) as T[]\n }\n}\n\nexport class ChoiceVar<T extends string> extends ComfyVar<T> {\n readonly kind = 'choice' as const\n readonly select = 'one' as const\n private list: ChoiceList<T>\n constructor(choices: readonly T[] | HostSlotSource, defaultValue: T, label?: string) {\n super(defaultValue, label)\n this.list = new ChoiceList(choices)\n }\n get choices(): readonly T[] {\n return this.list.choices\n }\n /** set for `v.model`: the loader input this choice lists */\n get hostSlot(): HostSlotSource | null {\n return this.list.slot\n }\n bindHost(host: LorasHost): void {\n this.list.bind(host)\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/** one option or none: `null` is \"nothing picked\", clicking the lit option clears it */\nexport class OptionalChoiceVar<T extends string> extends ComfyVar<T | null> {\n readonly kind = 'choice' as const\n readonly select = 'zero-or-one' as const\n private list: ChoiceList<T>\n constructor(choices: readonly T[] | HostSlotSource, defaultValue: T | null, label?: string) {\n super(defaultValue, label)\n this.list = new ChoiceList(choices)\n }\n get choices(): readonly T[] {\n return this.list.choices\n }\n get hostSlot(): HostSlotSource | null {\n return this.list.slot\n }\n bindHost(host: LorasHost): void {\n this.list.bind(host)\n }\n /** pick `c`, or clear it when it is already the one picked */\n toggle(c: T): this {\n return this.set(this.value === c ? null : c)\n }\n /** the TUI text form: a choice, or an empty line for none */\n parse(raw: string): boolean {\n if (raw.trim() === '') {\n this.set(null)\n return true\n }\n const hit = this.choices.find((c) => c === raw.trim())\n if (hit == null) return false\n this.set(hit)\n return true\n }\n override toEditBuffer(): string {\n return this.value ?? ''\n }\n /** a draft from when this was a many choice holds a list: its first known option */\n override loadJSON(value: unknown): this {\n const one = Array.isArray(value) ? value[0] : value\n return this.set(this.choices.find((c) => c === one) ?? null)\n }\n override display(): string {\n return this.value ?? 'none'\n }\n}\n\n/** any number of options, kept in the order the choices list them */\nexport class MultiChoiceVar<T extends string> extends ComfyVar<T[]> {\n readonly kind = 'choice' as const\n readonly select = 'many' as const\n constructor(\n public readonly choices: readonly T[],\n defaultValue: readonly T[],\n label?: string,\n ) {\n super([...defaultValue], label)\n }\n toggle(c: T): this {\n const on = this.value.includes(c)\n return this.set(this.choices.filter((x) => (x === c ? !on : this.value.includes(x))))\n }\n /** the TUI text form: `a, b` */\n parse(raw: string): boolean {\n const wanted = raw\n .split(',')\n .map((w) => w.trim())\n .filter((w) => w !== '')\n const picked = this.choices.filter((c) => wanted.includes(c))\n if (picked.length !== new Set(wanted).size) return false\n this.set(picked)\n return true\n }\n override toEditBuffer(): string {\n return this.value.join(', ')\n }\n /** a draft from when this was a single choice holds one value: a list of one. Unknown\n * options are dropped, the list comes back in the choices order */\n override loadJSON(value: unknown): this {\n const listed: unknown[] = Array.isArray(value) ? value : value == null ? [] : [value]\n return this.set(this.choices.filter((c) => listed.includes(c)))\n }\n override display(): string {\n return this.value.length === 0 ? 'none' : this.value.join(', ')\n }\n}\n\n/** the three choice shapes, told apart by `select` */\nexport type AnyChoiceVar<T extends string = string> = ChoiceVar<T> | OptionalChoiceVar<T> | MultiChoiceVar<T>\n\ntype ChoiceOpts<S extends ChoiceSelect> = { label?: string; select: S }\n\n/** Array.isArray does not narrow a READONLY array out of a union, this does */\nfunction isChoiceList<T extends string>(v: T | null | readonly T[] | HostSlotSource): v is readonly T[] {\n return Array.isArray(v)\n}\n\nfunction choice<const T extends string>(\n choices: readonly T[],\n defaultValue: T,\n label?: string | { label?: string; select?: 'one' },\n): ChoiceVar<T>\nfunction choice<const T extends string>(\n choices: readonly T[],\n defaultValue: T | null,\n opts: ChoiceOpts<'zero-or-one'>,\n): OptionalChoiceVar<T>\nfunction choice<const T extends string>(\n choices: readonly T[],\n defaultValue: readonly T[],\n opts: ChoiceOpts<'many'>,\n): MultiChoiceVar<T>\nfunction choice<const T extends string>(\n choices: readonly T[],\n defaultValue: T | null | readonly T[],\n opts?: string | { label?: string; select?: ChoiceSelect },\n): AnyChoiceVar<T> {\n const o = typeof opts === 'string' ? { label: opts } : (opts ?? {})\n const select = o.select ?? 'one'\n if (select === 'many') {\n if (!isChoiceList(defaultValue))\n throw new Error(`a 'many' choice takes a list as its default, got ${String(defaultValue)}`)\n return new MultiChoiceVar(choices, defaultValue, o.label)\n }\n if (isChoiceList(defaultValue)) throw new Error(`a '${select}' choice takes one value as its default, not a list`)\n if (select === 'zero-or-one') return new OptionalChoiceVar(choices, defaultValue, o.label)\n if (defaultValue == null) throw new Error(\"a 'one' choice needs a default: use { select: 'zero-or-one' } for none\")\n return new ChoiceVar(choices, defaultValue, o.label)\n}\n\nexport type ModelVarOpts<T extends string> = {\n /** narrows the host's list: `/krea/i` */\n filter?: RegExp\n label?: string\n /** a file name, or null for \"the workflow decides\" (the build then reads null) */\n default: T | null\n}\n\n/** a choice over the host's LIVE file list for one loader input (`'UNETLoader.unet_name'`),\n * resolved at define time and rebound by serve's refresh-schema: a downloaded model is picked\n * in the draft, never written into the workflow file */\nfunction model<T extends string>(slot: string, opts: ModelVarOpts<T> & { default: T }): ChoiceVar<T>\nfunction model<T extends string>(slot: string, opts: ModelVarOpts<T> & { default: null }): OptionalChoiceVar<T>\nfunction model<T extends string>(slot: string, opts: ModelVarOpts<T>): ChoiceVar<T> | OptionalChoiceVar<T> {\n const source: HostSlotSource = { slot, filter: opts.filter }\n if (opts.default == null) return new OptionalChoiceVar<T>(source, null, opts.label)\n return new ChoiceVar<T>(source, opts.default, opts.label)\n}\n\n/** per-lora setting, every spelling documented in src/vars/loraEntry.ts */\nexport type { LoraStrength } from 'src/vars/loraEntry.ts'\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: LorasInput<T>): ActiveLora<T>[] {\n const out: ActiveLora<T>[] = []\n for (const [lora_name, s] of Object.entries(flattenLoras(loras).record) as [T, LoraStrength | undefined][]) {\n // a paused lora ({ off: true }) is in the palette, never in the graph\n if (!loraIsOn(s)) continue\n const [strength_model, strength_clip] = loraStrengths(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 = {\n data?: { id?: string }\n schema: { getLoras(filter?: RegExp): string[]; stringValues(slot: string): string[] }\n}\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 */\n/**\n * the value is EITHER a plain record OR `{ lanes: [...] }` (src/vars/lanes.ts): named groups the\n * build merges in listed order, skipping inactive ones. Every method reads the merged record and\n * writes into the lane that holds the lora, so the TUI never needs to know lanes exist\n */\nexport class LorasVar<T extends string> extends ComfyVarBase<LorasInput<T>, LoraRecord<T>> {\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: LorasInput<T> = {},\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 /** the loras the build reads: the plain record, or the active lanes merged in order */\n get record(): LoraRecord<T> {\n return flattenLoras(this.value).record\n }\n\n /** what the graph consumes. A lora in two active lanes runs once, with its FIRST setting */\n outValue(): LoraRecord<T> {\n const flat = flattenLoras(this.value)\n if (flat.duplicates.length > 0)\n logError(\n `loras var '${this.name ?? this.label ?? '?'}': ${flat.duplicates.join(', ')} sit in two active lanes, the first lane's setting is used`,\n )\n return flat.record\n }\n\n /** rewrite one lora wherever it lives: the plain record, or the lane that holds it */\n private write(name: T, next: LoraStrength | null): this {\n return this.set(updateLora(this.value, name, next))\n }\n\n /** the parts of this lora's prompt keyword left out of the prompt */\n mutedWords(name: string): string[] {\n return loraMuted(this.record[name as T])\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 return loraIsOn(this.record[name])\n }\n\n toggleItem(name: T): this {\n const cur = this.record[name]\n if (cur == null || cur === false) return this.write(name, this.prev[name] ?? true)\n // a paused palette entry resumes in place, strengths kept\n if (!loraIsOn(cur)) return this.write(name, withLora(cur, { on: true }))\n this.prev[name] = cur\n return this.write(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.record[name]\n if (!loraIsOn(cur)) return this\n const step = (n: number): number => Math.max(0, Math.round((n + delta) * 100) / 100)\n // the short spellings stay short: only a palette entry needs the object form\n const next: LoraStrength =\n typeof cur === 'number' || cur === true\n ? step(cur === true ? 1 : cur)\n : Array.isArray(cur)\n ? [step(cur[0]), step(cur[1])]\n : withLora(cur, { strength: [step(loraStrengths(cur)[0]), step(loraStrengths(cur)[1])] })\n return this.write(name, next)\n }\n\n /** compact per-item strength label for lists */\n strengthLabel(name: T): string {\n const s = this.record[name]\n if (!loraIsOn(s)) return ''\n const [m, c] = loraStrengths(s)\n return m === c ? m.toFixed(2) : `m:${m.toFixed(2)} c:${c.toFixed(2)}`\n }\n\n parse(raw: string): boolean {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (!isLorasInput(parsed)) return false\n // cast: whitelist family 1, the names are this host's lora enum, checked by the build\n this.set(parsed as LorasInput<T>)\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 record = this.record\n let next = this.value\n for (const name of names) {\n const cur = record[name]\n if (on) {\n if (cur == null || cur === false) next = updateLora(next, name, this.prev[name] ?? true)\n // a paused palette entry resumes in place, strengths kept\n else if (!loraIsOn(cur)) next = updateLora(next, name, withLora(cur, { on: true }))\n } else {\n if (loraIsOn(cur)) this.prev[name] = cur\n next = updateLora(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/** the same aspect ratios around 512, for SD1.5-era models trained at ~0.25MP */\nexport const SD15_SIZE_PRESETS: SizePreset[] = [\n { label: '1:1 square', width: 512, height: 512 },\n { label: '4:3 landscape', width: 576, height: 448 },\n { label: '3:4 portrait', width: 448, height: 576 },\n { label: '3:2 landscape', width: 576, height: 384 },\n { label: '2:3 portrait', width: 384, height: 576 },\n { label: '16:9 widescreen', width: 704, height: 384 },\n { label: '9:16 tall', width: 384, height: 704 },\n]\n\n/** starred presets are one click away in the panel, before the full list */\nexport const DEFAULT_STARRED_SIZES = ['1:1 square', '3:4 portrait', '4:3 landscape']\n\n/** the family that matches a workflow's own default: a 512×512 workflow is an SD1.5-era one,\n * and offering it 1024 buckets would be offering sizes it was never trained at */\nexport function sizePresetsFor(defaultValue: SizeValue | undefined): SizePreset[] {\n if (defaultValue == null) return DEFAULT_SIZE_PRESETS\n return defaultValue.width * defaultValue.height <= 600 * 600 ? SD15_SIZE_PRESETS : DEFAULT_SIZE_PRESETS\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 /** preset LABELS starred by default; a user's own stars live in the panel */\n public readonly starred: readonly string[] = DEFAULT_STARRED_SIZES,\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 MediaVarOpts = {\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 media 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 /** the text var a file's `<name>.txt` sidecar fills, when a driver sets this var from a file\n * and leaves that one unset: a voice clip's transcript (`comfy-ts run`) */\n sidecarText?: TextVar\n}\nexport type ImageVarOpts = MediaVarOpts\nexport type AudioVarOpts = MediaVarOpts\nexport type VideoVarOpts = MediaVarOpts\n\nexport const DEFAULT_IMAGE_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.image\nexport const DEFAULT_AUDIO_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.audio\nexport const DEFAULT_VIDEO_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.video\n\n/** empty media var consumed at build time — typed so drivers surface it apart from real crashes */\nexport class MediaVarEmptyError extends Error {\n /** name, not instanceof: the cli bundle and dist/index.js each define this class */\n override readonly name: string = 'MediaVarEmptyError'\n constructor(\n public readonly varName: string,\n public readonly media: MediaKind = 'image',\n ) {\n super(`${media} var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/file'))`)\n }\n}\n/** the image-only name this error had first; the same class */\nexport const ImageVarEmptyError = MediaVarEmptyError\nexport type ImageVarEmptyError = MediaVarEmptyError\n\n/** trim + expand a leading `~/` — every media var 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/** the loader node each medium goes through, and its file input */\nconst MEDIA_LOADERS: Record<MediaKind, { node: string; input: string }> = {\n image: { node: 'LoadImage', input: 'image' },\n audio: { node: 'LoadAudio', input: 'audio' },\n video: { node: 'LoadVideo', input: 'file' },\n}\n\n/**\n * a local media file 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 MediaVarEmptyError,\n * so a build never runs on a silent placeholder. The TUI opens the file\n * picker overlay for every media kind.\n */\nexport abstract class MediaVar extends ComfyVar<string> {\n abstract override readonly kind: MediaKind\n constructor(\n defaultValue: string,\n public opts: MediaVarOpts = {},\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_MEDIA_EXTENSIONS[this.kind]\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(): MediaVarEmptyError {\n return new MediaVarEmptyError(this.name ?? this.label ?? this.kind, this.kind)\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 /** upload the file hash-named (reruns dedupe) and add this medium's loader node. A dry\n * build names the file by its hash and uploads nothing */\n protected async loadVia(wf: ComfyWorkflow<string>): Promise<unknown> {\n const loader = MEDIA_LOADERS[this.kind]\n const factory = wf.builderBase[loader.node]\n if (factory == null)\n throw new Error(\n `host '${wf.host.data.id}' has no ${loader.node} node: ${this.kind} var '${this.name ?? '?'}' cannot load`,\n )\n const abs = this.absPath()\n const bytes = getComfyStorage().readBytes(abs)\n const ext = extensionOf(abs)\n const name = `${hashArrayBuffer(bytes)}${ext === '' ? '' : `.${ext}`}`\n const onHost = wf.dry\n ? name\n : await wf.host.uploader.uploadInput({\n blob: new Blob([bytes as Uint8Array<ArrayBuffer>], { type: mediaMime(abs) }),\n name,\n slot: `${loader.node}.${loader.input}`,\n type: 'input',\n })\n return factory({ [loader.input]: onHost })\n }\n}\n\n/** a local image path, loaded through LoadImage */\nexport class ImageVar extends MediaVar {\n readonly kind = 'image' as const\n async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadImage'>> {\n // sanctioned cast (family 1): the node is the host's own LoadImage, built from object_info\n return (await this.loadVia(wf)) as NodeOf<WID, 'LoadImage'>\n }\n}\n\n/** a local audio path, loaded through LoadAudio */\nexport class AudioVar extends MediaVar {\n readonly kind = 'audio' as const\n async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadAudio'>> {\n // sanctioned cast (family 1): same as ImageVar\n return (await this.loadVia(wf)) as NodeOf<WID, 'LoadAudio'>\n }\n}\n\n/** a local video path, loaded through LoadVideo */\nexport class VideoVar extends MediaVar {\n readonly kind = 'video' as const\n async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadVideo'>> {\n // sanctioned cast (family 1): same as ImageVar\n return (await this.loadVia(wf)) as NodeOf<WID, 'LoadVideo'>\n }\n}\n\n/** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.model / v.loras / v.size / v.image / v.audio / v.video */\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 /** a string, or `{ lanes: [{ name, prompt, active }] }` merged in listed order */\n defaultValue: PromptInput,\n opts: PromptVarOpts = {},\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 /** exactly one option (the default), `{ select: 'zero-or-one' }` for one or none (value\n * `T | null`), `{ select: 'many' }` for any number (value `T[]`) */\n choice,\n loras: <T extends string = string>(\n options: readonly T[] | RegExp,\n /** a record, or `{ lanes: [{ name, active, loras }] }` merged in listed order */\n initial: LorasInput<T> = {},\n label?: string,\n ): LorasVar<T> => new LorasVar(options, initial, label),\n size: (\n defaultValue?: SizeValue,\n opts: { presets?: SizePreset[]; starred?: readonly string[]; label?: string; image?: ImageVar } = {},\n ): SizeVar =>\n new SizeVar(defaultValue, opts.presets ?? sizePresetsFor(defaultValue), opts.label, opts.image, opts.starred),\n /** host-bound: only inside defineWorkflow({ vars: (v) => … }), typed per slot there */\n model,\n image: (defaultValue: string, opts: MediaVarOpts = {}): ImageVar => new ImageVar(defaultValue, opts),\n audio: (defaultValue: string, opts: MediaVarOpts = {}): AudioVar => new AudioVar(defaultValue, opts),\n video: (defaultValue: string, opts: MediaVarOpts = {}): VideoVar => new VideoVar(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 readonly uiOpts: VarUi\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 type { LorasInput } from 'src/vars/lanes.ts'\nimport {\n type AnyVar,\n type ChoiceVar,\n type LorasVar,\n type ModelVarOpts,\n type OptionalChoiceVar,\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' | 'model'> & {\n loras(options: RegExp, initial?: LorasInput<LoraNameOf<ID>>, label?: string): LorasVar<LoraNameOf<ID>>\n loras<T extends string>(options: readonly T[], initial?: LorasInput<T>, label?: string): LorasVar<T>\n /** the host's file list for one loader input: the slot autocompletes, the value is its union */\n model: ModelFactory<SdkForHost<ID>['Slots']>\n}\n\n/** `v.model` typed by a host's slot table S (`Slots`): its own interface, so the host id's\n * variance stays measurable (inlined into BoundVars, ComfyHost<ID> stopped being a ComfyHost<string>) */\nexport interface ModelFactory<S> {\n <K extends keyof S & string>(\n slot: K,\n opts: ModelVarOpts<S[K] & string> & { default: S[K] & string },\n ): ChoiceVar<S[K] & string>\n <K extends keyof S & string>(\n slot: K,\n opts: ModelVarOpts<S[K] & string> & { default: null },\n ): OptionalChoiceVar<S[K] & string>\n}\n\n/** every `Node.input` slot of the host's generated sdk (any string without one) */\nexport type SlotNameOf<ID extends string> = keyof SdkForHost<ID>['Slots'] & string\n\n/** the value union of one slot, strings only (a loader file list) */\nexport type SlotValueOf<ID extends string, K extends string> = K extends keyof SdkForHost<ID>['Slots']\n ? SdkForHost<ID>['Slots'][K] & string\n : string\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 /** named texts computed from the CURRENT var values, the same `vars` build receives, shown\n * live while the vars are edited (the serve panel: a foldable block under generate). Use the\n * function build uses, so a preview is what the run sends, never a paraphrase of it */\n previews?: Record<string, (vars: VarValues<V>) => string>\n /** free search tags for the serve omnibox, added to the ones read from the graph\n * (`image`, `audio`, `video`, `text`, `llm`, `edit`) */\n tags?: string[]\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 // a condition naming a var that does not exist would silently never enable its field\n const names = this.entries().map(([key]) => key)\n for (const [key, varDef] of this.entries())\n for (const other of Object.keys(varDef.uiOpts.activeWhen ?? {}))\n if (!names.includes(other))\n throw new Error(\n `workflow '${spec.id ?? '?'}': var '${key}' is activeWhen '${other}', which is not one of its vars (${names.join(', ')})`,\n )\n }\n\n /** every preview for the current var values. A preview that throws, or vars that cannot be\n * read yet (an image var still empty), give a line saying so instead of failing the others */\n computePreviews(): Record<string, string> {\n const previews = this.spec.previews ?? {}\n const names = Object.keys(previews)\n if (names.length === 0) return {}\n let values: VarValues<V>\n try {\n values = varValues(this.vars)\n } catch (e) {\n const why = `unavailable: ${e instanceof Error ? e.message : String(e)}`\n return Object.fromEntries(names.map((n) => [n, why]))\n }\n const out: Record<string, string> = {}\n for (const [name, fn] of Object.entries(previews)) {\n try {\n out[name] = fn(values)\n } catch (e) {\n out[name] = `🔴 preview '${name}' failed: ${e instanceof Error ? e.message : String(e)}`\n }\n }\n return out\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 * `p.dry` builds a graph only to read it: nothing is uploaded, lastWorkflow is left alone.\n */\n async build(p: { advance?: boolean; host?: ComfyHost<ID>; dry?: boolean } = {}): Promise<ComfyWorkflow<ID>> {\n const host = p.host ?? this.host\n const wf = host.workflow({ id: this.spec.id })\n wf.dry = p.dry === true\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 if (wf.dry) return 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 onPreview: settings.onPreview,\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 { type PreviewMethod, previewMethodFromSystemStats } from 'src/host/previewMethod.ts'\nimport {\n binaryFrameType,\n isPreviewFrameType,\n type ParsedPreviewFrame,\n parseBinaryWsFrame,\n parsePreviewFrame,\n} 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 isIgnoredWsEventType,\n isRoutedWsEventType,\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\ntype LatentPreview = { promptID: Maybe<PromptID>; receivedAt: number_Timestamp; blob: Blob; url: string }\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 /** a repeat interrupt for the same running prompt inside this window reuses the first request */\n interruptCoalesceMs = 3000\n private _lastInterrupt: { promptID: PromptID | null; at: number; req: Promise<void> } | null = null\n\n /** interrupt the CURRENTLY RUNNING prompt. A burst of /interrupt posts can make the ComfyUI\n * python process quit, so repeats for the same prompt are coalesced into one request */\n interrupt = (): Promise<void> => {\n const now = Date.now()\n const last = this._lastInterrupt\n if (last != null && last.promptID === this.activePromptID && now - last.at < this.interruptCoalesceMs)\n return last.req\n const req = this.postJSON_('/interrupt', {})\n this._lastInterrupt = { promptID: this.activePromptID, at: now, req }\n // a failed request must not swallow the retry\n req.catch(() => {\n if (this._lastInterrupt?.req === req) this._lastInterrupt = null\n })\n return req\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 `--preview-method` this host was launched with, read from `GET /system_stats`.\n * `'none'` (ComfyUI's default) means no live preview frame will ever arrive; null = the host\n * does not publish its launch flags (a cloud host), so only a run can tell */\n fetchPreviewMethod = async (): Promise<PreviewMethod | null> => {\n const res = await this.fetch('/system_stats', {})\n if (!res.ok) throw new Error(`GET /system_stats failed: ${res.status}`)\n return previewMethodFromSystemStats(await res.json())\n }\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 last raw preview frame; `latentPreview` decodes it only when read */\n private _latentFrame: Maybe<{ data: ArrayBuffer; promptID: Maybe<PromptID>; receivedAt: number_Timestamp }> = null\n private _latentPreview: Maybe<LatentPreview> = null\n\n /** the latent image beeing generated, in case you want to display it. Built on read: a\n * session that never reads it never decodes a frame nor holds an object url */\n get latentPreview(): Maybe<LatentPreview> {\n if (this._latentPreview != null || this._latentFrame == null) return this._latentPreview\n const frame = parsePreviewFrame(this._latentFrame.data)\n const blob = new Blob([frame.bytes], { type: frame.mime })\n this._latentPreview = {\n blob,\n url: URL.createObjectURL(blob),\n receivedAt: this._latentFrame.receivedAt,\n promptID: this._latentFrame.promptID,\n }\n return this._latentPreview\n }\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 /** event types we already complained about on this connection (one log per type, no\n * spam); both sets clear when the server assigns a new session id */\n private _unknownBinaryFrameTypes = new Set<number>()\n private _unknownWsEventTypes = new Set<string>()\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 /** a type 1 or 4 frame. Parsed only when someone wants it, in this order (architecture.md,\n * Live previews): the ws saver's output, the pre-registration buffer, the run's onPreview,\n * the host hook. Nobody listening = the frame is kept by reference and never copied */\n private onPreviewFrame(data: ArrayBuffer): void {\n let parsed: ParsedPreviewFrame | null = null\n const frame = (): ParsedPreviewFrame => (parsed ??= parsePreviewFrame(data))\n const promptID = this.activePromptID\n const activeExec = promptID != null ? this.executions.get(promptID) : null\n // OUTPUT, not preview: while a SaveImageWebsocket node executes, each preview-kind\n // frame IS one output image (frames follow their 'executing' message on the same\n // socket, architecture.md item 14)\n if (activeExec?.wsOutputNodeExecuting)\n return activeExec.onWsImageOutput({ bytes: frame().bytes, mime: frame().mime })\n // pre-registration window: ws messages can beat the POST /prompt response, and an\n // ephemeral output frame in that window would be the ONLY copy of the image. Buffer it\n // IN ORDER with the json messages; ComfyExecution.onCreate replays the queue and decides\n // output-vs-preview from the state at replay time\n const pending = promptID != null ? this._pendingMsgs.get(promptID) : undefined\n if (pending != null)\n pending.push({\n type: 'binary_preview_frame',\n bytes: frame().bytes,\n mime: frame().mime,\n metadata: frame().metadata,\n })\n // the object url REGISTRY holds a strong ref to its blob until revoked, and a sampler\n // emits one frame per step: revoke the outgoing one or a long session retains every latent\n if (this._latentPreview != null) URL.revokeObjectURL(this._latentPreview.url)\n this._latentPreview = null\n this._latentFrame = { data, promptID, receivedAt: Date.now() as number_Timestamp }\n if (activeExec?.onPreview != null) activeExec.onPreviewFrame(frame())\n if (this.onLatentPreview != null) this.onLatentPreview({ bytes: frame().bytes, mime: frame().mime, promptID })\n }\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 if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data)\n const frame = parseBinaryWsFrame(e.data)\n 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 let msg_: unknown = JSON.parse(String(e.data))\n\n // ----- routed, ignored by name, or unknown (architecture.md, ws events) -----\n const rec = typeof msg_ === 'object' && msg_ != null ? msg_ : null\n const eventType = rec != null && 'type' in rec && typeof rec.type === 'string' ? rec.type : null\n if (eventType != null && isIgnoredWsEventType(eventType)) return\n if (eventType == null || !isRoutedWsEventType(eventType)) {\n const key = eventType ?? '<no type>'\n if (this._unknownWsEventTypes.has(key)) return\n this._unknownWsEventTypes.add(key)\n console.error(\n `🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`,\n )\n return\n }\n\n // the reconnect resend of the running node carries no prompt_id (server.py websocket_handler)\n if (eventType === 'executing' && this.activePromptID != null && rec != null) {\n const data: unknown = Reflect.get(rec, 'data')\n if (typeof data === 'object' && data != null && !('prompt_id' in data))\n msg_ = { type: eventType, data: { ...data, prompt_id: this.activePromptID } }\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) {\n this._unknownWsEventTypes.clear()\n this._unknownBinaryFrameTypes.clear()\n this.onSession?.(msg.data.sid)\n }\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_interrupted' ||\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 }\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 DB.modelRows = knownModelList\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 /** every model row, the ones sharing a name included (knownModels keeps the last) */\n modelRows: 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 /** the serve web ui's LLM configs (prompt enhancer), one json per config */\n resolveFromLlmConfigs(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'llm-configs', 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","import { existsSync, readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, join } from 'pathe'\n\n/**\n * the examples/ folder shipped in the npm tarball, resolved from THIS module's\n * own location (NEVER cwd): walking up to the nearest NAMED package.json finds\n * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/ and from\n * this repo's src/. Returns null when the examples are absent (a consumer may\n * prune the folder) or when the nearest named package is not comfy-ts (the lib\n * was inlined into someone else's bundle — its examples are not on disk); no\n * package.json all the way up is a broken install and throws.\n */\nexport function bundledExamplesDir(moduleUrl: string = import.meta.url): string | null {\n let dir = dirname(fileURLToPath(moduleUrl))\n let prev = ''\n while (dir !== prev) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n let pkg: { name?: string } = {}\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n } catch {\n // a malformed package.json on the walk (someone's broken fixture\n // dir) must not take the whole TUI down; treat as unnamed\n }\n if (pkg.name === 'comfy-ts') {\n const examples = join(dir, 'examples')\n return existsSync(examples) ? examples : null\n }\n if (pkg.name != null) return null\n }\n prev = dir\n dir = dirname(dir)\n }\n throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`)\n}\n\n/**\n * absolute path of a bundled `examples/images/` input image, e.g.\n * `exampleImagePath('bear_1024x1024.jpg')` — the out-of-the-box default for\n * i2i/i2v example image vars, valid from this repo AND from a consumer's\n * node_modules/comfy-ts/. Loud throw naming the path when the file is missing\n * or the package's examples/ folder was pruned.\n */\nexport function exampleImagePath(name: string): string {\n return bundledExampleFile('images', name)\n}\n\n/** the same for a bundled `examples/media/` audio or video file, e.g.\n * `exampleMediaPath('sine_440hz_3s.flac')` — the default of audio and video example vars */\nexport function exampleMediaPath(name: string): string {\n return bundledExampleFile('media', name)\n}\n\nfunction bundledExampleFile(folder: 'images' | 'media', name: string): string {\n const examples = bundledExamplesDir()\n if (examples == null) {\n throw new Error(\n `[comfy-ts] cannot resolve bundled example file '${name}': the package's examples/ folder is not on disk`,\n )\n }\n const abs = join(examples, folder, name)\n if (!existsSync(abs)) throw new Error(`[comfy-ts] bundled example file not found: ${abs}`)\n return abs\n}\n","// THE name gate for every serve route that turns a url segment into a file path.\n// SECURITY-CRITICAL and deliberately shared: handle() decodes per segment, so\n// `%2F` arrives as a real `/` while the segment count still looks right. One\n// function, because a second regex somewhere else is a second traversal hole.\n\n/** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */\nexport function validStoreName(raw: string): string | null {\n const name = raw.trim()\n // length cap: past it the fs answers ENAMETOOLONG as a raw 500\n if (name.length > 100) return null\n return /^[\\w][\\w .-]*$/.test(name) ? name : null\n}\n\n/** a save prefix becomes a PATH under outputs/, so every segment goes through the same gate:\n * it cannot climb out, and it cannot be absolute. Lives here, not on ServeApp, because the\n * settings READER validates it too, a hand-written settings file never met the PUT route. */\nexport function validSavePrefix(raw: string): string | null {\n const clean = raw.trim().replaceAll('\\\\', '/')\n if (clean === '') return ''\n // an ABSOLUTE path is refused, not quietly re-rooted: dropping the leading slash turned\n // '/etc' into 'etc' under outputs/, which is safe but is not what the writer asked for\n if (clean.startsWith('/') || /^[a-z]:/i.test(clean)) return null\n // the whole path is capped, not only each segment: 3000 valid two-char segments passed and\n // then broke that module's saving for good with an unopenable path\n if (clean.length > 200) return null\n const segments = clean.split('/').filter((s) => s !== '')\n if (segments.length === 0 || segments.some((s) => validStoreName(s) == null)) return null\n return segments.join('/')\n}\n","// the master prompts of the web ui's prompt enhancer, as FILES:\n// `.comfy-ts/prompt-enhancers/<name>.md`, the drafts model applied to prose.\n// markdown, not json: these are hand-edited paragraphs, and a json string field\n// would be one escaped line. The FILENAME is the identity (a rename is a write\n// plus a delete); validStoreName is the same gate the draft routes use.\n// NODE-ONLY (fs): the web entry never touches this folder, and a workflow reads\n// it through promptEnhancerPresets() to offer the same texts as var presets.\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'pathe'\nimport { validStoreName } from 'src/utils/safeName.ts'\nimport type { VarPresetSpec } from 'src/vars/presets.ts'\n\nconst EXT = '.md'\n\nexport type PromptEnhancer = { name: string; text: string }\n\nexport function promptEnhancersDir(): string {\n return comfyts.resolveFromPromptEnhancers('')\n}\n\nfunction promptEnhancerPath(name: string): string | null {\n const safe = validStoreName(name)\n return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`)\n}\n\n/** the shipped starting point. It is a FILE from the first read on, so it can be edited\n * on disk like everything else, the browser ships no copy of this text */\nconst SEED: PromptEnhancer = {\n name: 'refine-krea2-prompt',\n text: `You rewrite image prompts for krea2 turbo, a distilled 8 step text to image model whose text encoder reads flowing natural language. Long detailed prompts give it the best images. Your job is to serve the VISION behind the user's line: take what they wrote and expand it into the picture they were already imagining but did not type.\n\nRewrite it into ONE paragraph a reader could picture with their eyes closed:\n\n- every subject, action, color and spatial relation the user wrote survives, in their own words wherever those words already work. Nothing is dropped, nothing is swapped for something easier.\n- expand the vision, never replace it. Add the visual facts a camera would have to resolve anyway: what each subject looks like, lighting, palette, material and texture, camera angle and distance, framing and composition, background, depth of field, mood, and the signature of the medium itself (visible brushstrokes, film grain, cel shading, stippling, halftone, airbrush gradients, paper texture).\n- choose the style before you write, and keep the choosing invisible. Weigh two or three mediums and lighting setups, pick the one that best serves the input, then write only the result. If they named a medium (photo of, illustration of, 3D render of, painting of, sketch of), that medium is fixed.\n- attach every attribute to its own subject, so nothing bleeds: one clause per figure carrying its features, clothes, pose and action. Spatial words stay grounded: left foreground, upper center, behind, resting on, knee deep in.\n- an input that is already dense gets polished and finished, not inflated. Keep its phrasing and its direction, add only what is genuinely missing.\n- plain descriptive english. Flowing sentences and comma separated descriptive clauses both read well; disconnected keyword soup does not. No praise words, never \"masterpiece\", \"8k\", \"highly detailed\", \"award winning\", \"trending on\". The model is steered by what you name, not by what you forbid.\n- text that must appear inside the image is spelled out in \"quotes\", exactly as it should be rendered.\n- roughly 60 to 150 words, one paragraph, no lists, no headings, no quotes around the result itself.\n- never write a negative (\"- ...\") line or a comment (\"// ...\") line: the panel keeps the user's own and adds them back after your prompt.\n\nAnswer with the rewritten prompt and nothing else: no preamble, no explanation.\n`,\n}\n\n/** seeds ONCE, on an absent folder, then lists. An emptied folder stays empty: the seed is a\n * starting point, not a file the store keeps restoring */\nexport function listPromptEnhancers(): PromptEnhancer[] {\n if (!existsSync(promptEnhancersDir())) writePromptEnhancer(SEED.name, SEED.text)\n return readPromptEnhancers()\n}\n\n/** the PURE read: no seeding, no writing. What a workflow calls at define time, since importing\n * a module must never create files in someone's project */\nexport function readPromptEnhancers(): PromptEnhancer[] {\n const dir = promptEnhancersDir()\n if (!existsSync(dir)) return []\n const out: PromptEnhancer[] = []\n for (const file of readdirSync(dir).sort()) {\n if (!file.endsWith(EXT)) continue\n const name = file.slice(0, -EXT.length)\n if (validStoreName(name) == null) continue\n // one unreadable entry (a DIRECTORY called *.md, a permission problem) must not take the\n // whole route down: it is skipped loudly, the rest still list\n try {\n out.push({ name, text: readFileSync(join(dir, file), 'utf8') })\n } catch (e) {\n console.error(`[serve] prompt enhancer '${name}' unreadable, skipped:`, e)\n }\n }\n return out\n}\n\n/**\n * the same master prompts, shaped for `v.text(x, { presets })` / `v.prompt`: file name → text.\n * The point is that ONE library of texts serves the ✨ enhancer and every var that wants them,\n * so a paragraph you tuned in the panel is offered by the workflow too, with no copy.\n * Empty when the folder is absent, so a var keeps whatever presets it declares inline.\n */\nexport function promptEnhancerPresets(): VarPresetSpec {\n const out: VarPresetSpec = {}\n for (const e of readPromptEnhancers()) out[e.name] = e.text\n return out\n}\n\nexport function writePromptEnhancer(name: string, text: string): string | null {\n const path = promptEnhancerPath(name)\n if (path == null) return null\n mkdirSync(promptEnhancersDir(), { recursive: true })\n writeFileSync(path, text)\n return path\n}\n\n/** a missing file is still a success: the caller asked for it to be gone, and it is */\nexport function deletePromptEnhancer(name: string): boolean {\n const path = promptEnhancerPath(name)\n if (path == null) return false\n if (existsSync(path)) rmSync(path)\n return true\n}\n","// contract between the TUI and workflow modules: the TUI sets this env var\n// before importing a module; example files also use `import.meta.main` to\n// only self-run when executed directly.\nexport const COMFY_TS_TUI_ENV = 'COMFY_TS_TUI'\n\nexport function isTuiActive(): boolean {\n return process.env[COMFY_TS_TUI_ENV] === '1'\n}\n","/**\n * comfy-ts — type-safe ComfyUI workflow creation and execution (NODE entry)\n * @packageDocumentation\n */\nimport { setDefaultComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { createNodeStorage } from 'src/storage/nodeStorage.ts'\n\n// entry side effect: node 20/21 dist consumers have no getBuiltinModule\n// autodetect, so the node backend installs here (architecture item 13)\nsetDefaultComfyStorage(createNodeStorage())\n\nexport * from 'src/coreExports.ts'\n\n// node-only surface: fs-backed example assets + the TUI env contract\nexport { exampleImagePath, exampleMediaPath } from 'src/exampleAssets.ts'\n// the prompt-enhancer library on disk, offered as var presets (fs, so never in the web entry)\nexport { promptEnhancerPresets, readPromptEnhancers, type PromptEnhancer } from 'src/promptEnhancers.ts'\nexport { isTuiActive } from 'src/cli/tui-env.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,GAA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,mBAAmB;CAC/B,IAAI,EAAA,GAAA,QAAA,WAAA,CAAY,GAAG,GAAG,OAAO,CAAC;CAC9B,MAAM,MAAwB,CAAC;CAC/B,KAAK,MAAM,SAAA,GAAA,QAAA,YAAA,CAAoB,GAAG,CAAC,CAAC,KAAK,GAAG;EACzC,IAAI,CAAC,KAAK,SAAS,GAAG,GAAG;EACzB,MAAM,OAAO,KAAK,MAAM,GAAG,EAAW;EACtC,IAAI,eAAe,IAAI,KAAK,MAAM;EAGlC,IAAI;GACD,IAAI,KAAK;IAAE;IAAM,OAAA,GAAA,QAAA,aAAA,EAAA,GAAA,MAAA,KAAA,CAAwB,KAAK,IAAI,GAAG,MAAM;GAAE,CAAC;EACjE,SAAS,GAAG;GACT,QAAQ,MAAM,4BAA4B,KAAK,yBAAyB,CAAC;EAC5E;CACH;CACA,OAAO;AACV;;;;;;;AAQA,SAAgB,wBAAuC;CACpD,MAAM,MAAqB,CAAC;CAC5B,KAAK,MAAM,KAAK,oBAAoB,GAAG,IAAI,EAAE,QAAQ,EAAE;CACvD,OAAO;AACV;;;AClFA,MAAa,mBAAmB;AAEhC,SAAgB,cAAuB;CACpC,OAAO,QAAQ,IAAI,sBAAsB;AAC5C;;;;;;;ACEA,uBAAuB,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["g","fs","os","type","type","type","type","type","type","type","type","type","isRecord","isRecord","type","type","types","chalk","type","isRecord","type","type","type","type","type","type","observable","observable","action","type","chalk","chalk","type","type","chalk","type","type","type","chalk","type","type","chalk","type","type","chalk","pkgJson.version","globalHack"],"sources":["../src/storage/ComfyStorage.ts","../src/storage/nodeStorage.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/host/previewMethod.ts","../src/runner/wsBinaryFrame.ts","../src/sdk-generator/Primitives.ts","../src/utils/exhaust.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/sha1.ts","../src/utils/hashArrayBuffer.ts","../src/graph/ComfyNodeID.ts","../src/runner/ComfyWsApi.ts","../src/runner/MediaImage.ts","../src/runner/mediaKinds.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/installedView.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/loraEntry.ts","../src/vars/lanes.ts","../src/vars/promptSyntax.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/exampleAssets.ts","../src/utils/safeName.ts","../src/promptEnhancers.ts","../src/cli/tui-env.ts","../src/index.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","// the ONLY core-path module allowed to import node:fs statically\n// (architecture item 13) — index.ts installs it; the web graph never sees it\nimport * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport { type ComfyStorage, createNodeStorageFrom } from 'src/storage/ComfyStorage.ts'\n\nexport function createNodeStorage(): ComfyStorage {\n return createNodeStorageFrom(fs, os)\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/** expanded node count above which a file is refused before expanding: the largest official\n * template expands to 575 nodes, and fan-out nesting grows geometrically without any cycle */\nexport const MAX_EXPANDED_NODES = 100_000\n\n/**\n * before any expansion: the definitions as a graph (def → the defs its NORMAL-mode instances name,\n * the only ones expansion follows). A cycle reachable from the root is refused with the defs it\n * runs through, and the expanded size is counted, not built, and refused above\n * MAX_EXPANDED_NODES. One explicit stack, no recursion: the file decides the depth\n */\nconst checkExpansion = (wf: CanonicalWorkflow, defs: Map<string, CanonicalSubgraphDef>): void => {\n const children = (nodes: CanonicalNode[]): string[] =>\n nodes.filter((n) => n.mode === 'normal' && defs.has(n.type)).map((n) => n.type)\n const own = (nodes: CanonicalNode[]): number =>\n nodes.filter((n) => !(n.mode === 'normal' && defs.has(n.type))).length\n const name = (id: string): string => JSON.stringify(defs.get(id)?.name ?? id)\n const cap = (n: number): number => Math.min(n, MAX_EXPANDED_NODES + 1)\n const size = new Map<string, number>() // done (black): expanded node count of one instance\n const onPath = new Set<string>() // gray\n for (const root of new Set(children(wf.nodes))) {\n if (size.has(root)) continue\n const stack: { id: string; kids: string[]; next: number }[] = [\n { id: root, kids: children(bang(defs.get(root)).nodes), next: 0 },\n ]\n onPath.add(root)\n while (stack.length > 0) {\n const top = bang(stack[stack.length - 1])\n const kid = top.kids[top.next++]\n if (kid == null) {\n const total = top.kids.reduce((acc, k) => cap(acc + (size.get(k) ?? 0)), own(bang(defs.get(top.id)).nodes))\n size.set(top.id, total)\n onPath.delete(top.id)\n stack.pop()\n continue\n }\n if (size.has(kid)) continue\n if (onPath.has(kid)) {\n const from = stack.findIndex((frame) => frame.id === kid)\n const cycle = [...stack.slice(from).map((frame) => frame.id), kid].map(name).join(' → ')\n throw new WorkflowNormalizeError('subgraph-cycle', `subgraph definitions contain themselves: ${cycle}`, {\n cycle: stack.slice(from).map((frame) => frame.id),\n })\n }\n onPath.add(kid)\n stack.push({ id: kid, kids: children(bang(defs.get(kid)).nodes), next: 0 })\n }\n }\n const total = children(wf.nodes).reduce((acc, k) => cap(acc + (size.get(k) ?? 0)), own(wf.nodes))\n if (total > MAX_EXPANDED_NODES)\n throw new WorkflowNormalizeError(\n 'subgraph-too-large',\n `subgraph expansion would produce more than ${MAX_EXPANDED_NODES} nodes (the largest official template has 575)`,\n )\n}\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 checkExpansion(wf, defs)\n // acyclic now: each pass goes one definition deeper, so defs.size passes always suffice\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 > defs.size + 1)\n throw new WorkflowNormalizeError(\n 'subgraph-cycle',\n `subgraph expansion still had instances after ${passes - 1} passes over ${defs.size} 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 widgetSource: i.widgetSource,\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 // 8. a subgraph input with no outer link resolves to its promoted widget (frontend\n // ExecutableNodeDTO.resolveInput): its slot targets read that widget's value\n for (const [slot, targets] of boundaryTargetsByInSlot) {\n if (outerLinkIntoDefSlot.has(slot)) continue\n const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null)\n const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null\n if (source == null || sourceInput == null) continue\n for (const t of targets) {\n const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot]\n if (input == null || input.widgetName != null || input.link != null) continue\n input.widgetSource = { nodeId: source.nodeId, inputName: sourceInput.name }\n }\n }\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 | null // | 'select' (null in the official fibo2 templates)\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?': type.string.or(type.null),\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 | null // the official fibo2 templates write null\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_.or(type.null),\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 | string // v0.4 (recomputable, absent in v1), a NodeId: the official blueprints write a string\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 | string',\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 =\n | 'schema-reject'\n | 'subgraph-cycle'\n | 'subgraph-too-large'\n | 'subgraph-io-mismatch'\n | '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 widgetSource: 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","// ComfyUI sends live preview frames only when launched with `--preview-method` set to\n// something other than its default `none`. The launch flags reach a client through\n// `GET /system_stats` (`system.argv`), the one place a client can read them.\n\nexport type PreviewMethod = 'none' | 'auto' | 'latent2rgb' | 'taesd'\n\nfunction isPreviewMethod(x: unknown): x is PreviewMethod {\n return x === 'none' || x === 'auto' || x === 'latent2rgb' || x === 'taesd'\n}\n\n/** the preview method a host was launched with, from its /system_stats payload. `'none'` when\n * the flag is absent (ComfyUI's default), null when the payload carries no argv to read (a cloud\n * host) or the flag holds a value this parser does not know */\nexport function previewMethodFromSystemStats(stats: unknown): PreviewMethod | null {\n if (stats == null || typeof stats !== 'object' || !('system' in stats)) return null\n const system = stats.system\n if (system == null || typeof system !== 'object' || !('argv' in system)) return null\n const argv = system.argv\n if (!Array.isArray(argv)) return null\n for (let i = 0; i < argv.length; i++) {\n const arg: unknown = argv[i]\n if (typeof arg !== 'string') continue\n const value =\n arg === '--preview-method' ? argv[i + 1] : arg.startsWith('--preview-method=') ? arg.slice(17) : undefined\n if (value === undefined) continue\n return isPreviewMethod(value) ? value : null\n }\n return 'none'\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 const BINARY_FRAME_PREVIEW_IMAGE = 1\nexport const BINARY_FRAME_TEXT = 3\nexport const BINARY_FRAME_PREVIEW_IMAGE_WITH_METADATA = 4\n\nexport type ParsedPreviewFrame = { kind: 'preview'; bytes: Uint8Array<ArrayBuffer>; mime: string; metadata: unknown }\n\nexport type ParsedBinaryWsFrame =\n | ParsedPreviewFrame\n | { kind: 'text'; nodeId: string; text: string }\n | { kind: 'unknown'; eventType: number }\n\n/** the frame's event type, read in place: deciding whether anyone wants a frame costs no copy */\nexport function binaryFrameType(data: ArrayBuffer): number {\n if (data.byteLength < 4) return -1\n return new DataView(data).getUint32(0)\n}\n\nexport function isPreviewFrameType(eventType: number): boolean {\n return eventType === BINARY_FRAME_PREVIEW_IMAGE || eventType === BINARY_FRAME_PREVIEW_IMAGE_WITH_METADATA\n}\n\nexport function parseBinaryWsFrame(data: ArrayBuffer): ParsedBinaryWsFrame {\n const eventType = binaryFrameType(data)\n if (isPreviewFrameType(eventType)) return parsePreviewFrame(data)\n\n if (eventType === BINARY_FRAME_TEXT) {\n const nodeIdLen = new DataView(data).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 return { kind: 'unknown', eventType }\n}\n\n/** a type 1 or type 4 frame; the caller checked the type with `isPreviewFrameType` */\nexport function parsePreviewFrame(data: ArrayBuffer): ParsedPreviewFrame {\n const view = new DataView(data)\n if (view.getUint32(0) === BINARY_FRAME_PREVIEW_IMAGE) {\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 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/** the node a type 4 frame names (`node_id` in its metadata), null when absent or malformed */\nexport function previewMetadataNodeId(metadata: unknown): string | null {\n if (metadata == null || typeof metadata !== 'object' || !('node_id' in metadata)) return null\n return typeof metadata.node_id === 'string' && metadata.node_id !== '' ? metadata.node_id : null\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","/* 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","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 /** widget rows: prompt keys `<decl>.<row>.<field>`, saved run `[count, …row field runs]` (architecture.md, dynamic group) */\n | { kind: 'dynamic-group'; fields: RawInputSpecEntry[]; min: number; max: 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/** dynamic group (`template` holding `required`/`optional` sections itself): fields in the\n * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */\nconst parseGroup = (o: Record<string, unknown>, template: Record<string, unknown>): InputWidgetKind => ({\n kind: 'dynamic-group',\n fields: flattenInputSections(template),\n min: typeof o['min'] === 'number' ? o['min'] : 0,\n max: typeof o['max'] === 'number' ? o['max'] : 20,\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; WITH its own required/optional\n // sections = dynamic group; with neither = matchtype slot typing\n const template = o?.['template']\n if (o != null && isRecord(template)) {\n if (isRecord(template['input'])) return parseContainer(template)\n if (isRecord(template['required']) || isRecord(template['optional'])) return parseGroup(o, template)\n return { kind: 'slot' }\n }\n // 7. a socketless KEY, true or false: only a backend WidgetInput emits it (true = no socket,\n // IMAGECOMPARE, COLOR; false = a socket too, BOUNDING_BOXES, COLORS); value domain unknown\n if (typeof o?.['socketless'] === 'boolean')\n 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 { exhaust } from 'src/utils/exhaust.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 // indexes: a lookup per link must not scan the document (a large file stays linear)\n const linksById = new Map(workflow.links.map((l) => [l.id, l]))\n const nodesById = new Map(workflow.nodes.map((n) => [n.id, 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 /** the row count first (named, else positional, else `min`), then every row's fields in\n * template order: the frontend's saved run (architecture.md, dynamic group) */\n const consumeDynamicGroup = (p: {\n path: string\n fields: RawInputSpecEntry[]\n min: number\n max: number\n }): void => {\n const r = resolveWidgetValue({ promptName: p.path, consumes: 1, prefixLen: 0 })\n const saved = r.filled ? p.min : r.value\n if (typeof saved !== 'number' || !Number.isInteger(saved) || saved < 0 || saved > p.max)\n throw new WorkflowConvertError(\n 'invalid-widget-value',\n `node ${node.id}(${node.type}): dynamic group \"${p.path}\" row count is not an integer in [0, ${p.max}]: ${JSON.stringify(saved)}`,\n node,\n )\n // the frontend clamps a short count UP to min (dynamicGroupWidget: Math.max(min, requested))\n const rows = Math.max(p.min, saved)\n if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`)\n for (let row = 0; row < rows; row++)\n for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field)\n }\n\n const consumeBranchInput = (subPath: string, sub: RawInputSpecEntry): void => {\n // the frontend names a branch or row widget by its full dotted path, and the seed\n // heuristic of the control phantom reads that name (architecture.md, rule 9)\n const kind = classifyWidgetInput({ name: subPath, type: sub.type, opts: sub.opts })\n switch (kind.kind) {\n // slots and containers materialize as dotted serialized inputs, resolved as links in 2.b\n case 'slot':\n case 'dynamic-container':\n return\n case 'dynamic-combo':\n return consumeDynamicCombo({ path: subPath, options: kind.options, defaultKey: kind.defaultKey })\n case 'dynamic-group':\n return consumeDynamicGroup({ path: subPath, fields: kind.fields, min: kind.min, max: kind.max })\n case 'widget':\n break\n default:\n return exhaust(kind)\n }\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 switch (kind.kind) {\n case '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 break\n case 'dynamic-combo':\n consumeDynamicCombo({ path: field.nameInComfy, options: kind.options, defaultKey: kind.defaultKey })\n break\n case 'dynamic-group':\n consumeDynamicGroup({ path: field.nameInComfy, fields: kind.fields, min: kind.min, max: kind.max })\n break\n case '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 break\n case 'slot':\n // a value promoted onto a slot (io-widget era subgraph): the frontend sends the literal\n if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {\n inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {\n promptName: field.nameInComfy,\n strict: false,\n })\n break\n }\n if (!fieldNamesPresent.has(field.nameInComfy) && 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 break\n default:\n exhaust(kind)\n }\n }\n\n // 2.b links\n type ParentInfo = { node: CanonicalNode; link: CanonicalLink }\n const getParentNode = (linkId: LiteGraphLinkID): ParentInfo => {\n const link = linksById.get(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 = nodesById.get(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 // 3. unlinked slots a subgraph input fed with no outer link take that input's promoted widget\n // value, read from the sibling widget it also fed, once every node is converted\n for (const node of workflow.nodes) {\n const own = prompt[String(node.id)]\n if (own == null) continue\n for (const ipt of node.inputs) {\n if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue\n const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName]\n if (value !== undefined) own.inputs[ipt.name] = value\n }\n }\n\n // 4. a required plain input absent from the prompt. ComfyUI validates per OUTPUT node\n // (execution.py validate_prompt): it runs the outputs whose upstream nodes are complete and\n // rejects the prompt only when none is. Same here: a typed error when no output survives, a\n // loud warning naming what ComfyUI will drop otherwise; never silent\n const missing = new Map<string, { node: CanonicalNode; message: string }>()\n for (const node of workflow.nodes) {\n const own = prompt[String(node.id)]\n const nodeSchema = schema.nodesByNameInComfy[node.type]\n if (own == null || nodeSchema == null) continue\n for (const field of nodeSchema.inputs) {\n if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue\n const kind = classifySchemaInput(field).kind\n if (kind !== 'slot' && kind !== 'widget') continue\n missing.set(String(node.id), {\n node,\n message: `node ${node.id}(${node.type}): required input \"${field.nameInComfy}\" (${field.typeName}) is unlinked and no value covers it`,\n })\n break\n }\n }\n if (missing.size > 0) {\n // blocked = every node downstream of a missing input, one queue walk over the consumer\n // edges: a file decides the graph depth, so no recursion here\n const consumers = new Map<string, string[]>()\n for (const [id, n] of Object.entries(prompt))\n for (const value of Object.values(n.inputs))\n if (Array.isArray(value) && typeof value[0] === 'string') {\n const list = consumers.get(value[0]) ?? []\n list.push(id)\n consumers.set(value[0], list)\n }\n const blocked = new Set(missing.keys())\n const queue = [...blocked]\n for (let head = 0; head < queue.length; head++)\n for (const next of consumers.get(queue[head] ?? '') ?? [])\n if (!blocked.has(next)) {\n blocked.add(next)\n queue.push(next)\n }\n const outputs = Object.keys(prompt).filter(\n (id) => schema.data.spec[prompt[id]?.class_type ?? '']?.output_node === true,\n )\n const dropped = outputs.filter((id) => blocked.has(id))\n const first = missing.values().next().value\n if (first != null && outputs.length > 0 && dropped.length === outputs.length)\n throw new WorkflowConvertError('missing-required-input', first.message, first.node)\n if (dropped.length > 0 || outputs.length === 0)\n console.warn(\n `🟡 [workflow] ComfyUI will skip output node(s) ${dropped.join(', ') || '(none in this graph)'}: ${[...missing.values()].map((m) => m.message).join('; ')}`,\n )\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, RawInputSpecEntry } 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'\nimport { exhaust } from 'src/utils/exhaust.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 a dynamic input wrote or dropped on purpose: the rest loop skips them */\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 switch (kind.kind) {\n case '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 case 'dynamic-group':\n this._writeDynamicGroup({\n name: i.nameInComfy,\n fields: kind.fields,\n min: kind.min,\n max: kind.max,\n provided: promptExt.inputs,\n out: inputs,\n claimed: _comboBranchKeys,\n })\n continue\n case 'widget':\n case 'slot':\n case 'dynamic-container':\n break\n default:\n exhaust(kind)\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 /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled\n * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted\n * keys are already the rows: they pass through the rest loop untouched */\n private _writeDynamicGroup(p: {\n name: string\n fields: RawInputSpecEntry[]\n min: number\n max: number\n provided: { [k: string]: unknown }\n out: { [k: string]: any }\n claimed: Set<string>\n }): void {\n const where = `${this.$schema.nodeKey}#${this.uid}`\n const raw = p.provided[p.name]\n const prefix = `${p.name}.`\n if (raw == null) {\n const hasRows = Object.keys(p.provided).some((k) => k.startsWith(prefix))\n if (!hasRows && p.min > 0)\n this.graph.recordProblem(`🔴 \"${p.name}\" on ${where} needs at least ${p.min} row(s)`)\n return\n }\n // the array wins over stray dotted keys of the same group\n for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k)\n if (!Array.isArray(raw)) {\n this.graph.recordProblem(`🔴 \"${p.name}\" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`)\n return\n }\n if (raw.length < p.min || raw.length > p.max)\n this.graph.recordProblem(\n `🔴 \"${p.name}\" on ${where} has ${raw.length} row(s), the host takes ${p.min} to ${p.max}`,\n )\n raw.forEach((row: unknown, ix) => {\n if (typeof row !== 'object' || row == null || Array.isArray(row)) {\n this.graph.recordProblem(`🔴 \"${p.name}\" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`)\n return\n }\n const given = new Map(Object.entries(row))\n for (const field of p.fields) {\n const dotted = `${p.name}.${ix}.${field.name}`\n const value = given.get(field.name)\n p.out[dotted] =\n value == null\n ? defaultValueForWidget({\n type: typeof field.type === 'string' ? field.type : 'COMBO',\n opts: field.opts,\n enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : undefined,\n })\n : this.serializeValue(dotted, value)\n given.delete(field.name)\n }\n for (const extra of given.keys())\n this.graph.recordProblem(`🔴 \"${p.name}\" row ${ix} on ${where} has no field \"${extra}\"`)\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 // dynamic group row field `decl.<row>.<field>`: the template field carries the type\n if (kind.kind === 'dynamic-group') {\n const rest = name.slice(dot + 1)\n const fieldName = rest.slice(rest.indexOf('.') + 1)\n const field = kind.fields.find((f) => f.name === fieldName)\n if (rest.includes('.') && typeof field?.type === 'string') return field.type\n }\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 {\n classifySchemaInput,\n classifyWidgetInput,\n containerInstanceSlotType,\n defaultValueForWidget,\n type InputWidgetKind,\n type RawInputSpecEntry,\n} from 'src/sdk-generator/inputWidgetKind.ts'\nimport { exhaust } from 'src/utils/exhaust.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 // target_slot = index within THIS node's litegraph inputs array,\n // not the schema input index (widget inputs are not litegraph slots)\n const pushLinked = (\n name: string,\n type: string,\n link: [string, number],\n extra: { shape?: number; widget?: boolean } = {},\n ): void => {\n const nodeUidNumber = bang(\n ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber,\n `link target node \"${link[0]}\" not found in graph`,\n )\n const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)\n const input: LiteGraphNodeInput = { name, type, link: linkId }\n if (extra.shape != null) input.shape = extra.shape\n if (extra.widget === true) input.widget = { name }\n inputs.push(input)\n }\n /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate\n * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven\n * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can\n * never disagree on the run length */\n const pushWidgetRun = (kind: Extract<InputWidgetKind, { kind: 'widget' }>, raw: unknown, opts: unknown): void => {\n widgets_values.push(...kind.prefixValues, raw)\n const phantoms = kind.consumes - 1 - kind.prefixValues.length\n for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts))\n }\n /** one input, the way the editor saves it: a widget writes its run (a linked one too, with\n * its widget socket, since the editor serializes every widget), a dynamic combo its key then\n * the selected branch inline, a group its row count then the rows, a slot its socket */\n const writeInput = (p: {\n name: string\n kind: InputWidgetKind\n typeName: string\n opts: unknown\n value: unknown\n }): void => {\n const where = `${node.$schema.nameInComfy}#${node.uid} \"${p.name}\"`\n switch (p.kind.kind) {\n case 'widget':\n if (_isLink(p.value)) {\n pushLinked(p.name, p.typeName, p.value, { widget: true })\n pushWidgetRun(p.kind, defaultValueForWidget({ type: p.typeName, opts: p.opts }), p.opts)\n } else pushWidgetRun(p.kind, p.value, p.opts)\n return\n case 'slot':\n // an unconnected slot is a litegraph socket with no link, NEVER a widget value\n if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value)\n else inputs.push({ name: p.name, type: p.typeName, link: null })\n return\n case 'dynamic-combo': {\n const kind = p.kind\n const key = typeof p.value === 'string' ? p.value : kind.defaultKey\n const option = kind.options.find((o) => o.key === key)\n if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: \"${key}\" is not one of its options`)\n widgets_values.push(key)\n for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub)\n return\n }\n case 'dynamic-container': {\n // the declaration is never a slot: each grown instance is its own\n // optional slot `decl.<instance>` (shape 7), as the editor stores it\n const type = containerInstanceSlotType(p.opts) ?? '*'\n for (const instance of p.kind.instanceNames) {\n const name = `${p.name}.${instance}`\n const value = node.json.inputs[name]\n if (value == null) continue\n const raw = node.serializeValue(name, value)\n if (!_isLink(raw))\n throw new Error(\n `🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`,\n )\n pushLinked(name, type, raw, { shape: 7 })\n }\n return\n }\n case 'dynamic-group': {\n // the editor's run: the row count, then each row's field runs (dynamicGroupWidget.ts)\n const prefix = `${p.name}.`\n let rows = 0\n for (const key of Object.keys(node.json.inputs)) {\n if (!key.startsWith(prefix)) continue\n const row = Number(key.slice(prefix.length).split('.')[0])\n if (Number.isInteger(row) && row >= rows) rows = row + 1\n }\n widgets_values.push(rows)\n for (let row = 0; row < rows; row++)\n for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field)\n return\n }\n default:\n exhaust(p.kind)\n }\n }\n /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent\n * value is the widget's schema default rather than serializeValue's */\n const writeSub = (name: string, sub: RawInputSpecEntry): void => {\n const typeName = typeof sub.type === 'string' ? sub.type : 'COMBO'\n const raw: unknown = node.json.inputs[name]\n writeInput({\n name,\n kind: classifyWidgetInput({ name, type: sub.type, opts: sub.opts }),\n typeName,\n opts: sub.opts,\n value: raw === undefined ? defaultValueForWidget({ type: typeName, opts: sub.opts }) : raw,\n })\n }\n for (const ipt of node.$schema.inputs) {\n const kind = classifySchemaInput(ipt)\n // a dynamic input's own key is never a schema-default value: read it raw\n const raw = node.json.inputs[ipt.nameInComfy]\n const value = kind.kind === 'widget' || kind.kind === 'slot' ? node.serializeValue(ipt.nameInComfy, raw) : raw\n writeInput({ name: ipt.nameInComfy, kind, typeName: ipt.typeName, opts: ipt.opts, value })\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\n/** the editor's control widget is a combo (fixed, increment, decrement, randomize):\n * a config naming a mode keeps it, anything else is `fixed`, the seed the code pinned */\nconst controlMode = (opts: unknown): string => {\n const mode = typeof opts === 'object' && opts != null ? Reflect.get(opts, 'control_after_generate') : null\n return typeof mode === 'string' ? mode : 'fixed'\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","// 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 { IsEqual, 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 // null for a cached node whose cache entry holds no ui payload (asset_enrichment.emit_cached_output)\n output: '_WsMsgExecutedOutput | null',\n prompt_id: 'PromptID',\n },\n _WsMsgExecutedOutput: {\n 'previews?': [{ filepath: 'string' }, '[]'],\n 'images?': 'ComfyImageInfo[]',\n // SaveAudio*, PreviewAudio: same file triple as an image\n 'audio?': 'ComfyImageInfo[]',\n // VideoHelperSuite's VHS_VideoCombine, and savers that name their list `video`\n 'video?': 'ComfyImageInfo[]',\n 'gifs?': '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 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 // execution.py sends list(current_outputs): the ids of the nodes that already have outputs\n current_outputs: 'ComfyNodeID[]',\n },\n WsMsgExecutionError: {\n type: \"'execution_error'\",\n data: '_WsMsgExecutionErrorData',\n },\n\n // an interrupt (POST /interrupt) ends the prompt with this and no execution_success\n _WsMsgExecutionInterruptedData: {\n prompt_id: 'PromptID',\n node_id: 'ComfyNodeID',\n node_type: 'string',\n executed: 'ComfyNodeID[]',\n },\n WsMsgExecutionInterrupted: {\n type: \"'execution_interrupted'\",\n data: '_WsMsgExecutionInterruptedData',\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 | WsMsgExecutionInterrupted | 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; metadata: unknown }\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 WsMsgExecutionInterrupted = typeof types.WsMsgExecutionInterrupted.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\n\n/** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */\nexport const ROUTED_WS_EVENT_TYPES = [\n 'status',\n 'manager-terminal-feedback',\n 'logs',\n 'execution_start',\n 'execution_cached',\n 'executing',\n 'progress',\n 'progress_state',\n 'executed',\n 'execution_error',\n 'execution_interrupted',\n 'execution_success',\n] as const\ntrue satisfies IsEqual<(typeof ROUTED_WS_EVENT_TYPES)[number], WsMsg['type']>\n\n/** events a server or a custom node sends by design that comfy-ts has no use for: dropped\n * before validation, never logged (architecture.md, ws events) */\nexport const IGNORED_WS_EVENT_TYPES = [\n // ComfyUI server.py: only the reply to a client that opens with its own feature_flags\n 'feature_flags',\n // ComfyUI app/agent_host.py: the local agent host's state, broadcast\n 'agent_status',\n // ComfyUI app/asset_export.py: an export task's progress, broadcast\n 'asset_export',\n // ComfyUI app/assets/seeder.py: the asset index scan, broadcast while the assets system is on\n 'assets.seed.started',\n 'assets.seed.progress',\n 'assets.seed.fast_complete',\n 'assets.seed.enrich_complete',\n 'assets.seed.completed',\n 'assets.seed.cancelled',\n 'assets.seed.error',\n 'assets.seed.paused',\n 'assets.seed.resumed',\n // ComfyUI-Manager (V3.x legacy and 4.x): install queue progress, broadcast\n 'cm-queue-status',\n 'cm-api-try-install-customnode',\n // ComfyUI-Manager 4.x glob/manager_server.py: one task of the install queue\n 'cm-task-started',\n 'cm-task-completed',\n // ComfyUI-Crystools: the resource monitor, about once a second\n 'crystools.monitor',\n] as const\n\nconst ROUTED_SET: ReadonlySet<string> = new Set(ROUTED_WS_EVENT_TYPES)\nconst IGNORED_SET: ReadonlySet<string> = new Set(IGNORED_WS_EVENT_TYPES)\nexport const isRoutedWsEventType = (t: string): boolean => ROUTED_SET.has(t)\nexport const isIgnoredWsEventType = (t: string): boolean => IGNORED_SET.has(t)\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 = workflow.dry ? this.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 = workflow.dry ? this.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","// the three media a var can take and an output can be. PURE + dependency-free: the web bundle\n// imports it to decide which var a dropped output may land on\n\nexport type MediaKind = 'image' | 'audio' | 'video'\n\nexport const MEDIA_KINDS: readonly MediaKind[] = ['image', 'audio', 'video']\n\n/** picker defaults per kind, lowercase without dots */\nexport const DEFAULT_MEDIA_EXTENSIONS: Record<MediaKind, readonly string[]> = {\n image: ['png', 'jpg', 'jpeg', 'webp', 'gif'],\n audio: ['wav', 'flac', 'mp3', 'ogg', 'opus', 'm4a'],\n video: ['mp4', 'webm', 'mov', 'mkv', 'm4v'],\n}\n\nconst MIMES: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n flac: 'audio/flac',\n mp3: 'audio/mpeg',\n opus: 'audio/ogg',\n ogg: 'audio/ogg',\n wav: 'audio/wav',\n m4a: 'audio/mp4',\n aac: 'audio/aac',\n mp4: 'video/mp4',\n m4v: 'video/mp4',\n webm: 'video/webm',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n avi: 'video/x-msvideo',\n}\n\n/** video containers an output node can name. An animated webp or gif is an IMAGE: the\n * extension decides, never the `animated` flag */\nconst VIDEO_EXTENSIONS = new Set(['mp4', 'm4v', 'webm', 'mov', 'mkv', 'avi'])\n\nexport function extensionOf(filename: string): string {\n const dot = filename.lastIndexOf('.')\n return dot < 0 ? '' : filename.slice(dot + 1).toLowerCase()\n}\n\nexport function isVideoFilename(filename: string): boolean {\n return VIDEO_EXTENSIONS.has(extensionOf(filename))\n}\n\nexport function mediaMime(filename: string): string {\n return MIMES[extensionOf(filename)] ?? 'application/octet-stream'\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 WsMsgExecutionInterrupted,\n WsMsgExecutionSuccess,\n} from 'src/runner/ComfyWsApi.ts'\nimport { MediaImage } from 'src/runner/MediaImage.ts'\nimport { isVideoFilename, mediaMime } from 'src/runner/mediaKinds.ts'\nimport { previewMetadataNodeId } from 'src/runner/wsBinaryFrame.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 | WsMsgExecutionInterrupted | null\n status?: ComfyExecutionStatus | null\n}\n\n/** one audio file an output node published, downloaded as the server wrote it.\n * `absPath` is null when saving is off: `bytes` is then the only copy */\nexport type ComfyAudioOutput = {\n nodeId: ComfyNodeId\n filename: string\n mime: string\n bytes: Uint8Array\n absPath: AbsolutePath | null\n}\n\n/** one video file an output node published (SaveVideo, SaveWEBM, VHS_VideoCombine), same\n * shape and same retrieval as an audio file */\nexport type ComfyVideoOutput = ComfyAudioOutput\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\n/** one live preview frame of a run: the image a sampler is forming, once per step */\nexport type ExecutionPreview = {\n promptId: PromptID\n /** the image as ComfyUI encoded it, jpeg or png */\n bytes: Uint8Array\n mime: string\n /** the node that sent the frame: the frame's own metadata when it names one (type 4 frames),\n * else the node executing when it arrived. Null when neither is known */\n nodeId: ComfyNodeId | null\n /** that node's class name in the sent prompt (`KSampler`), null when unknown */\n nodeName: string | null\n /** that node's own counter when the frame arrived (sampler step of total), null when unknown */\n step: { value: number; max: number } | null\n /** the raw metadata json of a type 4 frame (`node_id`, `prompt_id`, …), null on a type 1 frame */\n metadata: unknown\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 onPreview?: Maybe<(p: ExecutionPreview) => 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.onPreview = init.onPreview ?? 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 /** called on every live preview frame of this run. Null = frames are never decoded for it */\n onPreview: Maybe<(p: ExecutionPreview) => 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.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`)\n if (this.videos.length > 0) outputs.push(`${this.videos.length} video(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, else a preview\n if (msg.type === 'binary_preview_frame') {\n if (this.wsOutputNodeExecuting) this.onWsImageOutput({ bytes: msg.bytes, mime: msg.mime })\n else this.onPreviewFrame(msg)\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 // the server sends no execution_success after an interrupt: this message ends the run\n else if (msg.type === 'execution_interrupted') return void this._finish({ status: 'Failure', error: 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 // a video file rides `images` (SaveVideo), `video` or `gifs` (VideoHelperSuite): the\n // extension decides, so an animated webp or gif stays an image\n const out = msg.data.output\n // a loader (LoadVideo) echoes the file it READ, typed 'input': a preview, never an output\n const listed = [...(out?.images ?? []), ...(out?.video ?? []), ...(out?.gifs ?? [])].filter(\n (f) => f.type !== 'input',\n )\n for (const video of listed.filter((f) => isVideoFilename(f.filename))) {\n this.pendingPromises.push(\n this.retrieveFile('video', video, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to retrieve ${video.filename}:`, e)\n this.videoErrors.push({ video, error: e })\n }),\n )\n }\n const images = listed.filter((f) => !isVideoFilename(f.filename))\n if (images.length > 0) {\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 for (const audio of msg.data.output?.audio ?? []) {\n this.pendingPromises.push(\n this.retrieveFile('audio', audio, promptNodeID).catch((e: unknown) => {\n console.error(`🔴 failed to retrieve ${audio.filename}:`, e)\n this.audioErrors.push({ audio, error: e })\n }),\n )\n }\n }\n private pendingPromises: Promise<void>[] = []\n\n /** audio retrievals that failed (their files are missing from `audios`) */\n audioErrors: { audio: ComfyImageInfo; error: unknown }[] = []\n\n /** audio files retrieved for this execution, in arrival order (final once `done` resolves) */\n audios: ComfyAudioOutput[] = []\n\n /** video retrievals that failed (their files are missing from `videos`) */\n videoErrors: { video: ComfyImageInfo; error: unknown }[] = []\n\n /** video files retrieved for this execution, in arrival order (final once `done` resolves) */\n videos: ComfyVideoOutput[] = []\n\n private retrieveFile = async (\n kind: 'audio' | 'video',\n info: ComfyImageInfo,\n promptNodeID: ComfyNodeId,\n ): Promise<void> => {\n const response = await this.host.fetchFile('/view?' + new URLSearchParams(info).toString())\n const bytes = new Uint8Array(await response.arrayBuffer())\n const mime = mediaMime(info.filename)\n const list = kind === 'audio' ? this.audios : this.videos\n const sf = this.save\n if (sf == null) {\n list.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: null })\n return\n }\n const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs['filename_prefix']\n const written = await this.encodeAndWrite({\n bytes,\n // never re-encoded: `save.format` is an image setting\n sf: { ...sf, format: 'raw' },\n filenamePrefix: typeof promptPrefix === 'string' ? promptPrefix : undefined,\n subfolder: info.subfolder,\n filename: info.filename,\n })\n list.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: written.path })\n }\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 /** @internal a live preview frame of this run; never an output (the host routes ws saver frames\n * to onWsImageOutput before they get here) */\n onPreviewFrame(p: { bytes: Uint8Array; mime: string; metadata: unknown }): void {\n const listener = this.onPreview\n if (listener == null) return\n const current = this.workflow.currentExecutingNode\n const named = previewMetadataNodeId(p.metadata)\n const nodeId: ComfyNodeId | null = named ?? current?.uid ?? null\n const apiJson = this.snapshot?.apiJson ?? this.workflow.apiJson\n const counter = current != null && current.uid === nodeId ? current.progress : null\n listener({\n promptId: this.data.id,\n bytes: p.bytes,\n mime: p.mime,\n nodeId,\n nodeName: nodeId != null ? (apiJson[nodeId]?.class_type ?? null) : null,\n step: counter != null ? { value: counter.value, max: counter.max } : null,\n metadata: p.metadata,\n })\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 ExecutionPreview, 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 /** called on every live preview frame of this run (the image a sampler is forming). Opt in:\n * without it no frame is decoded for the run. ComfyUI sends frames only when launched with\n * `--preview-method`, see `host.fetchPreviewMethod()` */\n onPreview?: (p: ExecutionPreview) => 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 /** a dry build: media loads name the local file by its hash and upload nothing, so a graph\n * can be built only to be read (serve derives workflow tags this way) */\n dry = false\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 onPreview: p.onPreview,\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 { exhaust } from 'src/utils/exhaust.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/** one dynamic-group row as an object type: a field is optional when it has a default or sits in\n * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */\nconst dynamicGroupRow = (fields: RawInputSpecEntry[]): string => {\n const members = fields.map((e) => {\n const opts = isRecord(e.opts) ? e.opts : null\n const optional = !e.required || opts?.['default'] !== undefined\n return `${escapeJSKey(e.name)}${optional ? '?' : ''}: ${branchInputType(e)}`\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 /** one row type per dynamic group, named once so a long COMBO union is not printed twice */\n const groupRows: [key: string, row: string][] = []\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 switch (kind.kind) {\n case '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 case '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 case 'dynamic-group': {\n // an array of row objects, the backend's own list[dict] value; ComfyNode\n // expands it to the dotted `<decl>.<row>.<field>` prompt keys\n const rowKey = `${n.nodeKey}.${i.nameInComfy}`\n groupRows.push([rowKey, dynamicGroupRow(kind.fields)])\n const row = `GroupRow[${JSON.stringify(rowKey)}]`\n p(` /** min=${kind.min} max=${kind.max} rows */`)\n if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`)\n else p(` ${i.nameInComfyEscaped}?: ${row}[]`)\n continue\n }\n case 'widget':\n case 'slot':\n break\n default:\n exhaust(kind)\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 if (groupRows.length > 0) {\n p(`/** one row of each dynamic group input, keyed \\`<node>.<input>\\` */`)\n p(`interface GroupRow {`)\n b.indent()\n for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`)\n b.deindent()\n p('}')\n p('')\n }\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 ?? n.nameInComfy}\" 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 // dynamic group: row fields are typed by their own slot types, and the group is\n // required exactly when it needs rows (upstream counts min even on an optional input)\n if (widgetKind?.kind === 'dynamic-group') {\n for (const entry of widgetKind.fields) {\n if (typeof entry.type === 'string') this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type))\n }\n }\n const required =\n widgetKind?.kind === 'dynamic-group' ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer\n\n node.inputs.push({\n slotName: inputSlotName,\n required,\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 | null)[]',\n output_name: 'string[]',\n name: 'string',\n display_name: 'string | null',\n description: 'string',\n /** */\n python_module: 'string',\n category: 'string',\n output_node: 'boolean',\n 'output_tooltips?': '(string | null)[]',\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 // a trailing extra entry (kjnodes EndRecordCUDAMemoryHistory: a description string); ComfyUI\n // and its frontend read [0] and [1] only, so do we\n ComfyInputSpecAlt4: ['ComfyInputType', 'ComfyInputOpts', 'unknown'],\n ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,\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 // number[] and object: widget defaults like a size pair, a curve, a trim window\n 'default?': 'boolean | number | string | null | number[] | object',\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","/**\n * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),\n * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).\n * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.\n */\nimport { type } from 'arktype'\nimport type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'\nimport type { ComfyManagerAPIModelList } from 'src/manager/types/ComfyManagerAPIModelList.ts'\nimport type { ComfyManagerAPIPluginList } from 'src/manager/types/ComfyManagerAPIPluginList.ts'\nimport type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'\nimport type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'\n\n/** the part of the registry the views read */\nexport type ManagerMirror = {\n plugins_byTitle: ReadonlyMap<KnownComfyPluginTitle, ComfyManagerPluginInfo>\n plugins_byFile: ReadonlyMap<string, ComfyManagerPluginInfo>\n plugins_byNodeKey: ReadonlyMap<string, readonly ComfyManagerPluginInfo[]>\n /** every model row: upstream ships a few names twice, with different files */\n modelRows: readonly ComfyManagerModelInfo[]\n}\n\n/** `GET customnode/installed`: a disk scan, keyed by directory */\nexport const InstalledPacks_ark = type.Record(\n 'string',\n type({ 'cnr_id?': 'string | null', 'aux_id?': 'string | null', enabled: 'boolean' }),\n)\nexport type InstalledPacks = typeof InstalledPacks_ark.infer\n\n/** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */\nexport const PackMappings_ark = type.Record('string', type(['string[]', { 'title_aux?': 'string' }]))\nexport type PackMappings = typeof PackMappings_ark.infer\n\n/** `https://github.com/Owner/Repo.git/` → `owner/repo` */\nexport const repoPath = (url: string): string =>\n url\n .toLowerCase()\n .replace(/\\/+$/, '')\n .replace(/\\.git$/, '')\n .split('/')\n .slice(-2)\n .join('/')\n\n/** one installed pack, joined to the mirror when the data allows it */\nexport type AttributedPack = { enabled: boolean; repo: string | null; title: string | null; id: string }\n\n/** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */\nexport const attributePacks = (installed: InstalledPacks, mappings: PackMappings): AttributedPack[] => {\n // registry ids are case insensitive: the mappings keep the registry's casing, the scan lowercases\n const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]))\n return Object.entries(installed).map(([dir, p]) => {\n const aux = p.aux_id ?? null\n const cnr = p.cnr_id != null && p.cnr_id !== '' ? p.cnr_id : null\n const repo = aux != null && aux.includes('/') ? repoPath(aux) : null\n const title = cnr != null ? (titleById.get(cnr.toLowerCase()) ?? null) : null\n return { enabled: p.enabled, repo, title, id: cnr ?? aux ?? dir }\n })\n}\n\n/** is this mirror row among the attributed packs, enabled? */\nexport const packIsInstalled = (\n packs: AttributedPack[],\n plugin: { title: string; files: string[]; reference: string },\n): boolean => {\n const repo = repoPath(plugin.files[0] ?? plugin.reference)\n return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title))\n}\n\nexport const buildPluginView = (p: {\n mirror: ManagerMirror\n installed: InstalledPacks\n mappings: PackMappings\n}): { list: ComfyManagerAPIPluginList; unattributed: string[] } => {\n const packs = attributePacks(p.installed, p.mappings)\n const plugins = [...p.mirror.plugins_byTitle.values()]\n const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)))\n const mirrorTitles = new Set<string>(plugins.map((x) => x.title))\n const joins = (x: AttributedPack): boolean =>\n (x.repo != null && mirrorRepos.has(x.repo)) || (x.title != null && mirrorTitles.has(x.title))\n // a git clone whose repo the mirror lacks is no mirror row; an enabled pack known by no repo that joins\n // nothing could be one (a disabled one reads `False` whichever row it is, like a missing one)\n const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x))\n const serverTitles = new Set(\n Object.values(p.mappings).flatMap((v) => (v[1].title_aux != null ? [v[1].title_aux] : [])),\n )\n const custom_nodes: ComfyManagerAPIPluginList['custom_nodes'] = []\n for (const plugin of plugins) {\n const repo = repoPath(plugin.files[0] ?? plugin.reference)\n const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title)\n if (joined.some((x) => x.enabled)) custom_nodes.push({ title: plugin.title, installed: 'True' })\n // an unattributed registry install can only be a row the server's mappings do not name\n else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue\n else custom_nodes.push({ title: plugin.title, installed: 'False' })\n }\n return { list: { chanel: 'default', custom_nodes }, unattributed: unattributed.map((x) => x.id) }\n}\n\n/** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */\nconst DEFAULT_FOLDER_BY_TYPE: Record<string, string> = {\n checkpoints: 'checkpoints',\n checkpoint: 'checkpoints',\n unclip: 'checkpoints',\n text_encoders: 'text_encoders',\n clip: 'text_encoders',\n vae: 'vae',\n lora: 'loras',\n 't2i-adapter': 'controlnet',\n 't2i-style': 'controlnet',\n controlnet: 'controlnet',\n clip_vision: 'clip_vision',\n gligen: 'gligen',\n upscale: 'upscale_models',\n embedding: 'embeddings',\n embeddings: 'embeddings',\n unet: 'diffusion_models',\n diffusion_model: 'diffusion_models',\n}\n\n/** what core `get_filename_list` lists in the standard folders */\nconst LISTED_EXTENSIONS = ['.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft']\n\n/**\n * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.\n * The Manager's own check accepts the folder root as well as the `save_path` sub folder.\n */\nexport const modelLocation = (m: ComfyManagerModelInfo): { folder: string; files: string[] } | null => {\n if (m.filename === '<huggingface>' || /[\\\\/:]/.test(m.filename)) return null\n if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null\n if (m.save_path === 'default') {\n const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()]\n return folder == null ? null : { folder, files: [m.filename] }\n }\n const parts = m.save_path\n .replaceAll('\\\\', '/')\n .split('/')\n .filter((s) => s !== '')\n const folder = parts[0]\n if (folder == null || folder === 'custom_nodes' || parts.includes('..')) return null\n const sub = [...parts.slice(1), m.filename].join('/')\n return { folder, files: sub === m.filename ? [m.filename] : [m.filename, sub] }\n}\n\nexport const buildModelView = (p: {\n models: readonly ComfyManagerModelInfo[]\n /** registered folder → its relative file paths, for the folders core lists */\n files: ReadonlyMap<string, readonly string[]>\n}): ComfyManagerAPIModelList => {\n const listed = new Map(\n [...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll('\\\\', '/')))]),\n )\n const statusOf = (m: ComfyManagerModelInfo): 'True' | 'False' | null => {\n const at = modelLocation(m)\n const files = at == null ? null : listed.get(at.folder)\n if (at == null || files == null) return null\n return at.files.some((f) => files.has(f)) ? 'True' : 'False'\n }\n const byName = new Map<string, ComfyManagerModelInfo[]>()\n for (const m of p.models) byName.set(m.name, [...(byName.get(m.name) ?? []), m])\n const models: ComfyManagerAPIModelList['models'] = []\n for (const rows of byName.values()) {\n // a name shipped twice with different files is decided only when every row agrees\n const statuses = new Set(rows.map(statusOf))\n const first = rows[0]\n const installed = statuses.size === 1 ? [...statuses][0] : null\n if (first == null || installed == null) continue\n models.push({\n name: first.name,\n installed,\n filename: first.filename,\n save_path: first.save_path,\n base: first.base,\n })\n }\n return { models }\n}\n\n/** the folders the views need listed */\nexport const modelFolders = (models: Iterable<ComfyManagerModelInfo>): Set<string> =>\n new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []))\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 'filename?': 'string',\n 'save_path?': 'string',\n 'base?': 'string',\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\n/** one pack as `GET customnode/getlist` serves it (Manager V3 and 4.x legacy UI); the install body is this row */\nexport type ComfyManagerAPIPack = typeof ComfyManagerAPIPack_ark.infer\nexport const ComfyManagerAPIPack_ark = type({\n title: type.string.as<KnownComfyPluginTitle>(),\n 'id?': 'string',\n 'files?': 'string[]',\n 'repository?': 'string',\n 'version?': 'string',\n 'state?': 'string',\n 'update-state?': 'string',\n})\n\n/** the getlist wire shape since Manager V3: packs keyed by their install key */\nexport type ComfyManagerAPIPackList = typeof ComfyManagerAPIPackList_ark.infer\nexport const ComfyManagerAPIPackList_ark = type({\n channel: 'string',\n node_packs: type.Record('string', ComfyManagerAPIPack_ark),\n})\n","/** 🔶 NAMING DISCLAIMER: I call a \"custom node package\" => \"PLUGIN\" */\n\nimport { type ArkErrors, type Type, type } from 'arktype'\nimport { nanoid } from 'nanoid'\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 {\n attributePacks,\n buildModelView,\n buildPluginView,\n type InstalledPacks,\n InstalledPacks_ark,\n type ManagerMirror,\n modelFolders,\n type PackMappings,\n PackMappings_ark,\n packIsInstalled,\n repoPath,\n} from 'src/manager/installedView.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 ComfyManagerAPIPackList,\n ComfyManagerAPIPackList_ark,\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, logSuccess } from 'src/utils/log.ts'\nimport { softValidate } from 'src/utils/softValidate.ts'\nimport type { PluginInstallStatus, Requirements } from 'src/host/Requirements.ts'\n\n/**\n * the three ComfyUI-Manager servers in the field (agent/architecture.md, Manager HTTP client):\n * `v3` the legacy custom node (bare routes), `v4-legacy-ui` the pip package under\n * `--enable-manager-legacy-ui` (/v2), `v4` the pip package with its default ui (/v2, no lists)\n */\nexport type ManagerGeneration = 'v3' | 'v4-legacy-ui' | 'v4'\nexport type ManagerApi = { generation: ManagerGeneration; version: string }\n\n/** install waits poll the queue; `pollGraceMs`: how long the poll survives a host that does not answer */\nexport type ManagerTiming = { pollMs: number; installTimeoutMs: number; pollGraceMs: number }\nexport const MANAGER_TIMING: ManagerTiming = { pollMs: 1000, installTimeoutMs: 60 * 60_000, pollGraceMs: 120_000 }\n\n/** `unknown`: we lost sight of the task, the Manager may still be installing (agent/architecture.md) */\nexport type InstallOutcome = 'installed' | 'failed' | 'unknown'\n\n/** an install the host refused or reported failed: ends the wait at once */\nclass InstallFailed extends Error {}\n/** we lost sight of the task: the outcome is not known */\nclass OutcomeUnknown extends Error {}\n\ntype ManagerRoute =\n | '/manager/version'\n | '/manager/reboot'\n | '/manager/terminal'\n | '/customnode/getlist'\n | '/externalmodel/getlist'\n | '/customnode/installed'\n | '/customnode/getmappings'\n | '/manager/queue/install'\n | '/manager/queue/batch'\n | '/manager/queue/task'\n | '/manager/queue/install_model'\n | '/manager/queue/start'\n | '/manager/queue/status'\n | '/manager/queue/history'\n\n/** what each generation does NOT serve (history means the `?ui_id=` form) */\nconst NOT_SERVED: Record<ManagerGeneration, ManagerRoute[]> = {\n v3: ['/manager/queue/batch', '/manager/queue/task', '/manager/queue/history'],\n 'v4-legacy-ui': ['/manager/queue/install', '/manager/queue/task', '/manager/queue/history', '/manager/terminal'],\n v4: [\n '/customnode/getlist',\n '/externalmodel/getlist',\n '/manager/queue/install',\n '/manager/queue/batch',\n '/manager/terminal',\n ],\n}\n\n/** everything that differs between generations beyond a route's spelling */\ntype ManagerStrategy = {\n fetchPlugins: (mode: ComfyManagerAPIFetchPolicy, skipUpdate: boolean) => Promise<ComfyManagerAPIPluginList>\n fetchModels: () => Promise<ComfyManagerAPIModelList>\n /** resolves with the id the host installs by, when it is not the pack's own row */\n enqueuePlugin: (plugin: ComfyManagerPluginInfo, uiId: string) => Promise<string | undefined>\n /** wait until the queued task ran: resolves when it succeeded, throws with why when not */\n settle: (what: string, uiId: string, landed: () => Promise<boolean | null>, sentId?: string) => Promise<void>\n}\n\nconst QueueStatus_ark = type({\n is_processing: 'boolean',\n 'pending_count?': 'number',\n 'total_count?': 'number',\n 'done_count?': 'number',\n})\nconst TaskHistory_ark = type({\n history: { 'status?': { status_str: 'string', 'messages?': 'string[]' }, 'result?': 'string' },\n})\nconst ModelFolders_ark = type('string[]')\n\nconst errorText = (e: unknown): string => (e instanceof Error ? e.message : String(e))\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 public timing: ManagerTiming = { ...MANAGER_TIMING },\n /** the mirror the lists are joined to; the registry by default */\n public mirror: () => ManagerMirror = () => comfyts.registry,\n ) {}\n\n get registry(): ComfyRegistry {\n return comfyts.registry\n }\n\n /** identifies install tasks of this client in the Manager queue (4.x requires one) */\n readonly clientId: string = `comfy-ts-${nanoid(8)}`\n\n // generation ------------------------------------------------------------------------\n private _api: Promise<ManagerApi> | null = null\n\n /** which Manager answers: probed once, remembered, forgotten on failure and on reboot */\n api = (): Promise<ManagerApi> => {\n if (this._api == null) {\n const probe = this.probeApi()\n this._api = probe\n probe.catch(() => {\n if (this._api === probe) this._api = null\n })\n }\n return this._api\n }\n\n private probeApi = async (): Promise<ManagerApi> => {\n const v4 = await this.host.fetch('/v2/manager/version')\n if (v4.ok) {\n const version = (await v4.text()).trim()\n const ui = await this.host.fetch('/v2/manager/is_legacy_manager_ui')\n if (!ui.ok) {\n logError(\n `ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`,\n )\n return { generation: 'v4', version }\n }\n const flag: unknown = await ui.json()\n const legacy =\n typeof flag === 'object' &&\n flag != null &&\n 'is_legacy_manager_ui' in flag &&\n flag.is_legacy_manager_ui === true\n return { generation: legacy ? 'v4-legacy-ui' : 'v4', version }\n }\n const v3 = await this.host.fetch('/manager/version')\n if (v3.ok) return { generation: 'v3', version: (await v3.text()).trim() }\n throw new Error(\n `🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} ` +\n `(GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`,\n )\n }\n\n /** the one place a Manager route gets its generation's spelling */\n private route = (api: ManagerApi, route: ManagerRoute, query: string = ''): string => {\n if (NOT_SERVED[api.generation].includes(route))\n throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`)\n return `${api.generation === 'v3' ? '' : '/v2'}${route}${query}`\n }\n\n /** the one place the generations differ beyond a route's spelling */\n private strategy = (api: ManagerApi): ManagerStrategy => {\n switch (api.generation) {\n case 'v3':\n return {\n fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),\n fetchModels: () => this.listedModels(api),\n enqueuePlugin: (plugin, uiId) =>\n this.enqueueListedPlugin(api, plugin, uiId, (body) =>\n this.post(this.route(api, '/manager/queue/install'), body),\n ),\n settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed),\n }\n case 'v4-legacy-ui':\n return {\n fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),\n fetchModels: () => this.listedModels(api),\n enqueuePlugin: (plugin, uiId) =>\n this.enqueueListedPlugin(api, plugin, uiId, async (body) => {\n const route = this.route(api, '/manager/queue/batch')\n const res = await this.post(route, { install: [body] })\n const failed = typeof res === 'object' && res != null && 'failed' in res ? res.failed : null\n if (Array.isArray(failed) && failed.length > 0)\n throw new Error(\n `POST ${route} refused ${JSON.stringify(failed)}: the batch reply carries ids only, ` +\n `the ComfyUI console says why (a 4.x security policy refusal is the usual one)`,\n )\n }),\n settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed),\n }\n case 'v4':\n return {\n fetchPlugins: () => this.installedPluginView(api),\n fetchModels: () => this.installedModelView(),\n enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),\n settle: (what, uiId, landed, sentId) => this.settleByHistory(api, what, uiId, landed, sentId),\n }\n }\n }\n\n // -----------\n configureLogging = async (mi: boolean): Promise<string> => {\n const api = await this.api()\n const route = this.route(api, '/manager/terminal', `?mode=${mi}`)\n const response = await this.host.fetch(route)\n const text = await response.text()\n if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`)\n return text\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, and a GET\n * there answers 404 while the process keeps running. Both verbs are tried so a pre-V3\n * Manager still reboots, and anything that is neither a disconnect nor a 404 throws with\n * what the host actually said. The process may come back with another Manager, so the\n * remembered generation is dropped.\n */\n restartComfyUI = async (): Promise<void> => {\n const api = await this.api()\n this._api = null\n const route = this.route(api, '/manager/reboot')\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(route, { 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 (${route}: ${refusals.join(', ')}) — ` +\n `ComfyUI-Manager ${api.version} is not there any more, or its reboot route moved again`,\n )\n }\n\n // LISTS ----------------------------------------------------------------------------\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 modelList: Maybe<ComfyManagerAPIModelList> = null\n\n /** what the host has of our model mirror; a model absent from the list reads `unknown` */\n fetchModels = async (): Promise<ComfyManagerAPIModelList> => {\n return this.strategy(await this.api()).fetchModels()\n }\n\n fetchLogs = (): Promise<any> => {\n return this.getJSON<unknown>('/internal/logs')\n }\n\n /** true only for a KNOWN install: false is \"not known to be installed\" (missing OR undecided), see `getModelStatus` */\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 /** queue the install, wait until the Manager ran it; true only once the model is verified installed (`installModelOutcome` tells failed from unknown) */\n installModel = async (model: ComfyManagerModelInfo): Promise<boolean> =>\n (await this.installModelOutcome(model)) === 'installed'\n\n installModelOutcome = async (model: ComfyManagerModelInfo): Promise<InstallOutcome> => {\n this.modelsBeeingInstalled.add(model.name)\n try {\n return await this.runInstall(`model \"${model.name}\"`, {\n enqueue: async (api, uiId) => {\n const body = { ...model, ui_id: uiId, client_id: this.clientId }\n await this.post(this.route(api, '/manager/queue/install_model'), body)\n },\n landed: async (s) => {\n // the triple the Manager's own install whitelist matches on\n const row = (await s.fetchModels()).models.find(\n (x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base,\n )\n return row == null ? null : row.installed === 'True'\n },\n })\n } finally {\n this.modelsBeeingInstalled.delete(model.name)\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 /** true only for a KNOWN install: false is \"not known to be installed\" (missing OR undecided), see `getPluginStatus` */\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 // REQUIREMENTS: undecided is not missing --------------------------------------------\n /** one requirement against the fetched lists; `unknown` when they cannot say, null when the mirror does not know it */\n requirementStatus = (req: Requirements): PluginInstallStatus | null => {\n const mirror = this.mirror()\n const packs = ((): readonly ComfyManagerPluginInfo[] | null => {\n if (req.type === 'customNodesByNodeKey') return mirror.plugins_byNodeKey.get(req.nodeName) ?? []\n if (req.type === 'customNodesByTitle') return [mirror.plugins_byTitle.get(req.title)].filter((x) => x != null)\n if (req.type === 'customNodesByURI') return [mirror.plugins_byFile.get(req.uri)].filter((x) => x != null)\n return null\n })()\n if (packs == null) return req.type === 'modelInManager' ? this.getModelStatus(req.modelName) : null\n if (packs.length === 0) return req.type === 'customNodesByNodeKey' ? 'unknown' : null\n const statuses = packs.map((x) => this.getPluginStatus(x.title))\n if (statuses.some((x) => x === 'installed' || x === 'update-available')) return 'installed'\n return statuses.every((x) => x === 'not-installed') ? 'not-installed' : 'unknown'\n }\n\n /** `missing`: known not installed, the only requirements an install flow may queue; `undecided`: the lists cannot say */\n checkRequirements = (requirements: Requirements[]): { missing: Requirements[]; undecided: Requirements[] } => {\n const out: { missing: Requirements[]; undecided: Requirements[] } = { missing: [], undecided: [] }\n for (const req of requirements) {\n if (req.optional) continue\n const status = this.requirementStatus(req)\n if (status === 'not-installed') out.missing.push(req)\n else if (status === 'unknown' || status === 'error') out.undecided.push(req)\n }\n return out\n }\n\n /** false only when a requirement is known missing; an undecided one passes with a warning */\n matchRequirements = (requirements: Requirements[]): boolean => {\n const check = this.checkRequirements(requirements)\n if (check.undecided.length > 0)\n logError(\n `requirements the host lists cannot decide, read as present: ${check.undecided.map((r) => JSON.stringify(r)).join(', ')}` +\n (this.pluginList == null || this.modelList == null\n ? ' (the lists are not fetched: call fetchPluginsAndModels)'\n : ''),\n )\n return check.missing.length === 0\n }\n\n /** the host's plugin list in the public `custom_nodes` shape, titled like our mirror; absent = `unknown` */\n fetchPlugins = async (\n /** @default: 'cache' */\n mode: ComfyManagerAPIFetchPolicy = 'cache',\n /** @default: true */\n skipUpdate: boolean = true,\n ): Promise<ComfyManagerAPIPluginList> => {\n return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate)\n }\n\n /** queue the install, wait until the Manager ran it; true only once the pack is verified installed (`installPluginOutcome` tells failed from unknown) */\n installPlugin = async (plugin: ComfyManagerPluginInfo): Promise<boolean> =>\n (await this.installPluginOutcome(plugin)) === 'installed'\n\n installPluginOutcome = async (plugin: ComfyManagerPluginInfo): Promise<InstallOutcome> => {\n return this.runInstall(`plugin \"${plugin.title}\"`, {\n enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),\n landed: async (_s, api) => {\n const data = await this.installedData(api)\n return packIsInstalled(attributePacks(data.installed, data.mappings), plugin)\n },\n })\n }\n\n // LIST BUILDERS: one per source, picked by the strategy -------------------------------\n /** the Manager's own getlist (v3, v4 legacy ui), normalized */\n private listedPlugins = async (\n api: ManagerApi,\n mode: ComfyManagerAPIFetchPolicy,\n skipUpdate: boolean,\n ): Promise<ComfyManagerAPIPluginList> => {\n const raw = await this.fetchPluginWire(api, mode, skipUpdate)\n if (!('node_packs' in raw)) return raw\n const titleByRepo = new Map<string, KnownComfyPluginTitle>()\n for (const p of this.mirror().plugins_byTitle.values())\n for (const f of p.files) titleByRepo.set(repoPath(f), p.title)\n return {\n chanel: raw.channel,\n custom_nodes: Object.values(raw.node_packs).map((p) => {\n const repo = p.files?.[0]\n return {\n title: (repo != null ? titleByRepo.get(repoPath(repo)) : undefined) ?? p.title,\n installed: p.state !== 'enabled' ? 'False' : p['update-state'] === 'true' ? 'Update' : 'True',\n }\n }),\n }\n }\n\n private fetchPluginWire = async (\n api: ManagerApi,\n mode: ComfyManagerAPIFetchPolicy,\n skipUpdate: boolean,\n ): Promise<ComfyManagerAPIPackList | ComfyManagerAPIPluginList> => {\n const query = `?mode=${mode}${skipUpdate ? '&skip_update=true' : ''}`\n const json: unknown = await this.getJSON(this.route(api, '/customnode/getlist', query))\n if (typeof json === 'object' && json != null && 'custom_nodes' in json)\n return softValidate(ComfyManagerAPIPluginList_ark, json)\n return softValidate(ComfyManagerAPIPackList_ark, json)\n }\n\n private listedModels = async (api: ManagerApi): Promise<ComfyManagerAPIModelList> => {\n return this.getJSON(this.route(api, '/externalmodel/getlist', '?mode=cache'), ComfyManagerAPIModelList_ark)\n }\n\n /** what is installed, as the Manager scans it, joined through its own registry id mappings */\n private installedData = async (api: ManagerApi): Promise<{ installed: InstalledPacks; mappings: PackMappings }> => {\n const [installed, mappings] = await Promise.all([\n this.getValid(this.route(api, '/customnode/installed'), InstalledPacks_ark),\n this.getValid(this.route(api, '/customnode/getmappings', '?mode=cache'), PackMappings_ark),\n ])\n return { installed, mappings }\n }\n\n /** v4 serves no list: our mirror against what is installed */\n private installedPluginView = async (api: ManagerApi): Promise<ComfyManagerAPIPluginList> => {\n const view = buildPluginView({ mirror: this.mirror(), ...(await this.installedData(api)) })\n if (view.unattributed.length > 0)\n logError(\n `ComfyUI-Manager ${api.version} reports installed packs no mirror row can be tied to ` +\n `(${view.unattributed.join(', ')}): the mirror rows they could be read unknown`,\n )\n return view.list\n }\n\n /** v4 serves no model list: core ComfyUI's model folders against our mirror */\n private installedModelView = async (): Promise<ComfyManagerAPIModelList> => {\n const models = this.mirror().modelRows\n const registered = new Set(await this.getValid('/models', ModelFolders_ark))\n const folders = [...modelFolders(models)].filter((f) => registered.has(f))\n const lists = await Promise.all(\n folders.map(\n async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)] as const,\n ),\n )\n return buildModelView({ models, files: new Map(lists) })\n }\n\n // INSTALL FLOW: enqueue → start → settle -------------------------------------------\n /** v3 and v4 legacy ui: the Manager's own list row for the pack, sent like its own ui does */\n private enqueueListedPlugin = async (\n api: ManagerApi,\n plugin: ComfyManagerPluginInfo,\n uiId: string,\n send: (body: Record<string, unknown>) => Promise<unknown>,\n ): Promise<undefined> => {\n const url = plugin.files[0] ?? plugin.reference\n const list = await this.fetchPluginWire(api, 'cache', true)\n if (!('node_packs' in list))\n throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`)\n const found = Object.entries(list.node_packs).find(([, p]) =>\n (p.files ?? []).some((f) => repoPath(f) === repoPath(url)),\n )\n if (found == null)\n throw new Error(\n `${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`,\n )\n const [key, row] = found\n await send({\n ...row,\n id: row.id ?? key,\n channel: list.channel,\n mode: 'cache',\n ui_id: uiId,\n skip_post_install: false,\n })\n return undefined\n }\n\n /** v4: no list to take a row from, so the pack goes by repo name at nightly; resolves with that id */\n private enqueuePluginTask = async (\n api: ManagerApi,\n plugin: ComfyManagerPluginInfo,\n uiId: string,\n ): Promise<string> => {\n const url = plugin.files[0] ?? plugin.reference\n const id = repoPath(url).split('/').pop() ?? url\n const params = {\n id,\n version: 'nightly',\n selected_version: 'nightly',\n repository: url,\n mode: 'cache',\n channel: 'default',\n }\n await this.post(this.route(api, '/manager/queue/task'), {\n ui_id: uiId,\n client_id: this.clientId,\n kind: 'install',\n params,\n })\n return id\n }\n\n /** v4: the task's own history entry says how it ended; the end state confirms a success */\n private settleByHistory = async (\n api: ManagerApi,\n what: string,\n uiId: string,\n landed: () => Promise<boolean | null>,\n sentId?: string,\n ): Promise<void> => {\n const route = this.route(api, '/manager/queue/history', `?ui_id=${encodeURIComponent(uiId)}`)\n const readEntry = async () => (await this.getValid(route, TaskHistory_ark)).history.status ?? null\n const entry = await this.waitFor(what, async () => {\n const status = await readEntry()\n if (status != null) return status\n if ((await this.restartIdleQueue(api)) !== 'drained') return null\n // the worker writes the entry before it lets go of the task: read once more to close that race\n const late = await readEntry()\n if (late != null) return late\n throw new InstallFailed(\n 'the task left the queue with no result (a queue/reset from the Manager UI or another client removes it)',\n )\n })\n if (entry.status_str === 'success' || entry.status_str === 'skip') {\n if ((await this.endState(landed)) !== false) return\n throw new InstallFailed(\n sentId != null\n ? `the Manager reported success, but this pack does not read installed: another pack holds the id \"${sentId}\" it installs by`\n : 'the Manager reported success, but it does not read installed afterwards',\n )\n }\n const messages = entry.messages ?? []\n // the 4.x worker answers a bare `failed` from its security gate only (4.2.2 and 4.4 source)\n const gate =\n messages.length === 1 && messages[0] === 'failed'\n ? ': refused by its security policy, which allows installs only with security_level normal or below ' +\n 'AND either ComfyUI listening on localhost or network_mode personal_cloud (the ComfyUI console names the rule)'\n : ''\n throw new InstallFailed(`the Manager reports ${entry.status_str}: ${messages.join(' | ')}${gate}`)\n }\n\n /**\n * a worker lingers a few seconds after a drain, then exits; a start in that window answers 201\n * \"already running\" and leaves the new task pending with no worker (seen live on 4.2.2, same loop\n * in V3 and 4.4). So an idle queue that still holds work is started again.\n */\n private restartIdleQueue = async (api: ManagerApi): Promise<'running' | 'restarted' | 'drained'> => {\n const status = await this.getValid(this.route(api, '/manager/queue/status'), QueueStatus_ark)\n if (status.is_processing) return 'running'\n const waiting = status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)\n if (waiting <= 0) return 'drained'\n await this.post(this.route(api, '/manager/queue/start'))\n return 'restarted'\n }\n\n /** v3, v4 legacy ui: no per item result over http, so wait for the drain and look at the end state */\n private settleByDrain = async (\n api: ManagerApi,\n what: string,\n landed: () => Promise<boolean | null>,\n ): Promise<void> => {\n await this.waitFor(what, async () => ((await this.restartIdleQueue(api)) === 'drained' ? true : null))\n const state = await this.endState(landed)\n if (state === true) return\n if (state === null)\n throw new OutcomeUnknown('the queue drained, but the lists cannot say whether it is installed')\n throw new InstallFailed(\n `the Manager queue drained but it is not installed; ComfyUI-Manager ${api.version} ` +\n `reports why only over its websocket (cm-queue-status) and in the ComfyUI console`,\n )\n }\n\n /** the end state after the task ran: a host that does not answer here leaves the outcome unknown */\n private endState = async (landed: () => Promise<boolean | null>): Promise<boolean | null> => {\n try {\n return await landed()\n } catch (exception) {\n throw new OutcomeUnknown(`the task ran, but its end state could not be read: ${errorText(exception)}`)\n }\n }\n\n private runInstall = async (\n what: string,\n p: {\n /** resolves with the id the host installs by, when it is not the pack's own row */\n enqueue: (api: ManagerApi, uiId: string) => Promise<string | undefined>\n /** the end state: true installed, false not, null the lists cannot say */\n landed: (s: ManagerStrategy, api: ManagerApi) => Promise<boolean | null>\n },\n ): Promise<InstallOutcome> => {\n const host = this.host.getServerHostHTTP()\n try {\n const api = await this.api()\n const s = this.strategy(api)\n const uiId = nanoid()\n const sentId = await p.enqueue(api, uiId)\n await this.post(this.route(api, '/manager/queue/start'))\n await s.settle(what, uiId, () => p.landed(s, api), sentId)\n logSuccess(`${what} installed`)\n return 'installed'\n } catch (exception) {\n if (exception instanceof OutcomeUnknown) {\n logError(\n `${what}: OUTCOME UNKNOWN on ${host}: ${exception.message}. The Manager may still be installing it: ` +\n `refetch the list (fetchModels / fetchPlugins) and read its status before installing again, ` +\n `a blind retry queues a second download`,\n )\n return 'unknown'\n }\n logError(`${what}: install failed on ${host}: ${errorText(exception)}`)\n return 'failed'\n }\n }\n\n /**\n * poll until `check` gives a value. A failed request is a blip: logged, and the poll goes on until\n * `timing.pollGraceMs` passes without one good answer. Giving up, or the deadline, is an UNKNOWN\n * outcome (the task may still run); only an `InstallFailed` from `check` ends the wait as a failure.\n */\n private waitFor = async <T>(what: string, check: () => Promise<T | null>): Promise<T> => {\n const deadline = Date.now() + this.timing.installTimeoutMs\n let lastAnswer = Date.now()\n for (;;) {\n try {\n const value = await check()\n lastAnswer = Date.now()\n if (value != null) return value\n } catch (exception) {\n if (exception instanceof InstallFailed) throw exception\n if (Date.now() - lastAnswer >= this.timing.pollGraceMs)\n throw new OutcomeUnknown(\n `the host gave no answer for ${this.timing.pollGraceMs} ms (manager.timing.pollGraceMs), last: ${errorText(exception)}`,\n )\n logError(`${what}: poll failed, still waiting: ${errorText(exception)}`)\n }\n if (Date.now() >= deadline)\n throw new OutcomeUnknown(\n `still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`,\n )\n await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs))\n }\n }\n\n // --------------------------------------------------------------\n /** json POST (the Manager's csrf guard refuses simple form types); the reply json, or null when empty */\n private post = async (route: string, body?: unknown): Promise<unknown> => {\n const response = await this.host.fetch(route, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: body === undefined ? undefined : JSON.stringify(body),\n })\n const text = await response.text()\n if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim())\n if (text === '') return null\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n }\n\n private getJSON = async <OUT = unknown>(route: string, validator?: Type<OUT>): Promise<OUT> => {\n const response = await this.host.fetch(route)\n if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim())\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 /** a GET whose shape the decision depends on: a mismatch throws instead of lying */\n private getValid = async <OUT>(route: string, schema: (json: unknown) => OUT | ArkErrors): Promise<OUT> => {\n const res = schema(await this.getJSON(route))\n if (res instanceof type.errors) throw new Error(`GET ${route}: ${res.summary}`)\n return res\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 /** names this process already uploaded to this host: a LoadAudio or LoadVideo list is not\n * reloaded after an upload, so without it every run re-sent the same file */\n private uploaded = new Set<string>()\n\n /** upload an image (hash-named, deduped against the host's LoadImage list) */\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 name = await this.uploadInput({ blob: img.getAsBlob(), name: img.enumName, ...p, slot: 'LoadImage.image' })\n return name as ComfyImageName\n }\n\n /**\n * THE upload path: any file a loader node reads from the host's input folder. ComfyUI routes\n * audio and video through `/upload/image` too. `slot` is the loader input whose value list\n * says the file is already there (`LoadImage.image`, `LoadAudio.audio`, `LoadVideo.file`)\n */\n uploadInput = async (p: {\n blob: Blob\n /** the name the file should get on the host, hash-derived by callers so reruns dedupe */\n name: string\n slot: string\n type?: Maybe<'input' | 'temp' | 'output'>\n override?: Maybe<boolean>\n subfolder?: string\n }): Promise<string> => {\n const expectedFinalName = p.subfolder ? `${p.subfolder}/${p.name}` : p.name\n if (this.uploaded.has(expectedFinalName) || this.host.schema.stringValues(p.slot).includes(expectedFinalName)) {\n console.log(`[🌁] UPLOAD: 🩶 \"${expectedFinalName}\" already exists on current ComfyUI instance`)\n return expectedFinalName\n }\n\n const form = new FormData()\n form.set('image', p.blob, p.name)\n if (p.type) form.set('type', p.type)\n if (p.override ?? true) form.set('override', 'true')\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 console.log('[🌁] UPLOAD: ✅ got', result)\n if (result.name == null) throw new Error(`upload of '${p.name}' failed: the host answered no name`)\n\n const finalName = result.subfolder ? `${result.subfolder}/${result.name}` : result.name\n if (finalName !== expectedFinalName)\n console.warn(`[🌁] UPLOAD: ⚠️ expected \"${expectedFinalName}\" but got \"${finalName}\"`)\n\n // the image list IS a known union: patch it so the next LoadImage typechecks against it\n if (p.slot === 'LoadImage.image')\n this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName as ComfyImageName)\n this.uploaded.add(finalName)\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 /** the `ws` package only (a browser answers pings by itself and exposes none of these) */\n ping?(): void\n on?(event: 'pong', cb: () => void): void\n terminate?(): 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\nexport type 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 /** tests only: a fake socket instead of the ws package / browser WebSocket */\n transport?: WsTransport\n /** a host that vanishes (power loss, hard reboot) never sends a close frame, so the\n * socket would look open forever: every `heartbeatMs` it is pinged, and one without a\n * pong since the last ping is dropped, which starts the reconnect. Default 15s */\n heartbeatMs?: number\n /** pause before a reconnect. Default 2s */\n reconnectMs?: number\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 heartbeat: ReturnType<typeof setInterval> | null = null\n private permanentlyClosed: boolean = false\n\n private stopHeartbeat(): void {\n if (this.heartbeat != null) clearInterval(this.heartbeat)\n this.heartbeat = null\n }\n\n /** ping on a timer; no pong since the previous ping = the peer is gone, drop the socket */\n private startHeartbeat(ws: WsLike): void {\n this.stopHeartbeat()\n if (typeof ws.ping !== 'function' || typeof ws.on !== 'function') return\n let awaitingPong = false\n ws.on('pong', () => {\n awaitingPong = false\n })\n const ms = this.options.heartbeatMs ?? 15_000\n this.heartbeat = setInterval(() => {\n if (ws !== this.currentWS) return this.stopHeartbeat()\n if (awaitingPong) {\n this.addError(`no pong within ${ms}ms: the host is gone, dropping the socket to reconnect`)\n this.stopHeartbeat()\n if (typeof ws.terminate === 'function') ws.terminate()\n else ws.close()\n return\n }\n awaitingPong = true\n try {\n ws.ping?.()\n } catch (e) {\n this.addError(`ping failed: ${extractErrorMessage(e)}`)\n }\n }, ms)\n }\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.stopHeartbeat()\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 this.stopHeartbeat()\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 = this.options.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 this.startHeartbeat(ws)\n }\n\n ws.onclose = (event: WsCloseEvent): void => {\n if (ws !== this.currentWS) return\n this.isOpen = false\n this.stopHeartbeat()\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 const wait = this.options.reconnectMs ?? 2000\n this.addInfo(`⏱️ reconnecting in ${wait / 1000} seconds...`)\n this.reconnectTimeout = setTimeout(() => void this.connect(), wait)\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\n/** the loras a host lists that the local copy of its lora manager list does not know yet:\n * downloaded after the last sync, so they have no name, preview or trigger words here */\nexport function lorasMissingFromMirror(hostLoras: readonly string[], inMirror: (name: string) => boolean): string[] {\n return hostLoras.filter((n) => !inMirror(n))\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","// one lora's stored setting, read the same way by LorasVar, serve and the web panel. PURE and\n// dependency-free, so the browser bundle imports it without pulling ComfyVars in.\n// absent not in the palette\n// false off, not in the palette (what an untick in the TUI writes)\n// true | n on, both strengths 1 | n\n// [m, c] on, each strength\n// { strength: [m, c], off?: true, mute?: string[] }\n// the palette form: `off` pauses it without forgetting it or its strengths,\n// `mute` the parts of its prompt keyword (split at commas) left out of the\n// prompt. Grouping loras into lanes is the VAR's shape, src/vars/lanes.ts\n\nexport type LoraEntry = {\n strength: [strengthModel: number, strengthClip: number]\n off?: boolean\n mute?: string[]\n}\n\nexport type LoraStrength = boolean | number | [strengthModel: number, strengthClip: number] | LoraEntry\n\nexport function isLoraEntry(s: unknown): s is LoraEntry {\n if (typeof s !== 'object' || s == null || Array.isArray(s)) return false\n const o = s as Record<string, unknown>\n const st = o.strength\n return (\n Array.isArray(st) &&\n st.length === 2 &&\n typeof st[0] === 'number' &&\n Number.isFinite(st[0]) &&\n typeof st[1] === 'number' &&\n Number.isFinite(st[1]) &&\n (o.off == null || typeof o.off === 'boolean') &&\n (o.mute == null || (Array.isArray(o.mute) && o.mute.every((w) => typeof w === 'string')))\n )\n}\n\nexport function isLoraStrength(s: unknown): s is LoraStrength {\n if (typeof s === 'boolean') return true\n if (typeof s === 'number') return Number.isFinite(s)\n if (Array.isArray(s)) return s.length === 2 && s.every((n) => typeof n === 'number' && Number.isFinite(n))\n return isLoraEntry(s)\n}\n\n/** on = it runs */\nexport function loraIsOn(s: unknown): boolean {\n if (s == null || s === false) return false\n if (isLoraEntry(s)) return s.off !== true\n return true\n}\n\n/** in the palette = on, or paused in the palette form */\nexport function loraInPalette(s: unknown): boolean {\n return loraIsOn(s) || (isLoraEntry(s) && s.off === true)\n}\n\n/** the strengths, whatever the spelling (1/1 when there is nothing to read) */\nexport function loraStrengths(s: unknown): [number, number] {\n if (typeof s === 'number' && Number.isFinite(s)) return [s, s]\n if (Array.isArray(s) && typeof s[0] === 'number' && typeof s[1] === 'number') return [s[0], s[1]]\n if (isLoraEntry(s)) return [s.strength[0], s.strength[1]]\n return [1, 1]\n}\n\nexport function loraMuted(s: unknown): string[] {\n return isLoraEntry(s) && s.mute != null ? s.mute : []\n}\n\n/** a prompt keyword's parts, split at commas: each one can be left out on its own */\nexport function keywordParts(keyword: string): string[] {\n return [\n ...new Set(\n keyword\n .split(',')\n .map((w) => w.trim())\n .filter((w) => w !== ''),\n ),\n ]\n}\n\n/** the keyword a lora adds to the prompt once its muted parts are left out ('' = nothing) */\nexport function keptKeyword(keyword: string, muted: readonly string[]): string {\n return keywordParts(keyword)\n .filter((w) => !muted.includes(w))\n .join(', ')\n}\n\n/** rewrite one setting, keeping what the patch does not name. The result stays in the short\n * spellings while nothing needs the palette form, so a plain draft reads as it always did */\nexport function withLora(\n s: unknown,\n patch: { on?: boolean; strength?: [number, number]; mute?: readonly string[] },\n): LoraStrength {\n const strength = patch.strength ?? loraStrengths(s)\n const off = patch.on == null ? !loraIsOn(s) : !patch.on\n const mute = [...(patch.mute ?? loraMuted(s))]\n if (!off && mute.length === 0) return [strength[0], strength[1]]\n return {\n strength: [strength[0], strength[1]],\n ...(off ? { off: true } : {}),\n ...(mute.length === 0 ? {} : { mute }),\n }\n}\n","// lanes: the second value shape of a prompt or loras var. A var holds EITHER its plain value OR\n// `{ lanes: [...] }`; the build merges the active lanes in listed order. PURE and dependency-free\n// (the browser bundle imports it), every shape runtime-checked like loraEntry.ts.\nimport { isLoraStrength, loraIsOn, type LoraStrength } from 'src/vars/loraEntry.ts'\n\nexport type PromptLane = { name: string; prompt: string; active: boolean }\nexport type PromptLanes = { lanes: PromptLane[] }\nexport type PromptInput = string | PromptLanes\n\nexport type LoraRecord<T extends string = string> = Partial<Record<T, LoraStrength>>\nexport type LoraLane<T extends string = string> = { name: string; active: boolean; loras: LoraRecord<T> }\nexport type LoraLanes<T extends string = string> = { lanes: LoraLane<T>[] }\n/** a lora file is never named `lanes` (options end in .safetensors), so the plain record and the\n * lanes object can never be mistaken for each other */\nexport type LorasInput<T extends string = string> = LoraRecord<T> | LoraLanes<T>\n\nexport const FIRST_LANE = 'main'\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v != null && !Array.isArray(v)\n}\n\n// ---- prompt ----\n\nexport function isPromptLane(v: unknown): v is PromptLane {\n return isObject(v) && typeof v.name === 'string' && typeof v.prompt === 'string' && typeof v.active === 'boolean'\n}\n\nexport function isPromptLanes(v: unknown): v is PromptLanes {\n return isObject(v) && Array.isArray(v.lanes) && v.lanes.every(isPromptLane)\n}\n\nexport function isPromptInput(v: unknown): v is PromptInput {\n return typeof v === 'string' || isPromptLanes(v)\n}\n\n/** the text the build reads: the active lanes joined in order, one line break between them, so\n * `//` and `- ` lines keep working inside every lane */\nexport function promptText(v: PromptInput): string {\n if (typeof v === 'string') return v\n return v.lanes\n .filter((l) => l.active)\n .map((l) => l.prompt)\n .join('\\n')\n}\n\nexport function toPromptLanes(v: PromptInput): PromptLanes {\n return typeof v === 'string' ? { lanes: [{ name: FIRST_LANE, prompt: v, active: true }] } : v\n}\n\n/** back to one string: only when it loses nothing (a single active lane) */\nexport function promptFromLanes(v: PromptLanes): string | null {\n const only = v.lanes[0]\n return v.lanes.length === 1 && only != null && only.active ? only.prompt : null\n}\n\n// the TUI edits a prompt as text: lanes round-trip through header lines, so it never flattens\n// them. `# name` starts a lane, `# name (off)` an inactive one\nconst HEADER = /^# (.+?)( \\(off\\))?$/\n\nexport function promptLanesToText(v: PromptLanes): string {\n return v.lanes.map((l) => `# ${l.name}${l.active ? '' : ' (off)'}\\n${l.prompt}`).join('\\n')\n}\n\n/** text before the first header lands in a lane named FIRST_LANE, so no typed line is lost */\nexport function promptLanesFromText(text: string): PromptLanes {\n const lanes: PromptLane[] = []\n let current: PromptLane | null = null\n const body: string[] = []\n const close = (): void => {\n if (current != null) lanes.push({ ...current, prompt: body.join('\\n') })\n else if (body.some((l) => l.trim() !== ''))\n lanes.push({ name: FIRST_LANE, prompt: body.join('\\n'), active: true })\n body.length = 0\n }\n for (const line of text.split('\\n')) {\n const m = HEADER.exec(line)\n if (m == null) {\n body.push(line)\n continue\n }\n close()\n current = { name: (m[1] ?? '').trim(), prompt: '', active: m[2] == null }\n }\n close()\n return { lanes: lanes.length > 0 ? lanes : [{ name: FIRST_LANE, prompt: '', active: true }] }\n}\n\n// ---- loras ----\n\nfunction isLoraRecord(v: unknown): v is LoraRecord {\n return isObject(v) && !('lanes' in v) && Object.values(v).every((s) => s == null || isLoraStrength(s))\n}\n\nexport function isLoraLane(v: unknown): v is LoraLane {\n return isObject(v) && typeof v.name === 'string' && typeof v.active === 'boolean' && isLoraRecord(v.loras)\n}\n\nexport function isLoraLanes<T extends string>(v: LorasInput<T>): v is LoraLanes<T>\nexport function isLoraLanes(v: unknown): v is LoraLanes\nexport function isLoraLanes(v: unknown): v is LoraLanes {\n return isObject(v) && Array.isArray(v.lanes) && v.lanes.every(isLoraLane)\n}\n\nexport function isLorasInput(v: unknown): v is LorasInput {\n return isLoraRecord(v) || isLoraLanes(v)\n}\n\n/** one record for the build: the active lanes in order. A lora in two active lanes keeps its\n * FIRST setting, and `duplicates` names it so the caller can say so */\nexport function flattenLoras<T extends string>(v: LorasInput<T>): { record: LoraRecord<T>; duplicates: T[] } {\n if (!isLoraLanes(v)) return { record: v, duplicates: [] }\n const record: LoraRecord<T> = {}\n const duplicates: T[] = []\n for (const lane of v.lanes) {\n if (!lane.active) continue\n for (const [name, st] of Object.entries(lane.loras) as [T, LoraStrength | undefined][]) {\n if (st == null) continue\n if (name in record) duplicates.push(name)\n else record[name] = st\n }\n }\n return { record, duplicates }\n}\n\nexport function toLoraLanes<T extends string>(v: LorasInput<T>): LoraLanes<T> {\n return isLoraLanes(v) ? v : { lanes: [{ name: FIRST_LANE, active: true, loras: v }] }\n}\n\nexport function lorasFromLanes<T extends string>(v: LoraLanes<T>): LoraRecord<T> | null {\n const only = v.lanes[0]\n return v.lanes.length === 1 && only != null && only.active ? only.loras : null\n}\n\n/** where a lora lives, so an edit lands in the lane that holds it: the first ACTIVE lane that\n * has it (the one the build reads), else any lane, else -1 */\nexport function laneIndexOf<T extends string>(v: LoraLanes<T>, name: T): number {\n const active = v.lanes.findIndex((l) => l.active && l.loras[name] != null)\n return active !== -1 ? active : v.lanes.findIndex((l) => l.loras[name] != null)\n}\n\n/** rewrite one lora's setting wherever it lives (plain record, or its lane). `null` removes it.\n * A lora in no lane yet lands in the first lane */\nexport function updateLora<T extends string>(v: LorasInput<T>, name: T, next: LoraStrength | null): LorasInput<T> {\n const write = (rec: LoraRecord<T>): LoraRecord<T> => {\n const out = { ...rec }\n if (next == null) delete out[name]\n else out[name] = next\n return out\n }\n if (!isLoraLanes(v)) return write(v)\n if (v.lanes.length === 0) return { lanes: [{ name: FIRST_LANE, active: true, loras: write({}) }] }\n const found = laneIndexOf(v, name)\n const ix = found === -1 ? 0 : found\n return { lanes: v.lanes.map((l, i) => (i === ix ? { ...l, loras: write(l.loras) } : l)) }\n}\n\n// ---- lane list edits, the same for prompt and lora lanes ----\n\ntype NamedLane = { name: string; active: boolean }\n\n/** a name no other lane has: `lane 2`, `lane 3`… */\nexport function newLaneName(lanes: readonly NamedLane[]): string {\n const taken = new Set(lanes.map((l) => l.name))\n let n = lanes.length + 1\n while (taken.has(`lane ${n}`)) n++\n return `lane ${n}`\n}\n\nexport function patchLane<L extends NamedLane>(lanes: readonly L[], ix: number, patch: Partial<L>): L[] {\n return lanes.map((l, i) => (i === ix ? { ...l, ...patch } : l))\n}\n\n/** move a lane up (-1) or down (+1); out of range changes nothing */\nexport function moveLane<L>(lanes: readonly L[], ix: number, delta: number): L[] {\n const to = ix + delta\n if (ix < 0 || ix >= lanes.length || to < 0 || to >= lanes.length) return [...lanes]\n const out = [...lanes]\n const [moved] = out.splice(ix, 1)\n if (moved != null) out.splice(to, 0, moved)\n return out\n}\n\nexport function removeLane<L>(lanes: readonly L[], ix: number): L[] {\n return lanes.filter((_, i) => i !== ix)\n}\n\n/** move one lora to another lane (or another slot of its own), before `beforeName` or last */\nexport function moveLoraToLane<T extends string>(\n v: LoraLanes<T>,\n p: { from: number; name: T; to: number; beforeName?: T },\n): LoraLanes<T> {\n const src = v.lanes[p.from]\n const setting = src?.loras[p.name]\n if (src == null || setting == null || v.lanes[p.to] == null) return v\n const lanes = v.lanes.map((l) => ({ ...l, loras: { ...l.loras } }))\n const from = lanes[p.from]\n const to = lanes[p.to]\n if (from == null || to == null) return v\n delete from.loras[p.name]\n const out: LoraRecord<T> = {}\n let placed = false\n for (const [k, st] of Object.entries(to.loras) as [T, LoraStrength | undefined][]) {\n if (k === p.beforeName && !placed) {\n out[p.name] = setting\n placed = true\n }\n out[k] = st\n }\n if (!placed) out[p.name] = setting\n to.loras = out\n return { lanes }\n}\n\n/** one lora's stored setting wherever it lives, inactive lanes included (the lane an edit\n * would write to, `updateLora`), or undefined */\nexport function loraSetting<T extends string>(v: LorasInput<T>, name: T): LoraStrength | undefined {\n if (!isLoraLanes(v)) return v[name]\n return v.lanes[laneIndexOf(v, name)]?.loras[name]\n}\n\n/** every lora in the palette of either shape, each once, with whether the build runs it: a lora\n * in an inactive lane, or paused, is there but not running */\nexport function paletteLoras<T extends string>(\n v: LorasInput<T>,\n): { name: T; setting: LoraStrength; running: boolean }[] {\n const out = new Map<T, { name: T; setting: LoraStrength; running: boolean }>()\n const lanes = isLoraLanes(v) ? v.lanes : [{ name: '', active: true, loras: v }]\n for (const lane of lanes)\n for (const [name, setting] of Object.entries(lane.loras) as [T, LoraStrength | undefined][]) {\n if (setting == null || setting === false) continue\n const running = lane.active && loraIsOn(setting)\n const seen = out.get(name)\n // a running copy wins over a stopped one, as it does in the build\n if (seen == null || (!seen.running && running)) out.set(name, { name, setting, running })\n }\n return [...out.values()]\n}\n","// prompt text rules shared by the build (PromptVar.outValue) and the web editor, so the editor's\n// colors can never disagree with what a run sends. PURE and import-free: the browser bundle takes it\n\n/** a whole line that is a comment (the TUI colors these) */\nexport const COMMENT_LINE_RE = /^\\s*\\/\\//\n/** a negative prompt line: `- ` then its text */\nexport const NEGATIVE_LINE_RE = /^\\s*- (.*)$/\nconst NEGATIVE_PREFIX_RE = /^(\\s*)- /\n\n/** where a `//` comment starts on this line, -1 when none. Only at line start or after\n * whitespace, so `http://host` is never cut */\nexport function commentStart(line: string): number {\n const m = /(?:^|\\s)\\/\\//.exec(line)\n if (m == null) return -1\n return m.index + m[0].length - 2\n}\n\n/** the line without its comment, trailing whitespace dropped with it */\nfunction withoutComment(line: string): { text: string; hadComment: boolean } {\n const c = commentStart(line)\n return c < 0 ? { text: line, hadComment: false } : { text: line.slice(0, c).trimEnd(), hadComment: true }\n}\n\n/** the build's reading of a prompt: comments out, `- ` lines comma-joined into the negative */\nexport function parsePromptText(text: string): { positive: string; negative: string } {\n const pos: string[] = []\n const neg: string[] = []\n for (const raw of text.split('\\n')) {\n const cut = withoutComment(raw)\n if (cut.hadComment && cut.text.trim() === '') continue\n const m = NEGATIVE_PREFIX_RE.exec(raw)\n if (m != null && m[0].length <= cut.text.length + 1) {\n const body = cut.text.slice(m[0].length).trim()\n if (body !== '') neg.push(body)\n } else pos.push(cut.text)\n }\n return { positive: pos.join('\\n').trim(), negative: neg.join(', ') }\n}\n\n// #region lines ---------------------------------------------------------------\n\ntype Line = { from: number; text: string }\n\nfunction linesOf(text: string): Line[] {\n const out: Line[] = []\n let from = 0\n for (const t of text.split('\\n')) {\n out.push({ from, text: t })\n from += t.length + 1\n }\n return out\n}\n\n// #region weights --------------------------------------------------------------\n\n/** one `(text:1.2)` group on a line, offsets local to that line */\nexport type WeightGroup = {\n from: number\n to: number\n innerFrom: number\n innerTo: number\n numFrom: number\n numTo: number\n weight: number\n}\n\n/** ComfyUI weight groups, innermost only (no nested parens inside), `\\(` `\\)` skipped as literal */\nexport function findWeights(line: string): WeightGroup[] {\n const out: WeightGroup[] = []\n const re = /(?<!\\\\)\\(((?:\\\\[()]|[^()])*?):\\s*(-?\\d*\\.?\\d+)\\s*(?<!\\\\)\\)/g\n for (let m = re.exec(line); m != null; m = re.exec(line)) {\n const inner = m[1] ?? ''\n const num = m[2] ?? '1'\n const from = m.index\n const to = from + m[0].length\n const numFrom = from + m[0].lastIndexOf(num)\n out.push({\n from,\n to,\n innerFrom: from + 1,\n innerTo: from + 1 + inner.length,\n numFrom,\n numTo: numFrom + num.length,\n weight: Number(num),\n })\n }\n return out\n}\n\nconst round2 = (n: number): number => Math.round(n * 100) / 100\nexport const formatWeight = (w: number): string => String(round2(w))\n\nexport type TextChange = { from: number; to: number; insert: string }\nexport type EditResult = { changes: TextChange[]; selection: { anchor: number; head: number } }\n\n/** the comma-separated chunk around `col`, trimmed, never reaching into a comment */\nfunction tagAround(line: string, col: number): { from: number; to: number } | null {\n const c = commentStart(line)\n const end = c < 0 ? line.length : c\n if (col > end) return null\n let from = col\n while (from > 0 && line[from - 1] !== ',') from--\n let to = col\n while (to < end && line[to] !== ',') to++\n const neg = NEGATIVE_PREFIX_RE.exec(line)\n if (neg != null && from < neg[0].length) from = neg[0].length\n while (from < to && /\\s/.test(line[from] ?? '')) from++\n while (to > from && /\\s/.test(line[to - 1] ?? '')) to--\n return from < to ? { from, to } : null\n}\n\n/** weight ± delta on the selection, or on the tag under the cursor when nothing is selected.\n * Inside a group its number moves, and reaching 1 unwraps it; plain text gets wrapped. null when\n * there is nothing to weigh (an empty chunk, a comment, a selection over several lines) */\nexport function adjustWeight(text: string, from: number, to: number, delta: number): EditResult | null {\n const line = linesOf(text).find((l) => from >= l.from && from <= l.from + l.text.length)\n if (line == null || to > line.from + line.text.length) return null\n const f = from - line.from\n const t = to - line.from\n const c = commentStart(line.text)\n if (c >= 0 && f >= c) return null\n const enclosing = findWeights(line.text)\n .filter((g) => f >= g.from && t <= g.to)\n .sort((a, b) => a.to - a.from - (b.to - b.from))[0]\n if (enclosing != null) {\n const w = round2(enclosing.weight + delta)\n const inner = line.text.slice(enclosing.innerFrom, enclosing.innerTo)\n if (w === 1) {\n const at = line.from + enclosing.from\n return {\n changes: [{ from: at, to: line.from + enclosing.to, insert: inner }],\n selection: { anchor: at, head: at + inner.length },\n }\n }\n return {\n changes: [{ from: line.from + enclosing.numFrom, to: line.from + enclosing.numTo, insert: formatWeight(w) }],\n selection: { anchor: line.from + enclosing.innerFrom, head: line.from + enclosing.innerTo },\n }\n }\n let span: { from: number; to: number } | null\n if (f === t) span = tagAround(line.text, f)\n else {\n let a = f\n let b = t\n while (a < b && /\\s/.test(line.text[a] ?? '')) a++\n while (b > a && /\\s/.test(line.text[b - 1] ?? '')) b--\n span = a < b ? { from: a, to: b } : null\n }\n if (span == null) return null\n const w = round2(1 + delta)\n const at = line.from + span.from\n const end = line.from + span.to\n return {\n changes: [\n { from: at, to: at, insert: '(' },\n { from: end, to: end, insert: `:${formatWeight(w)})` },\n ],\n selection: { anchor: at + 1, head: end + 1 },\n }\n}\n\n// #region line toggles -------------------------------------------------------\n\n/** the lines a selection touches; a selection ending at column 0 leaves that last line out */\nfunction touchedLines(text: string, from: number, to: number): Line[] {\n const all = linesOf(text)\n const endAt = to > from && all.some((l) => l.from === to) ? to - 1 : to\n return all.filter((l) => l.from + l.text.length >= from && l.from <= endAt)\n}\n\n/** ⌘/ — comment the touched lines, or uncomment them when every non-empty one already is */\nexport function toggleComment(text: string, from: number, to: number): TextChange[] {\n const lines = touchedLines(text, from, to).filter((l) => l.text.trim() !== '')\n if (lines.length === 0) return []\n if (lines.every((l) => COMMENT_LINE_RE.test(l.text)))\n return lines.map((l) => {\n const at = l.text.indexOf('//')\n const len = l.text[at + 2] === ' ' ? 3 : 2\n return { from: l.from + at, to: l.from + at + len, insert: '' }\n })\n return lines\n .filter((l) => !COMMENT_LINE_RE.test(l.text))\n .map((l) => {\n const at = l.from + (/^\\s*/.exec(l.text)?.[0].length ?? 0)\n return { from: at, to: at, insert: '// ' }\n })\n}\n\n/** ⌘⇧- — move the touched lines into the negative prompt, or back out when all already are.\n * Comment lines are left alone */\nexport function toggleNegative(text: string, from: number, to: number): TextChange[] {\n const lines = touchedLines(text, from, to).filter((l) => l.text.trim() !== '' && !COMMENT_LINE_RE.test(l.text))\n if (lines.length === 0) return []\n if (lines.every((l) => NEGATIVE_PREFIX_RE.test(l.text)))\n return lines.map((l) => {\n const indent = NEGATIVE_PREFIX_RE.exec(l.text)?.[1]?.length ?? 0\n return { from: l.from + indent, to: l.from + indent + 2, insert: '' }\n })\n return lines\n .filter((l) => !NEGATIVE_PREFIX_RE.test(l.text))\n .map((l) => {\n const at = l.from + (/^\\s*/.exec(l.text)?.[0].length ?? 0)\n return { from: at, to: at, insert: '- ' }\n })\n}\n\n// #region highlighting -------------------------------------------------------\n\nexport type PromptMarkKind = 'comment' | 'negative' | 'negative-dash' | 'weight-paren' | 'weight-num'\nexport type PromptMark = { from: number; to: number; kind: PromptMarkKind }\n\n/** what the editor colors, in document order */\nexport function promptMarks(text: string): PromptMark[] {\n const out: PromptMark[] = []\n for (const l of linesOf(text)) {\n const c = commentStart(l.text)\n const end = c < 0 ? l.text.length : c\n const neg = NEGATIVE_PREFIX_RE.exec(l.text)\n if (neg != null && neg[0].length <= end + 1) {\n const dash = l.from + neg[0].length - 2\n out.push({ from: dash, to: dash + 1, kind: 'negative-dash' })\n if (l.from + neg[0].length < l.from + end)\n out.push({ from: l.from + neg[0].length, to: l.from + end, kind: 'negative' })\n }\n for (const g of findWeights(l.text.slice(0, end))) {\n out.push({ from: l.from + g.from, to: l.from + g.innerFrom, kind: 'weight-paren' })\n out.push({ from: l.from + g.innerTo, to: l.from + g.numFrom, kind: 'weight-paren' })\n out.push({ from: l.from + g.numFrom, to: l.from + g.numTo, kind: 'weight-num' })\n out.push({ from: l.from + g.numTo, to: l.from + g.to, kind: 'weight-paren' })\n }\n if (c >= 0) out.push({ from: l.from + c, to: l.from + l.text.length, kind: 'comment' })\n }\n return out.sort((a, b) => a.from - b.from || a.to - b.to)\n}\n\n// #region tag issues ---------------------------------------------------------\n\n/** the form two tags are compared in: weight wrapper off, literal parens unescaped, lowercase,\n * underscores as spaces */\nexport function normalizeTag(chunk: string): string {\n let s = chunk.trim()\n const whole = findWeights(s)[0]\n if (whole != null && whole.from === 0 && whole.to === s.length) s = s.slice(whole.innerFrom, whole.innerTo)\n return s\n .replace(/\\\\([()])/g, '$1')\n .toLowerCase()\n .replace(/_/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\nexport type TagIssue = { from: number; to: number; message: string }\n\ntype Chunk = { from: number; to: number; tag: string }\n\nfunction chunksOf(line: string, offset: number, start: number): Chunk[] {\n const out: Chunk[] = []\n let from = start\n for (let i = start; i <= line.length; i++) {\n if (i < line.length && line[i] !== ',') continue\n const raw = line.slice(from, i)\n const lead = raw.length - raw.trimStart().length\n const tag = normalizeTag(raw)\n if (tag !== '') out.push({ from: offset + from + lead, to: offset + from + raw.trimEnd().length, tag })\n from = i + 1\n }\n return out\n}\n\n/** a tag written twice, a tag a lora already adds, a tag in both prompts, and every weight when\n * the model ignores weights. Each issue carries the sentence the editor shows on hover */\nexport function tagIssues(\n text: string,\n p: { injected?: readonly { tag: string; source: string }[]; weights?: boolean } = {},\n): TagIssue[] {\n const out: TagIssue[] = []\n const positive: Chunk[] = []\n const negative: Chunk[] = []\n for (const l of linesOf(text)) {\n if (COMMENT_LINE_RE.test(l.text)) continue\n const body = withoutComment(l.text).text\n const neg = NEGATIVE_PREFIX_RE.exec(l.text)\n const isNeg = neg != null && neg[0].length <= body.length + 1\n const chunks = chunksOf(body, l.from, isNeg ? neg[0].length : 0)\n ;(isNeg ? negative : positive).push(...chunks)\n if (p.weights === false)\n for (const g of findWeights(body))\n out.push({\n from: l.from + g.from,\n to: l.from + g.to,\n message: 'this model ignores weights: the text inside is read, the number is not',\n })\n }\n const injected = new Map<string, string>()\n for (const i of p.injected ?? []) {\n const tag = normalizeTag(i.tag)\n if (tag !== '' && !injected.has(tag)) injected.set(tag, i.source)\n }\n const scan = (side: Chunk[], sideName: string): void => {\n const seen = new Set<string>()\n for (const ch of side) {\n if (seen.has(ch.tag))\n out.push({ from: ch.from, to: ch.to, message: `'${ch.tag}' is already in the ${sideName}` })\n seen.add(ch.tag)\n }\n }\n scan(positive, 'prompt')\n scan(negative, 'negative prompt')\n const negTags = new Set(negative.map((c) => c.tag))\n for (const ch of positive) {\n const source = injected.get(ch.tag)\n if (source != null)\n out.push({ from: ch.from, to: ch.to, message: `'${ch.tag}' is already added by the lora ${source}` })\n if (negTags.has(ch.tag))\n out.push({ from: ch.from, to: ch.to, message: `'${ch.tag}' is also in the negative prompt` })\n }\n return out.sort((a, b) => a.from - b.from)\n}\n\n// #region token estimate ------------------------------------------------------\n\n/** a rough CLIP token count of what the build sends as positive: one per short word, long words\n * split, one per punctuation mark. An ESTIMATE, the editor shows it with ≈ */\nexport function estimateTokens(text: string): number {\n const body = parsePromptText(text).positive\n let n = 0\n for (const m of body.matchAll(/\\p{L}+|\\p{N}|[^\\s\\p{L}\\p{N}]/gu)) {\n const w = m[0]\n n += /^\\p{L}/u.test(w) && w.length > 8 ? Math.ceil(w.length / 5) : 1\n }\n return n\n}\n\n// #region completion ------------------------------------------------------------\n\n/** the partial tag being typed at `col`: from the last `,` `(` or line start, leading spaces\n * and a negative `- ` skipped. null inside a comment */\nexport function completionWord(line: string, col: number): { from: number; text: string } | null {\n const c = commentStart(line)\n if (c >= 0 && col > c) return null\n let from = col\n while (from > 0 && !/[,(]/.test(line[from - 1] ?? '')) from--\n const neg = NEGATIVE_PREFIX_RE.exec(line)\n if (neg != null && from < neg[0].length) from = neg[0].length\n while (from < col && /\\s/.test(line[from] ?? '')) from++\n return { from, text: line.slice(from, col) }\n}\n\n/** what to search for at `col`: the whole chunk first, then its last words, longest first, so a\n * tag typed after prose or another tag with no comma between (`a girl with long ha`) still\n * completes. At most the last four word starts, an empty tail never */\nexport function completionCandidates(line: string, col: number): { from: number; text: string }[] {\n const word = completionWord(line, col)\n if (word == null) return []\n const out = [word]\n const starts: number[] = []\n for (let i = word.from + 1; i < col; i++)\n if (/\\s/.test(line[i - 1] ?? '') && !/\\s/.test(line[i] ?? '')) starts.push(i)\n for (const from of starts.slice(-4)) out.push({ from, text: line.slice(from, col) })\n return out\n}\n\nexport type TagFormat = { underscores?: boolean; weights?: boolean; artistPrefix?: string }\n\n/** a tag list name as the prompt wants it. Underscores between letters become spaces (`>_<`\n * keeps its own), parens get escaped where ComfyUI would read them as emphasis */\nexport function formatTag(name: string, category: number | null, p: TagFormat): string {\n let s = p.underscores === true ? name : name.replace(/(?<=[\\p{L}\\p{N})])_(?=[\\p{L}\\p{N}(])/gu, ' ')\n if (p.weights !== false) s = s.replace(/(?<!\\\\)([()])/g, '\\\\$1')\n if (category === TAG_CATEGORY_ARTIST && p.artistPrefix != null) s = `${p.artistPrefix}${s}`\n return s\n}\n\n/** danbooru categories as the a1111 tagcomplete csv numbers them */\nexport const TAG_CATEGORY_ARTIST = 1\nexport const TAG_CATEGORY_NAMES: Record<number, string> = {\n 0: 'general',\n 1: 'artist',\n 3: 'copyright',\n 4: 'character',\n 5: 'meta',\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 {\n flattenLoras,\n isLorasInput,\n isPromptLanes,\n promptLanesFromText,\n promptLanesToText,\n promptText,\n updateLora,\n type LoraRecord,\n type LorasInput,\n type PromptInput,\n} from 'src/vars/lanes.ts'\nimport { keptKeyword, loraIsOn, loraMuted, loraStrengths, withLora, type LoraStrength } from 'src/vars/loraEntry.ts'\nimport { logError } from 'src/utils/log.ts'\nimport { COMMENT_LINE_RE, NEGATIVE_LINE_RE, parsePromptText } from 'src/vars/promptSyntax.ts'\nimport { toPresetList, type VarPreset, type VarPresetSpec } from 'src/vars/presets.ts'\nimport { DEFAULT_MEDIA_EXTENSIONS, extensionOf, mediaMime, type MediaKind } from 'src/runner/mediaKinds.ts'\nimport { hashArrayBuffer } from 'src/utils/hashArrayBuffer.ts'\nimport { statelessRegex } from 'src/utils/matchesRegex.ts'\nimport type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'\nimport type { NodeOf } from 'src/types/comfy-sdk.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' | MediaKind\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 */\n/** how a var LOOKS in the panel, set by the workflow: `v.int(8).ui({ icon, color, description })`.\n * Every slot is optional, a color is any css color */\nexport type VarUi = {\n /** shown as a (?) after the label, the text is its tooltip */\n description?: string\n /** a 24×24 svg path drawn in the icon color, or a whole `<svg …>` string */\n icon?: string\n /** the icon's color */\n color?: string\n labelColor?: string\n /** the whole row, drawn without moving anything in it */\n background?: string\n /** vars that go together: consecutive vars with the same group share one tinted block */\n group?: string\n /** the block's tint, read from the first var of the group that sets it */\n groupColor?: string\n border?: string\n /** choice vars: a look per option, keyed by the option value. The lit option is filled\n * with its own color */\n options?: Record<string, { icon?: string; color?: string }>\n /** the field is shown but disabled unless every named var holds one of the listed values:\n * `{ model: ['aesthetic', 'base'] }`. Checked against the var names when the workflow loads.\n * Display only: a disabled var's value still reaches the build */\n activeWhen?: Record<string, readonly (string | number | boolean)[]>\n}\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 /** panel looks, see VarUi. Never part of the value, never in a draft */\n uiOpts: VarUi = {}\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 /** chainable: `v.choice([...], 'a').ui({ icon: 'M4 12h16', color: '#e0af68' })` */\n ui(p: VarUi): this {\n this.uiOpts = { ...this.uiOpts, ...p }\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\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 = {\n activeNames(): string[]\n hostId?: string\n /** the parts of a lora's keyword left out of the prompt (LorasVar: the `mute` list) */\n mutedWords?(name: string): string[]\n}\n\n/** where a prompt's tag completion comes from (the serve web editor). The list is never shipped:\n * `url` is a local path (relative to the workflow file, `~/`, `file://`) or an http(s) url */\nexport type PromptTagsOpts = {\n url: string\n /** insert `long_hair` as written in the list; default inserts `long hair` */\n underscores?: boolean\n /** put in front of an artist tag on insert (Anima: `@`) */\n artistPrefix?: string\n}\n\nexport type PromptVarOpts = {\n label?: string\n loraKeywordsFrom?: ActiveLoraSource\n presets?: VarPresetSpec\n /** booru tag completion for this prompt: a tag list url, or the url with its insert rules */\n tags?: string | PromptTagsOpts\n /** false when the model's encoder ignores `(text:1.2)`: the editor then flags every weight */\n weights?: boolean\n}\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 * - `//` starts a COMMENT to the end of the line (src/vars/promptSyntax.ts) — 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<PromptInput, 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: PromptInput,\n public promptOpts: PromptVarOpts = {},\n ) {\n super(defaultValue, promptOpts.label)\n this.presets = toPresetList(promptOpts.presets)\n }\n /** in lanes mode the text carries `# name` headers, so a lane survives a round trip */\n parse(raw: string): boolean {\n this.set(isPromptLanes(this.value) ? promptLanesFromText(raw) : raw)\n return true\n }\n override toEditBuffer(): string {\n return isPromptLanes(this.value) ? promptLanesToText(this.value) : this.value\n }\n /** a var list shows the lanes by name, the inactive ones in parentheses */\n override display(): string {\n if (!isPromptLanes(this.value)) return super.display()\n return `${this.value.lanes.length} lanes: ${this.value.lanes.map((l) => (l.active ? l.name : `(${l.name})`)).join(', ')}`\n }\n /** the text the build reads: the plain string, or the active lanes joined in order */\n get text(): string {\n return promptText(this.value)\n }\n /** the tag list options in their one object form, null when this prompt has no completion */\n get tags(): PromptTagsOpts | null {\n const t = this.promptOpts.tags\n if (t == null) return null\n return typeof t === 'string' ? { url: t } : t\n }\n static isCommentLine(line: string): boolean {\n return COMMENT_LINE_RE.test(line)\n }\n static isNegativeLine(line: string): boolean {\n return NEGATIVE_LINE_RE.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) => keptKeyword(getLoraKeyword(name, src.hostId), src.mutedWords?.(name) ?? []))\n .filter((k) => k !== ''),\n ),\n ]\n }\n outValue(): PromptValue {\n const parsed = parsePromptText(this.text)\n const body = parsed.positive\n const keywords = this.injectedKeywords()\n const positive =\n keywords.length === 0 ? body : body === '' ? keywords.join(', ') : `${keywords.join(', ')}, ${body}`\n return { positive, negative: parsed.negative }\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\n/** how many options a choice holds: exactly one (the default), one or none, or any number */\nexport type ChoiceSelect = 'one' | 'zero-or-one' | 'many'\n\n/** where a host-bound choice reads its options: one loader input of the host's live schema,\n * optionally narrowed (`v.model`) */\nexport type HostSlotSource = { slot: string; filter?: RegExp }\n\n/** a fixed list, or the host's list for one slot once bindHost ran */\nclass ChoiceList<T extends string> {\n private resolved: readonly T[] | null = null\n constructor(readonly source: readonly T[] | HostSlotSource) {}\n get slot(): HostSlotSource | null {\n return isChoiceList(this.source) ? null : this.source\n }\n get choices(): readonly T[] {\n if (isChoiceList(this.source)) return this.source\n if (this.resolved == null)\n throw new Error(\n `v.model('${this.source.slot}') is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list to v.choice otherwise)`,\n )\n return this.resolved\n }\n /** cast: whitelist family 1 (agent/coding.md) — stringValues() returns the runtime values of\n * the SAME object_info enum the generated slot union comes from */\n bind(host: LorasHost): void {\n const src = this.slot\n if (src == null) return\n const all = host.schema.stringValues(src.slot)\n const filter = src.filter == null ? null : statelessRegex(src.filter)\n this.resolved = (filter == null ? all : all.filter((n) => filter.test(n))) as T[]\n }\n}\n\nexport class ChoiceVar<T extends string> extends ComfyVar<T> {\n readonly kind = 'choice' as const\n readonly select = 'one' as const\n private list: ChoiceList<T>\n constructor(choices: readonly T[] | HostSlotSource, defaultValue: T, label?: string) {\n super(defaultValue, label)\n this.list = new ChoiceList(choices)\n }\n get choices(): readonly T[] {\n return this.list.choices\n }\n /** set for `v.model`: the loader input this choice lists */\n get hostSlot(): HostSlotSource | null {\n return this.list.slot\n }\n bindHost(host: LorasHost): void {\n this.list.bind(host)\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/** one option or none: `null` is \"nothing picked\", clicking the lit option clears it */\nexport class OptionalChoiceVar<T extends string> extends ComfyVar<T | null> {\n readonly kind = 'choice' as const\n readonly select = 'zero-or-one' as const\n private list: ChoiceList<T>\n constructor(choices: readonly T[] | HostSlotSource, defaultValue: T | null, label?: string) {\n super(defaultValue, label)\n this.list = new ChoiceList(choices)\n }\n get choices(): readonly T[] {\n return this.list.choices\n }\n get hostSlot(): HostSlotSource | null {\n return this.list.slot\n }\n bindHost(host: LorasHost): void {\n this.list.bind(host)\n }\n /** pick `c`, or clear it when it is already the one picked */\n toggle(c: T): this {\n return this.set(this.value === c ? null : c)\n }\n /** the TUI text form: a choice, or an empty line for none */\n parse(raw: string): boolean {\n if (raw.trim() === '') {\n this.set(null)\n return true\n }\n const hit = this.choices.find((c) => c === raw.trim())\n if (hit == null) return false\n this.set(hit)\n return true\n }\n override toEditBuffer(): string {\n return this.value ?? ''\n }\n /** a draft from when this was a many choice holds a list: its first known option */\n override loadJSON(value: unknown): this {\n const one = Array.isArray(value) ? value[0] : value\n return this.set(this.choices.find((c) => c === one) ?? null)\n }\n override display(): string {\n return this.value ?? 'none'\n }\n}\n\n/** any number of options, kept in the order the choices list them */\nexport class MultiChoiceVar<T extends string> extends ComfyVar<T[]> {\n readonly kind = 'choice' as const\n readonly select = 'many' as const\n constructor(\n public readonly choices: readonly T[],\n defaultValue: readonly T[],\n label?: string,\n ) {\n super([...defaultValue], label)\n }\n toggle(c: T): this {\n const on = this.value.includes(c)\n return this.set(this.choices.filter((x) => (x === c ? !on : this.value.includes(x))))\n }\n /** the TUI text form: `a, b` */\n parse(raw: string): boolean {\n const wanted = raw\n .split(',')\n .map((w) => w.trim())\n .filter((w) => w !== '')\n const picked = this.choices.filter((c) => wanted.includes(c))\n if (picked.length !== new Set(wanted).size) return false\n this.set(picked)\n return true\n }\n override toEditBuffer(): string {\n return this.value.join(', ')\n }\n /** a draft from when this was a single choice holds one value: a list of one. Unknown\n * options are dropped, the list comes back in the choices order */\n override loadJSON(value: unknown): this {\n const listed: unknown[] = Array.isArray(value) ? value : value == null ? [] : [value]\n return this.set(this.choices.filter((c) => listed.includes(c)))\n }\n override display(): string {\n return this.value.length === 0 ? 'none' : this.value.join(', ')\n }\n}\n\n/** the three choice shapes, told apart by `select` */\nexport type AnyChoiceVar<T extends string = string> = ChoiceVar<T> | OptionalChoiceVar<T> | MultiChoiceVar<T>\n\ntype ChoiceOpts<S extends ChoiceSelect> = { label?: string; select: S }\n\n/** Array.isArray does not narrow a READONLY array out of a union, this does */\nfunction isChoiceList<T extends string>(v: T | null | readonly T[] | HostSlotSource): v is readonly T[] {\n return Array.isArray(v)\n}\n\nfunction choice<const T extends string>(\n choices: readonly T[],\n defaultValue: T,\n label?: string | { label?: string; select?: 'one' },\n): ChoiceVar<T>\nfunction choice<const T extends string>(\n choices: readonly T[],\n defaultValue: T | null,\n opts: ChoiceOpts<'zero-or-one'>,\n): OptionalChoiceVar<T>\nfunction choice<const T extends string>(\n choices: readonly T[],\n defaultValue: readonly T[],\n opts: ChoiceOpts<'many'>,\n): MultiChoiceVar<T>\nfunction choice<const T extends string>(\n choices: readonly T[],\n defaultValue: T | null | readonly T[],\n opts?: string | { label?: string; select?: ChoiceSelect },\n): AnyChoiceVar<T> {\n const o = typeof opts === 'string' ? { label: opts } : (opts ?? {})\n const select = o.select ?? 'one'\n if (select === 'many') {\n if (!isChoiceList(defaultValue))\n throw new Error(`a 'many' choice takes a list as its default, got ${String(defaultValue)}`)\n return new MultiChoiceVar(choices, defaultValue, o.label)\n }\n if (isChoiceList(defaultValue)) throw new Error(`a '${select}' choice takes one value as its default, not a list`)\n if (select === 'zero-or-one') return new OptionalChoiceVar(choices, defaultValue, o.label)\n if (defaultValue == null) throw new Error(\"a 'one' choice needs a default: use { select: 'zero-or-one' } for none\")\n return new ChoiceVar(choices, defaultValue, o.label)\n}\n\nexport type ModelVarOpts<T extends string> = {\n /** narrows the host's list: `/krea/i` */\n filter?: RegExp\n label?: string\n /** a file name, or null for \"the workflow decides\" (the build then reads null) */\n default: T | null\n}\n\n/** a choice over the host's LIVE file list for one loader input (`'UNETLoader.unet_name'`),\n * resolved at define time and rebound by serve's refresh-schema: a downloaded model is picked\n * in the draft, never written into the workflow file */\nfunction model<T extends string>(slot: string, opts: ModelVarOpts<T> & { default: T }): ChoiceVar<T>\nfunction model<T extends string>(slot: string, opts: ModelVarOpts<T> & { default: null }): OptionalChoiceVar<T>\nfunction model<T extends string>(slot: string, opts: ModelVarOpts<T>): ChoiceVar<T> | OptionalChoiceVar<T> {\n const source: HostSlotSource = { slot, filter: opts.filter }\n if (opts.default == null) return new OptionalChoiceVar<T>(source, null, opts.label)\n return new ChoiceVar<T>(source, opts.default, opts.label)\n}\n\n/** per-lora setting, every spelling documented in src/vars/loraEntry.ts */\nexport type { LoraStrength } from 'src/vars/loraEntry.ts'\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: LorasInput<T>): ActiveLora<T>[] {\n const out: ActiveLora<T>[] = []\n for (const [lora_name, s] of Object.entries(flattenLoras(loras).record) as [T, LoraStrength | undefined][]) {\n // a paused lora ({ off: true }) is in the palette, never in the graph\n if (!loraIsOn(s)) continue\n const [strength_model, strength_clip] = loraStrengths(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 = {\n data?: { id?: string }\n schema: { getLoras(filter?: RegExp): string[]; stringValues(slot: string): string[] }\n}\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 */\n/**\n * the value is EITHER a plain record OR `{ lanes: [...] }` (src/vars/lanes.ts): named groups the\n * build merges in listed order, skipping inactive ones. Every method reads the merged record and\n * writes into the lane that holds the lora, so the TUI never needs to know lanes exist\n */\nexport class LorasVar<T extends string> extends ComfyVarBase<LorasInput<T>, LoraRecord<T>> {\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: LorasInput<T> = {},\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 /** the loras the build reads: the plain record, or the active lanes merged in order */\n get record(): LoraRecord<T> {\n return flattenLoras(this.value).record\n }\n\n /** what the graph consumes. A lora in two active lanes runs once, with its FIRST setting */\n outValue(): LoraRecord<T> {\n const flat = flattenLoras(this.value)\n if (flat.duplicates.length > 0)\n logError(\n `loras var '${this.name ?? this.label ?? '?'}': ${flat.duplicates.join(', ')} sit in two active lanes, the first lane's setting is used`,\n )\n return flat.record\n }\n\n /** rewrite one lora wherever it lives: the plain record, or the lane that holds it */\n private write(name: T, next: LoraStrength | null): this {\n return this.set(updateLora(this.value, name, next))\n }\n\n /** the parts of this lora's prompt keyword left out of the prompt */\n mutedWords(name: string): string[] {\n return loraMuted(this.record[name as T])\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 return loraIsOn(this.record[name])\n }\n\n toggleItem(name: T): this {\n const cur = this.record[name]\n if (cur == null || cur === false) return this.write(name, this.prev[name] ?? true)\n // a paused palette entry resumes in place, strengths kept\n if (!loraIsOn(cur)) return this.write(name, withLora(cur, { on: true }))\n this.prev[name] = cur\n return this.write(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.record[name]\n if (!loraIsOn(cur)) return this\n const step = (n: number): number => Math.max(0, Math.round((n + delta) * 100) / 100)\n // the short spellings stay short: only a palette entry needs the object form\n const next: LoraStrength =\n typeof cur === 'number' || cur === true\n ? step(cur === true ? 1 : cur)\n : Array.isArray(cur)\n ? [step(cur[0]), step(cur[1])]\n : withLora(cur, { strength: [step(loraStrengths(cur)[0]), step(loraStrengths(cur)[1])] })\n return this.write(name, next)\n }\n\n /** compact per-item strength label for lists */\n strengthLabel(name: T): string {\n const s = this.record[name]\n if (!loraIsOn(s)) return ''\n const [m, c] = loraStrengths(s)\n return m === c ? m.toFixed(2) : `m:${m.toFixed(2)} c:${c.toFixed(2)}`\n }\n\n parse(raw: string): boolean {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (!isLorasInput(parsed)) return false\n // cast: whitelist family 1, the names are this host's lora enum, checked by the build\n this.set(parsed as LorasInput<T>)\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 record = this.record\n let next = this.value\n for (const name of names) {\n const cur = record[name]\n if (on) {\n if (cur == null || cur === false) next = updateLora(next, name, this.prev[name] ?? true)\n // a paused palette entry resumes in place, strengths kept\n else if (!loraIsOn(cur)) next = updateLora(next, name, withLora(cur, { on: true }))\n } else {\n if (loraIsOn(cur)) this.prev[name] = cur\n next = updateLora(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/** the same aspect ratios around 512, for SD1.5-era models trained at ~0.25MP */\nexport const SD15_SIZE_PRESETS: SizePreset[] = [\n { label: '1:1 square', width: 512, height: 512 },\n { label: '4:3 landscape', width: 576, height: 448 },\n { label: '3:4 portrait', width: 448, height: 576 },\n { label: '3:2 landscape', width: 576, height: 384 },\n { label: '2:3 portrait', width: 384, height: 576 },\n { label: '16:9 widescreen', width: 704, height: 384 },\n { label: '9:16 tall', width: 384, height: 704 },\n]\n\n/** starred presets are one click away in the panel, before the full list */\nexport const DEFAULT_STARRED_SIZES = ['1:1 square', '3:4 portrait', '4:3 landscape']\n\n/** the family that matches a workflow's own default: a 512×512 workflow is an SD1.5-era one,\n * and offering it 1024 buckets would be offering sizes it was never trained at */\nexport function sizePresetsFor(defaultValue: SizeValue | undefined): SizePreset[] {\n if (defaultValue == null) return DEFAULT_SIZE_PRESETS\n return defaultValue.width * defaultValue.height <= 600 * 600 ? SD15_SIZE_PRESETS : DEFAULT_SIZE_PRESETS\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 /** preset LABELS starred by default; a user's own stars live in the panel */\n public readonly starred: readonly string[] = DEFAULT_STARRED_SIZES,\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 MediaVarOpts = {\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 media 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 /** the text var a file's `<name>.txt` sidecar fills, when a driver sets this var from a file\n * and leaves that one unset: a voice clip's transcript (`comfy-ts run`) */\n sidecarText?: TextVar\n}\nexport type ImageVarOpts = MediaVarOpts\nexport type AudioVarOpts = MediaVarOpts\nexport type VideoVarOpts = MediaVarOpts\n\nexport const DEFAULT_IMAGE_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.image\nexport const DEFAULT_AUDIO_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.audio\nexport const DEFAULT_VIDEO_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.video\n\n/** empty media var consumed at build time — typed so drivers surface it apart from real crashes */\nexport class MediaVarEmptyError extends Error {\n /** name, not instanceof: the cli bundle and dist/index.js each define this class */\n override readonly name: string = 'MediaVarEmptyError'\n constructor(\n public readonly varName: string,\n public readonly media: MediaKind = 'image',\n ) {\n super(`${media} var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/file'))`)\n }\n}\n/** the image-only name this error had first; the same class */\nexport const ImageVarEmptyError = MediaVarEmptyError\nexport type ImageVarEmptyError = MediaVarEmptyError\n\n/** trim + expand a leading `~/` — every media var 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/** the loader node each medium goes through, and its file input */\nconst MEDIA_LOADERS: Record<MediaKind, { node: string; input: string }> = {\n image: { node: 'LoadImage', input: 'image' },\n audio: { node: 'LoadAudio', input: 'audio' },\n video: { node: 'LoadVideo', input: 'file' },\n}\n\n/**\n * a local media file 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 MediaVarEmptyError,\n * so a build never runs on a silent placeholder. The TUI opens the file\n * picker overlay for every media kind.\n */\nexport abstract class MediaVar extends ComfyVar<string> {\n abstract override readonly kind: MediaKind\n constructor(\n defaultValue: string,\n public opts: MediaVarOpts = {},\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_MEDIA_EXTENSIONS[this.kind]\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(): MediaVarEmptyError {\n return new MediaVarEmptyError(this.name ?? this.label ?? this.kind, this.kind)\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 /** upload the file hash-named (reruns dedupe) and add this medium's loader node. A dry\n * build names the file by its hash and uploads nothing */\n protected async loadVia(wf: ComfyWorkflow<string>): Promise<unknown> {\n const loader = MEDIA_LOADERS[this.kind]\n const factory = wf.builderBase[loader.node]\n if (factory == null)\n throw new Error(\n `host '${wf.host.data.id}' has no ${loader.node} node: ${this.kind} var '${this.name ?? '?'}' cannot load`,\n )\n const abs = this.absPath()\n const bytes = getComfyStorage().readBytes(abs)\n const ext = extensionOf(abs)\n const name = `${hashArrayBuffer(bytes)}${ext === '' ? '' : `.${ext}`}`\n const onHost = wf.dry\n ? name\n : await wf.host.uploader.uploadInput({\n blob: new Blob([bytes as Uint8Array<ArrayBuffer>], { type: mediaMime(abs) }),\n name,\n slot: `${loader.node}.${loader.input}`,\n type: 'input',\n })\n return factory({ [loader.input]: onHost })\n }\n}\n\n/** a local image path, loaded through LoadImage */\nexport class ImageVar extends MediaVar {\n readonly kind = 'image' as const\n async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadImage'>> {\n // sanctioned cast (family 1): the node is the host's own LoadImage, built from object_info\n return (await this.loadVia(wf)) as NodeOf<WID, 'LoadImage'>\n }\n}\n\n/** a local audio path, loaded through LoadAudio */\nexport class AudioVar extends MediaVar {\n readonly kind = 'audio' as const\n async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadAudio'>> {\n // sanctioned cast (family 1): same as ImageVar\n return (await this.loadVia(wf)) as NodeOf<WID, 'LoadAudio'>\n }\n}\n\n/** a local video path, loaded through LoadVideo */\nexport class VideoVar extends MediaVar {\n readonly kind = 'video' as const\n async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadVideo'>> {\n // sanctioned cast (family 1): same as ImageVar\n return (await this.loadVia(wf)) as NodeOf<WID, 'LoadVideo'>\n }\n}\n\n/** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.model / v.loras / v.size / v.image / v.audio / v.video */\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 /** a string, or `{ lanes: [{ name, prompt, active }] }` merged in listed order */\n defaultValue: PromptInput,\n opts: PromptVarOpts = {},\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 /** exactly one option (the default), `{ select: 'zero-or-one' }` for one or none (value\n * `T | null`), `{ select: 'many' }` for any number (value `T[]`) */\n choice,\n loras: <T extends string = string>(\n options: readonly T[] | RegExp,\n /** a record, or `{ lanes: [{ name, active, loras }] }` merged in listed order */\n initial: LorasInput<T> = {},\n label?: string,\n ): LorasVar<T> => new LorasVar(options, initial, label),\n size: (\n defaultValue?: SizeValue,\n opts: { presets?: SizePreset[]; starred?: readonly string[]; label?: string; image?: ImageVar } = {},\n ): SizeVar =>\n new SizeVar(defaultValue, opts.presets ?? sizePresetsFor(defaultValue), opts.label, opts.image, opts.starred),\n /** host-bound: only inside defineWorkflow({ vars: (v) => … }), typed per slot there */\n model,\n image: (defaultValue: string, opts: MediaVarOpts = {}): ImageVar => new ImageVar(defaultValue, opts),\n audio: (defaultValue: string, opts: MediaVarOpts = {}): AudioVar => new AudioVar(defaultValue, opts),\n video: (defaultValue: string, opts: MediaVarOpts = {}): VideoVar => new VideoVar(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 readonly uiOpts: VarUi\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 type { LorasInput } from 'src/vars/lanes.ts'\nimport {\n type AnyVar,\n type ChoiceVar,\n type LorasVar,\n type ModelVarOpts,\n type OptionalChoiceVar,\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' | 'model'> & {\n loras(options: RegExp, initial?: LorasInput<LoraNameOf<ID>>, label?: string): LorasVar<LoraNameOf<ID>>\n loras<T extends string>(options: readonly T[], initial?: LorasInput<T>, label?: string): LorasVar<T>\n /** the host's file list for one loader input: the slot autocompletes, the value is its union */\n model: ModelFactory<SdkForHost<ID>['Slots']>\n}\n\n/** `v.model` typed by a host's slot table S (`Slots`): its own interface, so the host id's\n * variance stays measurable (inlined into BoundVars, ComfyHost<ID> stopped being a ComfyHost<string>) */\nexport interface ModelFactory<S> {\n <K extends keyof S & string>(\n slot: K,\n opts: ModelVarOpts<S[K] & string> & { default: S[K] & string },\n ): ChoiceVar<S[K] & string>\n <K extends keyof S & string>(\n slot: K,\n opts: ModelVarOpts<S[K] & string> & { default: null },\n ): OptionalChoiceVar<S[K] & string>\n}\n\n/** every `Node.input` slot of the host's generated sdk (any string without one) */\nexport type SlotNameOf<ID extends string> = keyof SdkForHost<ID>['Slots'] & string\n\n/** the value union of one slot, strings only (a loader file list) */\nexport type SlotValueOf<ID extends string, K extends string> = K extends keyof SdkForHost<ID>['Slots']\n ? SdkForHost<ID>['Slots'][K] & string\n : string\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 /** named texts computed from the CURRENT var values, the same `vars` build receives, shown\n * live while the vars are edited (the serve panel: a foldable block under generate). Use the\n * function build uses, so a preview is what the run sends, never a paraphrase of it */\n previews?: Record<string, (vars: VarValues<V>) => string>\n /** free search tags for the serve omnibox, added to the ones read from the graph\n * (`image`, `audio`, `video`, `text`, `llm`, `edit`) */\n tags?: string[]\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 // a condition naming a var that does not exist would silently never enable its field\n const names = this.entries().map(([key]) => key)\n for (const [key, varDef] of this.entries())\n for (const other of Object.keys(varDef.uiOpts.activeWhen ?? {}))\n if (!names.includes(other))\n throw new Error(\n `workflow '${spec.id ?? '?'}': var '${key}' is activeWhen '${other}', which is not one of its vars (${names.join(', ')})`,\n )\n }\n\n /** every preview for the current var values. A preview that throws, or vars that cannot be\n * read yet (an image var still empty), give a line saying so instead of failing the others */\n computePreviews(): Record<string, string> {\n const previews = this.spec.previews ?? {}\n const names = Object.keys(previews)\n if (names.length === 0) return {}\n let values: VarValues<V>\n try {\n values = varValues(this.vars)\n } catch (e) {\n const why = `unavailable: ${e instanceof Error ? e.message : String(e)}`\n return Object.fromEntries(names.map((n) => [n, why]))\n }\n const out: Record<string, string> = {}\n for (const [name, fn] of Object.entries(previews)) {\n try {\n out[name] = fn(values)\n } catch (e) {\n out[name] = `🔴 preview '${name}' failed: ${e instanceof Error ? e.message : String(e)}`\n }\n }\n return out\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 * `p.dry` builds a graph only to read it: nothing is uploaded, lastWorkflow is left alone.\n */\n async build(p: { advance?: boolean; host?: ComfyHost<ID>; dry?: boolean } = {}): Promise<ComfyWorkflow<ID>> {\n const host = p.host ?? this.host\n const wf = host.workflow({ id: this.spec.id })\n wf.dry = p.dry === true\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 if (wf.dry) return 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 onPreview: settings.onPreview,\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 { type PreviewMethod, previewMethodFromSystemStats } from 'src/host/previewMethod.ts'\nimport {\n binaryFrameType,\n isPreviewFrameType,\n type ParsedPreviewFrame,\n parseBinaryWsFrame,\n parsePreviewFrame,\n} 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 isIgnoredWsEventType,\n isRoutedWsEventType,\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\ntype LatentPreview = { promptID: Maybe<PromptID>; receivedAt: number_Timestamp; blob: Blob; url: string }\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 /** false only when a requirement is known missing; an undecided one passes with a warning (manager.matchRequirements) */\n matchRequirements = (requirements: Requirements[]): boolean => this.manager.matchRequirements(requirements)\n\n /** `missing` (known not installed, the only ones to queue for install) and `undecided` (the lists cannot say) */\n checkRequirements = (requirements: Requirements[]): { missing: Requirements[]; undecided: Requirements[] } =>\n this.manager.checkRequirements(requirements)\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 /** a repeat interrupt for the same running prompt inside this window reuses the first request */\n interruptCoalesceMs = 3000\n private _lastInterrupt: { promptID: PromptID | null; at: number; req: Promise<void> } | null = null\n\n /** interrupt the CURRENTLY RUNNING prompt. A burst of /interrupt posts can make the ComfyUI\n * python process quit, so repeats for the same prompt are coalesced into one request */\n interrupt = (): Promise<void> => {\n const now = Date.now()\n const last = this._lastInterrupt\n if (last != null && last.promptID === this.activePromptID && now - last.at < this.interruptCoalesceMs)\n return last.req\n const req = this.postJSON_('/interrupt', {})\n this._lastInterrupt = { promptID: this.activePromptID, at: now, req }\n // a failed request must not swallow the retry\n req.catch(() => {\n if (this._lastInterrupt?.req === req) this._lastInterrupt = null\n })\n return req\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 `--preview-method` this host was launched with, read from `GET /system_stats`.\n * `'none'` (ComfyUI's default) means no live preview frame will ever arrive; null = the host\n * does not publish its launch flags (a cloud host), so only a run can tell */\n fetchPreviewMethod = async (): Promise<PreviewMethod | null> => {\n const res = await this.fetch('/system_stats', {})\n if (!res.ok) throw new Error(`GET /system_stats failed: ${res.status}`)\n return previewMethodFromSystemStats(await res.json())\n }\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 last raw preview frame; `latentPreview` decodes it only when read */\n private _latentFrame: Maybe<{ data: ArrayBuffer; promptID: Maybe<PromptID>; receivedAt: number_Timestamp }> = null\n private _latentPreview: Maybe<LatentPreview> = null\n\n /** the latent image beeing generated, in case you want to display it. Built on read: a\n * session that never reads it never decodes a frame nor holds an object url */\n get latentPreview(): Maybe<LatentPreview> {\n if (this._latentPreview != null || this._latentFrame == null) return this._latentPreview\n const frame = parsePreviewFrame(this._latentFrame.data)\n const blob = new Blob([frame.bytes], { type: frame.mime })\n this._latentPreview = {\n blob,\n url: URL.createObjectURL(blob),\n receivedAt: this._latentFrame.receivedAt,\n promptID: this._latentFrame.promptID,\n }\n return this._latentPreview\n }\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 /** event types we already complained about on this connection (one log per type, no\n * spam); both sets clear when the server assigns a new session id */\n private _unknownBinaryFrameTypes = new Set<number>()\n private _unknownWsEventTypes = new Set<string>()\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 /** a type 1 or 4 frame. Parsed only when someone wants it, in this order (architecture.md,\n * Live previews): the ws saver's output, the pre-registration buffer, the run's onPreview,\n * the host hook. Nobody listening = the frame is kept by reference and never copied */\n private onPreviewFrame(data: ArrayBuffer): void {\n let parsed: ParsedPreviewFrame | null = null\n const frame = (): ParsedPreviewFrame => (parsed ??= parsePreviewFrame(data))\n const promptID = this.activePromptID\n const activeExec = promptID != null ? this.executions.get(promptID) : null\n // OUTPUT, not preview: while a SaveImageWebsocket node executes, each preview-kind\n // frame IS one output image (frames follow their 'executing' message on the same\n // socket, architecture.md item 14)\n if (activeExec?.wsOutputNodeExecuting)\n return activeExec.onWsImageOutput({ bytes: frame().bytes, mime: frame().mime })\n // pre-registration window: ws messages can beat the POST /prompt response, and an\n // ephemeral output frame in that window would be the ONLY copy of the image. Buffer it\n // IN ORDER with the json messages; ComfyExecution.onCreate replays the queue and decides\n // output-vs-preview from the state at replay time\n const pending = promptID != null ? this._pendingMsgs.get(promptID) : undefined\n if (pending != null)\n pending.push({\n type: 'binary_preview_frame',\n bytes: frame().bytes,\n mime: frame().mime,\n metadata: frame().metadata,\n })\n // the object url REGISTRY holds a strong ref to its blob until revoked, and a sampler\n // emits one frame per step: revoke the outgoing one or a long session retains every latent\n if (this._latentPreview != null) URL.revokeObjectURL(this._latentPreview.url)\n this._latentPreview = null\n this._latentFrame = { data, promptID, receivedAt: Date.now() as number_Timestamp }\n if (activeExec?.onPreview != null) activeExec.onPreviewFrame(frame())\n if (this.onLatentPreview != null) this.onLatentPreview({ bytes: frame().bytes, mime: frame().mime, promptID })\n }\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 if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data)\n const frame = parseBinaryWsFrame(e.data)\n 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 let msg_: unknown = JSON.parse(String(e.data))\n\n // ----- routed, ignored by name, or unknown (architecture.md, ws events) -----\n const rec = typeof msg_ === 'object' && msg_ != null ? msg_ : null\n const eventType = rec != null && 'type' in rec && typeof rec.type === 'string' ? rec.type : null\n if (eventType != null && isIgnoredWsEventType(eventType)) return\n if (eventType == null || !isRoutedWsEventType(eventType)) {\n const key = eventType ?? '<no type>'\n if (this._unknownWsEventTypes.has(key)) return\n this._unknownWsEventTypes.add(key)\n console.error(\n `🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`,\n )\n return\n }\n\n // the reconnect resend of the running node carries no prompt_id (server.py websocket_handler)\n if (eventType === 'executing' && this.activePromptID != null && rec != null) {\n const data: unknown = Reflect.get(rec, 'data')\n if (typeof data === 'object' && data != null && !('prompt_id' in data))\n msg_ = { type: eventType, data: { ...data, prompt_id: this.activePromptID } }\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) {\n this._unknownWsEventTypes.clear()\n this._unknownBinaryFrameTypes.clear()\n this.onSession?.(msg.data.sid)\n }\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_interrupted' ||\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 }\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 DB.modelRows = knownModelList\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 /** every model row, the ones sharing a name included (knownModels keeps the last) */\n modelRows: 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 /** the serve web ui's LLM configs (prompt enhancer), one json per config */\n resolveFromLlmConfigs(relativePath: string): AbsolutePath {\n return asAbsolutePath(join(this.baseFolder, 'llm-configs', 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","import { existsSync, readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, join } from 'pathe'\n\n/**\n * the examples/ folder shipped in the npm tarball, resolved from THIS module's\n * own location (NEVER cwd): walking up to the nearest NAMED package.json finds\n * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/ and from\n * this repo's src/. Returns null when the examples are absent (a consumer may\n * prune the folder) or when the nearest named package is not comfy-ts (the lib\n * was inlined into someone else's bundle — its examples are not on disk); no\n * package.json all the way up is a broken install and throws.\n */\nexport function bundledExamplesDir(moduleUrl: string = import.meta.url): string | null {\n let dir = dirname(fileURLToPath(moduleUrl))\n let prev = ''\n while (dir !== prev) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n let pkg: { name?: string } = {}\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n } catch {\n // a malformed package.json on the walk (someone's broken fixture\n // dir) must not take the whole TUI down; treat as unnamed\n }\n if (pkg.name === 'comfy-ts') {\n const examples = join(dir, 'examples')\n return existsSync(examples) ? examples : null\n }\n if (pkg.name != null) return null\n }\n prev = dir\n dir = dirname(dir)\n }\n throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`)\n}\n\n/**\n * absolute path of a bundled `examples/images/` input image, e.g.\n * `exampleImagePath('bear_1024x1024.jpg')` — the out-of-the-box default for\n * i2i/i2v example image vars, valid from this repo AND from a consumer's\n * node_modules/comfy-ts/. Loud throw naming the path when the file is missing\n * or the package's examples/ folder was pruned.\n */\nexport function exampleImagePath(name: string): string {\n return bundledExampleFile('images', name)\n}\n\n/** the same for a bundled `examples/media/` audio or video file, e.g.\n * `exampleMediaPath('sine_440hz_3s.flac')` — the default of audio and video example vars */\nexport function exampleMediaPath(name: string): string {\n return bundledExampleFile('media', name)\n}\n\nfunction bundledExampleFile(folder: 'images' | 'media', name: string): string {\n const examples = bundledExamplesDir()\n if (examples == null) {\n throw new Error(\n `[comfy-ts] cannot resolve bundled example file '${name}': the package's examples/ folder is not on disk`,\n )\n }\n const abs = join(examples, folder, name)\n if (!existsSync(abs)) throw new Error(`[comfy-ts] bundled example file not found: ${abs}`)\n return abs\n}\n","// THE name gate for every serve route that turns a url segment into a file path.\n// SECURITY-CRITICAL and deliberately shared: handle() decodes per segment, so\n// `%2F` arrives as a real `/` while the segment count still looks right. One\n// function, because a second regex somewhere else is a second traversal hole.\n\n/** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */\nexport function validStoreName(raw: string): string | null {\n const name = raw.trim()\n // length cap: past it the fs answers ENAMETOOLONG as a raw 500\n if (name.length > 100) return null\n return /^[\\w][\\w .-]*$/.test(name) ? name : null\n}\n\n/** a save prefix becomes a PATH under outputs/, so every segment goes through the same gate:\n * it cannot climb out, and it cannot be absolute. Lives here, not on ServeApp, because the\n * settings READER validates it too, a hand-written settings file never met the PUT route. */\nexport function validSavePrefix(raw: string): string | null {\n const clean = raw.trim().replaceAll('\\\\', '/')\n if (clean === '') return ''\n // an ABSOLUTE path is refused, not quietly re-rooted: dropping the leading slash turned\n // '/etc' into 'etc' under outputs/, which is safe but is not what the writer asked for\n if (clean.startsWith('/') || /^[a-z]:/i.test(clean)) return null\n // the whole path is capped, not only each segment: 3000 valid two-char segments passed and\n // then broke that module's saving for good with an unopenable path\n if (clean.length > 200) return null\n const segments = clean.split('/').filter((s) => s !== '')\n if (segments.length === 0 || segments.some((s) => validStoreName(s) == null)) return null\n return segments.join('/')\n}\n","// the master prompts of the web ui's prompt enhancer, as FILES:\n// `.comfy-ts/prompt-enhancers/<name>.md`, the drafts model applied to prose.\n// markdown, not json: these are hand-edited paragraphs, and a json string field\n// would be one escaped line. The FILENAME is the identity (a rename is a write\n// plus a delete); validStoreName is the same gate the draft routes use.\n// NODE-ONLY (fs): the web entry never touches this folder, and a workflow reads\n// it through promptEnhancerPresets() to offer the same texts as var presets.\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'pathe'\nimport { validStoreName } from 'src/utils/safeName.ts'\nimport type { VarPresetSpec } from 'src/vars/presets.ts'\n\nconst EXT = '.md'\n\nexport type PromptEnhancer = { name: string; text: string }\n\nexport function promptEnhancersDir(): string {\n return comfyts.resolveFromPromptEnhancers('')\n}\n\nfunction promptEnhancerPath(name: string): string | null {\n const safe = validStoreName(name)\n return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`)\n}\n\n/** the shipped starting point. It is a FILE from the first read on, so it can be edited\n * on disk like everything else, the browser ships no copy of this text */\nconst SEED: PromptEnhancer = {\n name: 'refine-krea2-prompt',\n text: `You rewrite image prompts for krea2 turbo, a distilled 8 step text to image model whose text encoder reads flowing natural language. Long detailed prompts give it the best images. Your job is to serve the VISION behind the user's line: take what they wrote and expand it into the picture they were already imagining but did not type.\n\nRewrite it into ONE paragraph a reader could picture with their eyes closed:\n\n- every subject, action, color and spatial relation the user wrote survives, in their own words wherever those words already work. Nothing is dropped, nothing is swapped for something easier.\n- expand the vision, never replace it. Add the visual facts a camera would have to resolve anyway: what each subject looks like, lighting, palette, material and texture, camera angle and distance, framing and composition, background, depth of field, mood, and the signature of the medium itself (visible brushstrokes, film grain, cel shading, stippling, halftone, airbrush gradients, paper texture).\n- choose the style before you write, and keep the choosing invisible. Weigh two or three mediums and lighting setups, pick the one that best serves the input, then write only the result. If they named a medium (photo of, illustration of, 3D render of, painting of, sketch of), that medium is fixed.\n- attach every attribute to its own subject, so nothing bleeds: one clause per figure carrying its features, clothes, pose and action. Spatial words stay grounded: left foreground, upper center, behind, resting on, knee deep in.\n- an input that is already dense gets polished and finished, not inflated. Keep its phrasing and its direction, add only what is genuinely missing.\n- plain descriptive english. Flowing sentences and comma separated descriptive clauses both read well; disconnected keyword soup does not. No praise words, never \"masterpiece\", \"8k\", \"highly detailed\", \"award winning\", \"trending on\". The model is steered by what you name, not by what you forbid.\n- text that must appear inside the image is spelled out in \"quotes\", exactly as it should be rendered.\n- roughly 60 to 150 words, one paragraph, no lists, no headings, no quotes around the result itself.\n- never write a negative (\"- ...\") line or a comment (\"// ...\") line: the panel keeps the user's own and adds them back after your prompt.\n\nAnswer with the rewritten prompt and nothing else: no preamble, no explanation.\n`,\n}\n\n/** seeds ONCE, on an absent folder, then lists. An emptied folder stays empty: the seed is a\n * starting point, not a file the store keeps restoring */\nexport function listPromptEnhancers(): PromptEnhancer[] {\n if (!existsSync(promptEnhancersDir())) writePromptEnhancer(SEED.name, SEED.text)\n return readPromptEnhancers()\n}\n\n/** the PURE read: no seeding, no writing. What a workflow calls at define time, since importing\n * a module must never create files in someone's project */\nexport function readPromptEnhancers(): PromptEnhancer[] {\n const dir = promptEnhancersDir()\n if (!existsSync(dir)) return []\n const out: PromptEnhancer[] = []\n for (const file of readdirSync(dir).sort()) {\n if (!file.endsWith(EXT)) continue\n const name = file.slice(0, -EXT.length)\n if (validStoreName(name) == null) continue\n // one unreadable entry (a DIRECTORY called *.md, a permission problem) must not take the\n // whole route down: it is skipped loudly, the rest still list\n try {\n out.push({ name, text: readFileSync(join(dir, file), 'utf8') })\n } catch (e) {\n console.error(`[serve] prompt enhancer '${name}' unreadable, skipped:`, e)\n }\n }\n return out\n}\n\n/**\n * the same master prompts, shaped for `v.text(x, { presets })` / `v.prompt`: file name → text.\n * The point is that ONE library of texts serves the ✨ enhancer and every var that wants them,\n * so a paragraph you tuned in the panel is offered by the workflow too, with no copy.\n * Empty when the folder is absent, so a var keeps whatever presets it declares inline.\n */\nexport function promptEnhancerPresets(): VarPresetSpec {\n const out: VarPresetSpec = {}\n for (const e of readPromptEnhancers()) out[e.name] = e.text\n return out\n}\n\nexport function writePromptEnhancer(name: string, text: string): string | null {\n const path = promptEnhancerPath(name)\n if (path == null) return null\n mkdirSync(promptEnhancersDir(), { recursive: true })\n writeFileSync(path, text)\n return path\n}\n\n/** a missing file is still a success: the caller asked for it to be gone, and it is */\nexport function deletePromptEnhancer(name: string): boolean {\n const path = promptEnhancerPath(name)\n if (path == null) return false\n if (existsSync(path)) rmSync(path)\n return true\n}\n","// contract between the TUI and workflow modules: the TUI sets this env var\n// before importing a module; example files also use `import.meta.main` to\n// only self-run when executed directly.\nexport const COMFY_TS_TUI_ENV = 'COMFY_TS_TUI'\n\nexport function isTuiActive(): boolean {\n return process.env[COMFY_TS_TUI_ENV] === '1'\n}\n","/**\n * comfy-ts — type-safe ComfyUI workflow creation and execution (NODE entry)\n * @packageDocumentation\n */\nimport { setDefaultComfyStorage } from 'src/storage/ComfyStorage.ts'\nimport { createNodeStorage } from 'src/storage/nodeStorage.ts'\n\n// entry side effect: node 20/21 dist consumers have no getBuiltinModule\n// autodetect, so the node backend installs here (architecture item 13)\nsetDefaultComfyStorage(createNodeStorage())\n\nexport * from 'src/coreExports.ts'\n\n// node-only surface: fs-backed example assets + the TUI env contract\nexport { exampleImagePath, exampleMediaPath } from 'src/exampleAssets.ts'\n// the prompt-enhancer library on disk, offered as var presets (fs, so never in the web entry)\nexport { promptEnhancerPresets, readPromptEnhancers, type PromptEnhancer } from 'src/promptEnhancers.ts'\nexport { isTuiActive } from 'src/cli/tui-env.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,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